context.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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/context.h"
  5. #include <optional>
  6. #include <string>
  7. #include <utility>
  8. #include "common/check.h"
  9. #include "common/vlog.h"
  10. #include "llvm/ADT/Sequence.h"
  11. #include "toolchain/check/decl_name_stack.h"
  12. #include "toolchain/check/eval.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/generic_region_stack.h"
  15. #include "toolchain/check/import.h"
  16. #include "toolchain/check/import_ref.h"
  17. #include "toolchain/check/inst_block_stack.h"
  18. #include "toolchain/check/merge.h"
  19. #include "toolchain/check/type_completion.h"
  20. #include "toolchain/diagnostics/diagnostic_emitter.h"
  21. #include "toolchain/diagnostics/format_providers.h"
  22. #include "toolchain/lex/tokenized_buffer.h"
  23. #include "toolchain/parse/node_ids.h"
  24. #include "toolchain/parse/node_kind.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/formatter.h"
  27. #include "toolchain/sem_ir/generic.h"
  28. #include "toolchain/sem_ir/ids.h"
  29. #include "toolchain/sem_ir/import_ir.h"
  30. #include "toolchain/sem_ir/inst.h"
  31. #include "toolchain/sem_ir/inst_kind.h"
  32. #include "toolchain/sem_ir/name_scope.h"
  33. #include "toolchain/sem_ir/type_info.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. namespace Carbon::Check {
  36. Context::Context(DiagnosticEmitter* emitter,
  37. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter,
  38. SemIR::File* sem_ir, int imported_ir_count, int total_ir_count,
  39. llvm::raw_ostream* vlog_stream)
  40. : emitter_(emitter),
  41. tree_and_subtrees_getter_(tree_and_subtrees_getter),
  42. sem_ir_(sem_ir),
  43. vlog_stream_(vlog_stream),
  44. node_stack_(sem_ir->parse_tree(), vlog_stream),
  45. inst_block_stack_("inst_block_stack_", *sem_ir, vlog_stream),
  46. pattern_block_stack_("pattern_block_stack_", *sem_ir, vlog_stream),
  47. param_and_arg_refs_stack_(*sem_ir, vlog_stream, node_stack_),
  48. args_type_info_stack_("args_type_info_stack_", *sem_ir, vlog_stream),
  49. decl_name_stack_(this),
  50. scope_stack_(sem_ir_),
  51. vtable_stack_("vtable_stack_", *sem_ir, vlog_stream),
  52. global_init_(this),
  53. region_stack_(
  54. [this](SemIRLoc loc, std::string label) { TODO(loc, label); }) {
  55. // Prepare fields which relate to the number of IRs available for import.
  56. import_irs().Reserve(imported_ir_count);
  57. import_ir_constant_values_.reserve(imported_ir_count);
  58. check_ir_map_.resize(total_ir_count, SemIR::ImportIRId::None);
  59. // Map the builtin `<error>` and `type` type constants to their corresponding
  60. // special `TypeId` values.
  61. type_ids_for_type_constants_.Insert(
  62. SemIR::ConstantId::ForConcreteConstant(SemIR::ErrorInst::SingletonInstId),
  63. SemIR::ErrorInst::SingletonTypeId);
  64. type_ids_for_type_constants_.Insert(
  65. SemIR::ConstantId::ForConcreteConstant(SemIR::TypeType::SingletonInstId),
  66. SemIR::TypeType::SingletonTypeId);
  67. // TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
  68. // in the right places.
  69. generic_region_stack().Push();
  70. }
  71. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  72. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "semantics TODO: `{0}`", std::string);
  73. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  74. return false;
  75. }
  76. auto Context::VerifyOnFinish() -> void {
  77. // Information in all the various context objects should be cleaned up as
  78. // various pieces of context go out of scope. At this point, nothing should
  79. // remain.
  80. // node_stack_ will still contain top-level entities.
  81. inst_block_stack_.VerifyOnFinish();
  82. pattern_block_stack_.VerifyOnFinish();
  83. param_and_arg_refs_stack_.VerifyOnFinish();
  84. args_type_info_stack_.VerifyOnFinish();
  85. CARBON_CHECK(struct_type_fields_stack_.empty());
  86. // TODO: Add verification for decl_name_stack_ and
  87. // decl_introducer_state_stack_.
  88. scope_stack_.VerifyOnFinish();
  89. // TODO: Add verification for generic_region_stack_.
  90. }
  91. auto Context::GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst)
  92. -> SemIR::InstId {
  93. if (loc_id_and_inst.loc_id.is_implicit()) {
  94. auto const_id =
  95. TryEvalInst(*this, SemIR::InstId::None, loc_id_and_inst.inst);
  96. if (const_id.has_value()) {
  97. CARBON_VLOG("GetOrAddInst: constant: {0}\n", loc_id_and_inst.inst);
  98. return constant_values().GetInstId(const_id);
  99. }
  100. }
  101. // TODO: For an implicit instruction, this reattempts evaluation.
  102. return AddInst(loc_id_and_inst);
  103. }
  104. // Finish producing an instruction. Set its constant value, and register it in
  105. // any applicable instruction lists.
  106. auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
  107. GenericRegionStack::DependencyKind dep_kind =
  108. GenericRegionStack::DependencyKind::None;
  109. // If the instruction has a symbolic constant type, track that we need to
  110. // substitute into it.
  111. if (constant_values().DependsOnGenericParameter(
  112. types().GetConstantId(inst.type_id()))) {
  113. dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
  114. }
  115. // If the instruction has a constant value, compute it.
  116. auto const_id = TryEvalInst(*this, inst_id, inst);
  117. constant_values().Set(inst_id, const_id);
  118. if (const_id.is_constant()) {
  119. CARBON_VLOG("Constant: {0} -> {1}\n", inst,
  120. constant_values().GetInstId(const_id));
  121. // If the constant value is symbolic, track that we need to substitute into
  122. // it.
  123. if (constant_values().DependsOnGenericParameter(const_id)) {
  124. dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
  125. }
  126. }
  127. // Keep track of dependent instructions.
  128. if (dep_kind != GenericRegionStack::DependencyKind::None) {
  129. // TODO: Also check for template-dependent instructions.
  130. generic_region_stack().AddDependentInst(
  131. {.inst_id = inst_id, .kind = dep_kind});
  132. }
  133. }
  134. // Returns whether a parse node associated with an imported instruction of kind
  135. // `imported_kind` is usable as the location of a corresponding local
  136. // instruction of kind `local_kind`.
  137. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  138. SemIR::InstKind local_kind) -> bool {
  139. if (imported_kind == local_kind) {
  140. return true;
  141. }
  142. if (imported_kind == SemIR::ImportDecl::Kind &&
  143. local_kind == SemIR::Namespace::Kind) {
  144. static_assert(
  145. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  146. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  147. return true;
  148. }
  149. return false;
  150. }
  151. auto Context::CheckCompatibleImportedNodeKind(
  152. SemIR::ImportIRInstId imported_loc_id, SemIR::InstKind kind) -> void {
  153. auto& import_ir_inst = import_ir_insts().Get(imported_loc_id);
  154. const auto* import_ir = import_irs().Get(import_ir_inst.ir_id).sem_ir;
  155. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
  156. CARBON_CHECK(
  157. HasCompatibleImportedNodeKind(imported_kind, kind),
  158. "Node of kind {0} created with location of imported node of kind {1}",
  159. kind, imported_kind);
  160. }
  161. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  162. -> SemIR::InstId {
  163. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  164. CARBON_VLOG("AddPlaceholderInst: {0}\n", loc_id_and_inst.inst);
  165. constant_values().Set(inst_id, SemIR::ConstantId::None);
  166. return inst_id;
  167. }
  168. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  169. -> SemIR::InstId {
  170. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  171. inst_block_stack_.AddInstId(inst_id);
  172. return inst_id;
  173. }
  174. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  175. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  176. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  177. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, loc_id_and_inst.inst);
  178. FinishInst(inst_id, loc_id_and_inst.inst);
  179. }
  180. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  181. SemIR::Inst inst) -> void {
  182. sem_ir().insts().Set(inst_id, inst);
  183. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  184. FinishInst(inst_id, inst);
  185. }
  186. auto Context::ReplaceInstPreservingConstantValue(SemIR::InstId inst_id,
  187. SemIR::Inst inst) -> void {
  188. auto old_const_id = sem_ir().constant_values().Get(inst_id);
  189. sem_ir().insts().Set(inst_id, inst);
  190. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  191. auto new_const_id = TryEvalInst(*this, inst_id, inst);
  192. CARBON_CHECK(old_const_id == new_const_id);
  193. }
  194. auto Context::Finalize() -> void {
  195. // Pop information for the file-level scope.
  196. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  197. scope_stack().Pop();
  198. // Finalizes the list of exports on the IR.
  199. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  200. // Finalizes the ImportRef inst block.
  201. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  202. // Finalizes __global_init.
  203. global_init_.Finalize();
  204. }
  205. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  206. output << "Check::Context\n";
  207. // In a stack dump, this is probably indented by a tab. We treat that as 8
  208. // spaces then add a couple to indent past the Context label.
  209. constexpr int Indent = 10;
  210. node_stack_.PrintForStackDump(Indent, output);
  211. inst_block_stack_.PrintForStackDump(Indent, output);
  212. pattern_block_stack_.PrintForStackDump(Indent, output);
  213. param_and_arg_refs_stack_.PrintForStackDump(Indent, output);
  214. args_type_info_stack_.PrintForStackDump(Indent, output);
  215. }
  216. auto Context::DumpFormattedFile() const -> void {
  217. SemIR::Formatter formatter(sem_ir_);
  218. formatter.Print(llvm::errs());
  219. }
  220. } // namespace Carbon::Check