global_init.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/global_init.h"
  5. #include "toolchain/check/context.h"
  6. namespace Carbon::Check {
  7. auto GlobalInit::Resume() -> void {
  8. context_->inst_block_stack().Push(block_id_, block_);
  9. }
  10. auto GlobalInit::Suspend() -> void {
  11. // TODO: Consider splicing together blocks in order to avoid sizable copies
  12. // here.
  13. auto contents = context_->inst_block_stack().PeekCurrentBlockContents();
  14. block_.assign(contents.begin(), contents.end());
  15. block_id_ = context_->inst_block_stack().PeekOrAdd();
  16. context_->inst_block_stack().PopAndDiscard();
  17. }
  18. auto GlobalInit::Finalize() -> void {
  19. // __global_init is only added if there are initialization instructions.
  20. if (block_.empty() && block_id_ == SemIR::InstBlockId::GlobalInit) {
  21. return;
  22. }
  23. Resume();
  24. context_->AddInst<SemIR::Return>(Parse::NodeId::None, {});
  25. // Pop the GlobalInit block here to finalize it.
  26. context_->inst_block_stack().Pop();
  27. auto name_id = context_->sem_ir().identifiers().Add("__global_init");
  28. context_->sem_ir().set_global_ctor_id(context_->sem_ir().functions().Add(
  29. {{.name_id = SemIR::NameId::ForIdentifier(name_id),
  30. .parent_scope_id = SemIR::NameScopeId::Package,
  31. .generic_id = SemIR::GenericId::None,
  32. .first_param_node_id = Parse::NodeId::None,
  33. .last_param_node_id = Parse::NodeId::None,
  34. .pattern_block_id = SemIR::InstBlockId::Empty,
  35. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  36. .param_patterns_id = SemIR::InstBlockId::Empty,
  37. .call_params_id = SemIR::InstBlockId::Empty,
  38. .is_extern = false,
  39. .extern_library_id = SemIR::LibraryNameId::None,
  40. .non_owning_decl_id = SemIR::InstId::None,
  41. .first_owning_decl_id = SemIR::InstId::None},
  42. {.return_slot_pattern_id = SemIR::InstId::None,
  43. .body_block_ids = {SemIR::InstBlockId::GlobalInit}}}));
  44. }
  45. } // namespace Carbon::Check