context.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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 <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "common/vlog.h"
  9. #include "llvm/ADT/Sequence.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/decl_name_stack.h"
  12. #include "toolchain/check/eval.h"
  13. #include "toolchain/check/import_ref.h"
  14. #include "toolchain/check/inst_block_stack.h"
  15. #include "toolchain/check/merge.h"
  16. #include "toolchain/diagnostics/diagnostic_emitter.h"
  17. #include "toolchain/lex/tokenized_buffer.h"
  18. #include "toolchain/parse/node_ids.h"
  19. #include "toolchain/parse/node_kind.h"
  20. #include "toolchain/sem_ir/builtin_kind.h"
  21. #include "toolchain/sem_ir/file.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/inst.h"
  24. #include "toolchain/sem_ir/inst_kind.h"
  25. #include "toolchain/sem_ir/typed_insts.h"
  26. namespace Carbon::Check {
  27. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  28. const Parse::Tree& parse_tree, SemIR::File& sem_ir,
  29. llvm::raw_ostream* vlog_stream)
  30. : tokens_(&tokens),
  31. emitter_(&emitter),
  32. parse_tree_(&parse_tree),
  33. sem_ir_(&sem_ir),
  34. vlog_stream_(vlog_stream),
  35. node_stack_(parse_tree, vlog_stream),
  36. inst_block_stack_("inst_block_stack_", sem_ir, vlog_stream),
  37. param_and_arg_refs_stack_(sem_ir, vlog_stream, node_stack_),
  38. args_type_info_stack_("args_type_info_stack_", sem_ir, vlog_stream),
  39. decl_name_stack_(this),
  40. scope_stack_(sem_ir_->identifiers()) {
  41. // Map the builtin `<error>` and `type` type constants to their corresponding
  42. // special `TypeId` values.
  43. type_ids_for_type_constants_.insert(
  44. {SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinError),
  45. SemIR::TypeId::Error});
  46. type_ids_for_type_constants_.insert(
  47. {SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinTypeType),
  48. SemIR::TypeId::TypeType});
  49. }
  50. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  51. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  52. std::string);
  53. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  54. return false;
  55. }
  56. auto Context::VerifyOnFinish() -> void {
  57. // Information in all the various context objects should be cleaned up as
  58. // various pieces of context go out of scope. At this point, nothing should
  59. // remain.
  60. // node_stack_ will still contain top-level entities.
  61. scope_stack_.VerifyOnFinish();
  62. inst_block_stack_.VerifyOnFinish();
  63. param_and_arg_refs_stack_.VerifyOnFinish();
  64. }
  65. auto Context::AddInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  66. -> SemIR::InstId {
  67. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  68. CARBON_VLOG() << "AddInst: " << loc_id_and_inst.inst << "\n";
  69. auto const_id = TryEvalInst(*this, inst_id, loc_id_and_inst.inst);
  70. if (const_id.is_constant()) {
  71. CARBON_VLOG() << "Constant: " << loc_id_and_inst.inst << " -> "
  72. << const_id.inst_id() << "\n";
  73. constant_values().Set(inst_id, const_id);
  74. }
  75. return inst_id;
  76. }
  77. auto Context::AddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId {
  78. auto inst_id = AddInstInNoBlock(loc_id_and_inst);
  79. inst_block_stack_.AddInstId(inst_id);
  80. return inst_id;
  81. }
  82. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  83. -> SemIR::InstId {
  84. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  85. CARBON_VLOG() << "AddPlaceholderInst: " << loc_id_and_inst.inst << "\n";
  86. constant_values().Set(inst_id, SemIR::ConstantId::Invalid);
  87. return inst_id;
  88. }
  89. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  90. -> SemIR::InstId {
  91. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  92. inst_block_stack_.AddInstId(inst_id);
  93. return inst_id;
  94. }
  95. auto Context::AddConstant(SemIR::Inst inst, bool is_symbolic)
  96. -> SemIR::ConstantId {
  97. auto const_id = constants().GetOrAdd(inst, is_symbolic);
  98. CARBON_VLOG() << "AddConstant: " << inst << "\n";
  99. return const_id;
  100. }
  101. auto Context::AddInstAndPush(SemIR::LocIdAndInst loc_id_and_inst) -> void {
  102. auto inst_id = AddInst(loc_id_and_inst);
  103. node_stack_.Push(loc_id_and_inst.loc_id.node_id(), inst_id);
  104. }
  105. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  106. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  107. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  108. CARBON_VLOG() << "ReplaceInst: " << inst_id << " -> " << loc_id_and_inst.inst
  109. << "\n";
  110. // Redo evaluation. This is only safe to do if this instruction has not
  111. // already been used as a constant, which is the caller's responsibility to
  112. // ensure.
  113. auto const_id = TryEvalInst(*this, inst_id, loc_id_and_inst.inst);
  114. if (const_id.is_constant()) {
  115. CARBON_VLOG() << "Constant: " << loc_id_and_inst.inst << " -> "
  116. << const_id.inst_id() << "\n";
  117. }
  118. constant_values().Set(inst_id, const_id);
  119. }
  120. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  121. SemIR::Inst inst) -> void {
  122. sem_ir().insts().Set(inst_id, inst);
  123. CARBON_VLOG() << "ReplaceInst: " << inst_id << " -> " << inst << "\n";
  124. // Redo evaluation. This is only safe to do if this instruction has not
  125. // already been used as a constant, which is the caller's responsibility to
  126. // ensure.
  127. auto const_id = TryEvalInst(*this, inst_id, inst);
  128. if (const_id.is_constant()) {
  129. CARBON_VLOG() << "Constant: " << inst << " -> " << const_id.inst_id()
  130. << "\n";
  131. }
  132. constant_values().Set(inst_id, const_id);
  133. }
  134. auto Context::AddImportRef(SemIR::ImportIRInst import_ir_inst)
  135. -> SemIR::InstId {
  136. auto import_ref_id = AddPlaceholderInstInNoBlock(
  137. SemIR::ImportRefUnloaded{import_ir_insts().Add(import_ir_inst)});
  138. // We can't insert this instruction into whatever block we happen to be in,
  139. // because this function is typically called by name lookup in the middle of
  140. // an otherwise unknown checking step. But we need to add the instruction
  141. // somewhere, because it's referenced by other instructions and needs to be
  142. // visible in textual IR. Adding it to the file block is arbitrary but is the
  143. // best place we have right now.
  144. //
  145. // TODO: Consider adding a dedicated block for import_refs.
  146. inst_block_stack().AddInstIdToFileBlock(import_ref_id);
  147. return import_ref_id;
  148. }
  149. auto Context::DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def)
  150. -> void {
  151. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  152. "Duplicate name being declared in the same scope.");
  153. CARBON_DIAGNOSTIC(NameDeclPrevious, Note,
  154. "Name is previously declared here.");
  155. emitter_->Build(dup_def, NameDeclDuplicate)
  156. .Note(prev_def, NameDeclPrevious)
  157. .Emit();
  158. }
  159. auto Context::DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id)
  160. -> void {
  161. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  162. SemIR::NameId);
  163. emitter_->Emit(loc, NameNotFound, name_id);
  164. }
  165. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  166. DiagnosticBuilder& builder) -> void {
  167. const auto& class_info = classes().Get(class_id);
  168. CARBON_CHECK(!class_info.is_defined()) << "Class is not incomplete";
  169. if (class_info.definition_id.is_valid()) {
  170. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  171. "Class is incomplete within its definition.");
  172. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  173. } else {
  174. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  175. "Class was forward declared here.");
  176. builder.Note(class_info.decl_id, ClassForwardDeclaredHere);
  177. }
  178. }
  179. auto Context::NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  180. DiagnosticBuilder& builder) -> void {
  181. const auto& interface_info = interfaces().Get(interface_id);
  182. CARBON_CHECK(!interface_info.is_defined()) << "Interface is not incomplete";
  183. if (interface_info.is_being_defined()) {
  184. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  185. "Interface is currently being defined.");
  186. builder.Note(interface_info.definition_id,
  187. InterfaceUndefinedWithinDefinition);
  188. } else {
  189. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  190. "Interface was forward declared here.");
  191. builder.Note(interface_info.decl_id, InterfaceForwardDeclaredHere);
  192. }
  193. }
  194. auto Context::AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id)
  195. -> void {
  196. if (auto existing = scope_stack().LookupOrAddName(name_id, target_id);
  197. existing.is_valid()) {
  198. DiagnoseDuplicateName(target_id, existing);
  199. }
  200. }
  201. auto Context::LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  202. SemIR::NameScopeId scope_id,
  203. bool mark_imports_used) -> SemIR::InstId {
  204. if (!scope_id.is_valid()) {
  205. // Look for a name in the current scope only. There are two cases where the
  206. // name would be in an outer scope:
  207. //
  208. // - The name is the sole component of the declared name:
  209. //
  210. // class A;
  211. // fn F() {
  212. // class A;
  213. // }
  214. //
  215. // In this case, the inner A is not the same class as the outer A, so
  216. // lookup should not find the outer A.
  217. //
  218. // - The name is a qualifier of some larger declared name:
  219. //
  220. // class A { class B; }
  221. // fn F() {
  222. // class A.B {}
  223. // }
  224. //
  225. // In this case, we're not in the correct scope to define a member of
  226. // class A, so we should reject, and we achieve this by not finding the
  227. // name A from the outer scope.
  228. return scope_stack().LookupInCurrentScope(name_id);
  229. } else {
  230. // We do not look into `extend`ed scopes here. A qualified name in a
  231. // declaration must specify the exact scope in which the name was originally
  232. // introduced:
  233. //
  234. // base class A { fn F(); }
  235. // class B { extend base: A; }
  236. //
  237. // // Error, no `F` in `B`.
  238. // fn B.F() {}
  239. return LookupNameInExactScope(loc_id, name_id, name_scopes().Get(scope_id),
  240. mark_imports_used);
  241. }
  242. }
  243. auto Context::LookupUnqualifiedName(Parse::NodeId node_id,
  244. SemIR::NameId name_id) -> SemIR::InstId {
  245. // TODO: Check for shadowed lookup results.
  246. // Find the results from enclosing lexical scopes. These will be combined with
  247. // results from non-lexical scopes such as namespaces and classes.
  248. auto [lexical_result, non_lexical_scopes] =
  249. scope_stack().LookupInEnclosingScopes(name_id);
  250. // Walk the non-lexical scopes and perform lookups into each of them.
  251. for (auto [index, name_scope_id] : llvm::reverse(non_lexical_scopes)) {
  252. if (auto non_lexical_result =
  253. LookupQualifiedName(node_id, name_id, name_scope_id,
  254. /*required=*/false);
  255. non_lexical_result.is_valid()) {
  256. return non_lexical_result;
  257. }
  258. }
  259. if (lexical_result.is_valid()) {
  260. return lexical_result;
  261. }
  262. // We didn't find anything at all.
  263. DiagnoseNameNotFound(node_id, name_id);
  264. return SemIR::InstId::BuiltinError;
  265. }
  266. // Handles lookup through the import_ir_scopes for LookupNameInExactScope.
  267. static auto LookupInImportIRScopes(Context& context, SemIRLoc loc,
  268. SemIR::NameId name_id,
  269. const SemIR::NameScope& scope,
  270. bool mark_imports_used) -> SemIR::InstId {
  271. auto identifier_id = name_id.AsIdentifierId();
  272. llvm::StringRef identifier;
  273. if (identifier_id.is_valid()) {
  274. identifier = context.identifiers().Get(identifier_id);
  275. }
  276. DiagnosticAnnotationScope annotate_diagnostics(
  277. &context.emitter(), [&](auto& builder) {
  278. CARBON_DIAGNOSTIC(InNameLookup, Note, "In name lookup for `{0}`.",
  279. SemIR::NameId);
  280. builder.Note(loc, InNameLookup, name_id);
  281. });
  282. auto result_id = SemIR::InstId::Invalid;
  283. for (auto [import_ir_id, import_scope_id] : scope.import_ir_scopes) {
  284. auto& import_ir = context.import_irs().Get(import_ir_id);
  285. // Determine the NameId in the import IR.
  286. SemIR::NameId import_name_id = name_id;
  287. if (identifier_id.is_valid()) {
  288. auto import_identifier_id =
  289. import_ir.sem_ir->identifiers().Lookup(identifier);
  290. if (!import_identifier_id.is_valid()) {
  291. // Name doesn't exist in the import IR.
  292. continue;
  293. }
  294. import_name_id = SemIR::NameId::ForIdentifier(import_identifier_id);
  295. }
  296. // Look up the name in the import scope.
  297. const auto& import_scope =
  298. import_ir.sem_ir->name_scopes().Get(import_scope_id);
  299. auto it = import_scope.names.find(import_name_id);
  300. if (it == import_scope.names.end()) {
  301. // Name doesn't exist in the import scope.
  302. continue;
  303. }
  304. auto import_inst_id =
  305. context.AddImportRef({.ir_id = import_ir_id, .inst_id = it->second});
  306. if (result_id.is_valid()) {
  307. MergeImportRef(context, import_inst_id, result_id);
  308. } else {
  309. LoadImportRef(context, import_inst_id,
  310. mark_imports_used ? loc : SemIR::LocId::Invalid);
  311. result_id = import_inst_id;
  312. }
  313. }
  314. return result_id;
  315. }
  316. auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  317. const SemIR::NameScope& scope,
  318. bool mark_imports_used) -> SemIR::InstId {
  319. if (auto it = scope.names.find(name_id); it != scope.names.end()) {
  320. LoadImportRef(*this, it->second,
  321. mark_imports_used ? loc : SemIR::LocId::Invalid);
  322. return it->second;
  323. }
  324. if (!scope.import_ir_scopes.empty()) {
  325. return LookupInImportIRScopes(*this, loc, name_id, scope,
  326. mark_imports_used);
  327. }
  328. return SemIR::InstId::Invalid;
  329. }
  330. auto Context::LookupQualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  331. SemIR::NameScopeId scope_id, bool required)
  332. -> SemIR::InstId {
  333. llvm::SmallVector<SemIR::NameScopeId> scope_ids = {scope_id};
  334. auto result_id = SemIR::InstId::Invalid;
  335. bool has_error = false;
  336. // Walk this scope and, if nothing is found here, the scopes it extends.
  337. while (!scope_ids.empty()) {
  338. const auto& scope = name_scopes().Get(scope_ids.pop_back_val());
  339. has_error |= scope.has_error;
  340. auto scope_result_id = LookupNameInExactScope(node_id, name_id, scope,
  341. /*mark_imports_used=*/true);
  342. if (!scope_result_id.is_valid()) {
  343. // Nothing found in this scope: also look in its extended scopes.
  344. auto extended = llvm::reverse(scope.extended_scopes);
  345. scope_ids.append(extended.begin(), extended.end());
  346. continue;
  347. }
  348. // If this is our second lookup result, diagnose an ambiguity.
  349. if (result_id.is_valid()) {
  350. // TODO: This is currently not reachable because the only scope that can
  351. // extend is a class scope, and it can only extend a single base class.
  352. // Add test coverage once this is possible.
  353. CARBON_DIAGNOSTIC(
  354. NameAmbiguousDueToExtend, Error,
  355. "Ambiguous use of name `{0}` found in multiple extended scopes.",
  356. SemIR::NameId);
  357. emitter_->Emit(node_id, NameAmbiguousDueToExtend, name_id);
  358. // TODO: Add notes pointing to the scopes.
  359. return SemIR::InstId::BuiltinError;
  360. }
  361. result_id = scope_result_id;
  362. }
  363. if (required && !result_id.is_valid()) {
  364. if (!has_error) {
  365. DiagnoseNameNotFound(node_id, name_id);
  366. }
  367. return SemIR::InstId::BuiltinError;
  368. }
  369. return result_id;
  370. }
  371. // Returns the scope of the Core package, or Invalid if it's not found.
  372. //
  373. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  374. // name lookup to find it.
  375. static auto GetCorePackage(Context& context, SemIRLoc loc)
  376. -> SemIR::NameScopeId {
  377. auto core_ident_id = context.identifiers().Add("Core");
  378. auto packaging = context.parse_tree().packaging_directive();
  379. if (packaging && packaging->names.package_id == core_ident_id) {
  380. return SemIR::NameScopeId::Package;
  381. }
  382. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  383. // Look up `package.Core`.
  384. auto core_inst_id = context.LookupNameInExactScope(
  385. loc, core_name_id, context.name_scopes().Get(SemIR::NameScopeId::Package),
  386. /*mark_imports_used=*/true);
  387. if (!core_inst_id.is_valid()) {
  388. context.DiagnoseNameNotFound(loc, core_name_id);
  389. return SemIR::NameScopeId::Invalid;
  390. }
  391. // We expect it to be a namespace.
  392. if (auto namespace_inst =
  393. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  394. return namespace_inst->name_scope_id;
  395. }
  396. // TODO: This should really diagnose the name issue.
  397. context.DiagnoseNameNotFound(loc, core_name_id);
  398. return SemIR::NameScopeId::Invalid;
  399. }
  400. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  401. -> SemIR::InstId {
  402. auto core_package_id = GetCorePackage(*this, loc);
  403. if (!core_package_id.is_valid()) {
  404. return SemIR::InstId::BuiltinError;
  405. }
  406. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  407. auto inst_id =
  408. LookupNameInExactScope(loc, name_id, name_scopes().Get(core_package_id),
  409. /*mark_imports_used=*/true);
  410. if (!inst_id.is_valid()) {
  411. DiagnoseNameNotFound(loc, name_id);
  412. return SemIR::InstId::BuiltinError;
  413. }
  414. // Look through import_refs and aliases.
  415. return constant_values().Get(inst_id).inst_id();
  416. }
  417. template <typename BranchNode, typename... Args>
  418. static auto AddDominatedBlockAndBranchImpl(Context& context,
  419. Parse::NodeId node_id, Args... args)
  420. -> SemIR::InstBlockId {
  421. if (!context.inst_block_stack().is_current_block_reachable()) {
  422. return SemIR::InstBlockId::Unreachable;
  423. }
  424. auto block_id = context.inst_blocks().AddDefaultValue();
  425. context.AddInst({node_id, BranchNode{block_id, args...}});
  426. return block_id;
  427. }
  428. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  429. -> SemIR::InstBlockId {
  430. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  431. }
  432. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  433. SemIR::InstId arg_id)
  434. -> SemIR::InstBlockId {
  435. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  436. arg_id);
  437. }
  438. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  439. SemIR::InstId cond_id)
  440. -> SemIR::InstBlockId {
  441. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  442. cond_id);
  443. }
  444. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  445. -> void {
  446. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  447. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  448. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  449. if (inst_block_stack().is_current_block_reachable()) {
  450. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  451. new_block_id = inst_blocks().AddDefaultValue();
  452. }
  453. AddInst({node_id, SemIR::Branch{new_block_id}});
  454. }
  455. inst_block_stack().Pop();
  456. }
  457. inst_block_stack().Push(new_block_id);
  458. }
  459. auto Context::AddConvergenceBlockWithArgAndPush(
  460. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  461. -> SemIR::InstId {
  462. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  463. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  464. for (auto arg_id : block_args) {
  465. if (inst_block_stack().is_current_block_reachable()) {
  466. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  467. new_block_id = inst_blocks().AddDefaultValue();
  468. }
  469. AddInst({node_id, SemIR::BranchWithArg{new_block_id, arg_id}});
  470. }
  471. inst_block_stack().Pop();
  472. }
  473. inst_block_stack().Push(new_block_id);
  474. // Acquire the result value.
  475. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  476. return AddInst({node_id, SemIR::BlockArg{result_type_id, new_block_id}});
  477. }
  478. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  479. SemIR::InstId cond_id,
  480. SemIR::InstId if_true,
  481. SemIR::InstId if_false)
  482. -> void {
  483. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  484. // Determine the constant result based on the condition value.
  485. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  486. auto cond_const_id = constant_values().Get(cond_id);
  487. if (!cond_const_id.is_template()) {
  488. // Symbolic or non-constant condition means a non-constant result.
  489. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  490. cond_const_id.inst_id())) {
  491. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  492. : if_false);
  493. } else {
  494. CARBON_CHECK(cond_const_id == SemIR::ConstantId::Error)
  495. << "Unexpected constant branch condition.";
  496. const_id = SemIR::ConstantId::Error;
  497. }
  498. if (const_id.is_constant()) {
  499. CARBON_VLOG() << "Constant: " << insts().Get(select_id) << " -> "
  500. << const_id.inst_id() << "\n";
  501. constant_values().Set(select_id, const_id);
  502. }
  503. }
  504. // Add the current code block to the enclosing function.
  505. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  506. CARBON_CHECK(!inst_block_stack().empty()) << "no current code block";
  507. if (return_scope_stack().empty()) {
  508. CARBON_CHECK(node_id.is_valid())
  509. << "No current function, but node_id not provided";
  510. TODO(node_id,
  511. "Control flow expressions are currently only supported inside "
  512. "functions.");
  513. return;
  514. }
  515. if (!inst_block_stack().is_current_block_reachable()) {
  516. // Don't include unreachable blocks in the function.
  517. return;
  518. }
  519. auto function_id =
  520. insts()
  521. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  522. .function_id;
  523. functions()
  524. .Get(function_id)
  525. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  526. }
  527. auto Context::is_current_position_reachable() -> bool {
  528. if (!inst_block_stack().is_current_block_reachable()) {
  529. return false;
  530. }
  531. // Our current position is at the end of a reachable block. That position is
  532. // reachable unless the previous instruction is a terminator instruction.
  533. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  534. if (block_contents.empty()) {
  535. return true;
  536. }
  537. const auto& last_inst = insts().Get(block_contents.back());
  538. return last_inst.kind().terminator_kind() !=
  539. SemIR::TerminatorKind::Terminator;
  540. }
  541. auto Context::FinalizeGlobalInit() -> void {
  542. inst_block_stack().PushGlobalInit();
  543. if (!inst_block_stack().PeekCurrentBlockContents().empty()) {
  544. AddInst({Parse::NodeId::Invalid, SemIR::Return{}});
  545. // Pop the GlobalInit block here to finalize it.
  546. inst_block_stack().Pop();
  547. // __global_init is only added if there are initialization instructions.
  548. auto name_id = sem_ir().identifiers().Add("__global_init");
  549. sem_ir().functions().Add(
  550. {.name_id = SemIR::NameId::ForIdentifier(name_id),
  551. .enclosing_scope_id = SemIR::NameScopeId::Package,
  552. .decl_id = SemIR::InstId::Invalid,
  553. .implicit_param_refs_id = SemIR::InstBlockId::Empty,
  554. .param_refs_id = SemIR::InstBlockId::Empty,
  555. .return_type_id = SemIR::TypeId::Invalid,
  556. .return_slot_id = SemIR::InstId::Invalid,
  557. .body_block_ids = {SemIR::InstBlockId::GlobalInit}});
  558. } else {
  559. inst_block_stack().PopGlobalInit();
  560. }
  561. }
  562. namespace {
  563. // Worklist-based type completion mechanism.
  564. //
  565. // When attempting to complete a type, we may find other types that also need to
  566. // be completed: types nested within that type, and the value representation of
  567. // the type. In order to complete a type without recursing arbitrarily deeply,
  568. // we use a worklist of tasks:
  569. //
  570. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  571. // nested within a type to the work list.
  572. // - A `BuildValueRepr` step computes the value representation for a
  573. // type, once all of its nested types are complete, and marks the type as
  574. // complete.
  575. class TypeCompleter {
  576. public:
  577. TypeCompleter(
  578. Context& context,
  579. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  580. diagnoser)
  581. : context_(context), diagnoser_(diagnoser) {}
  582. // Attempts to complete the given type. Returns true if it is now complete,
  583. // false if it could not be completed.
  584. auto Complete(SemIR::TypeId type_id) -> bool {
  585. Push(type_id);
  586. while (!work_list_.empty()) {
  587. if (!ProcessStep()) {
  588. return false;
  589. }
  590. }
  591. return true;
  592. }
  593. private:
  594. // Adds `type_id` to the work list, if it's not already complete.
  595. auto Push(SemIR::TypeId type_id) -> void {
  596. if (!context_.types().IsComplete(type_id)) {
  597. work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes});
  598. }
  599. }
  600. // Runs the next step.
  601. auto ProcessStep() -> bool {
  602. auto [type_id, phase] = work_list_.back();
  603. // We might have enqueued the same type more than once. Just skip the
  604. // type if it's already complete.
  605. if (context_.types().IsComplete(type_id)) {
  606. work_list_.pop_back();
  607. return true;
  608. }
  609. auto inst_id = context_.types().GetInstId(type_id);
  610. auto inst = context_.insts().Get(inst_id);
  611. auto old_work_list_size = work_list_.size();
  612. switch (phase) {
  613. case Phase::AddNestedIncompleteTypes:
  614. if (!AddNestedIncompleteTypes(inst)) {
  615. return false;
  616. }
  617. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  618. << "AddNestedIncompleteTypes should not remove work items";
  619. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  620. break;
  621. case Phase::BuildValueRepr: {
  622. auto value_rep = BuildValueRepr(type_id, inst);
  623. context_.sem_ir().CompleteType(type_id, value_rep);
  624. CARBON_CHECK(old_work_list_size == work_list_.size())
  625. << "BuildValueRepr should not change work items";
  626. work_list_.pop_back();
  627. // Also complete the value representation type, if necessary. This
  628. // should never fail: the value representation shouldn't require any
  629. // additional nested types to be complete.
  630. if (!context_.types().IsComplete(value_rep.type_id)) {
  631. work_list_.push_back({value_rep.type_id, Phase::BuildValueRepr});
  632. }
  633. // For a pointer representation, the pointee also needs to be complete.
  634. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  635. if (value_rep.type_id == SemIR::TypeId::Error) {
  636. break;
  637. }
  638. auto pointee_type_id =
  639. context_.sem_ir().GetPointeeType(value_rep.type_id);
  640. if (!context_.types().IsComplete(pointee_type_id)) {
  641. work_list_.push_back({pointee_type_id, Phase::BuildValueRepr});
  642. }
  643. }
  644. break;
  645. }
  646. }
  647. return true;
  648. }
  649. // Adds any types nested within `type_inst` that need to be complete for
  650. // `type_inst` to be complete to our work list.
  651. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  652. CARBON_KIND_SWITCH(type_inst) {
  653. case CARBON_KIND(SemIR::ArrayType inst): {
  654. Push(inst.element_type_id);
  655. break;
  656. }
  657. case CARBON_KIND(SemIR::StructType inst): {
  658. for (auto field_id : context_.inst_blocks().Get(inst.fields_id)) {
  659. Push(context_.insts()
  660. .GetAs<SemIR::StructTypeField>(field_id)
  661. .field_type_id);
  662. }
  663. break;
  664. }
  665. case CARBON_KIND(SemIR::TupleType inst): {
  666. for (auto element_type_id :
  667. context_.type_blocks().Get(inst.elements_id)) {
  668. Push(element_type_id);
  669. }
  670. break;
  671. }
  672. case CARBON_KIND(SemIR::ClassType inst): {
  673. auto& class_info = context_.classes().Get(inst.class_id);
  674. if (!class_info.is_defined()) {
  675. if (diagnoser_) {
  676. auto builder = (*diagnoser_)();
  677. context_.NoteIncompleteClass(inst.class_id, builder);
  678. builder.Emit();
  679. }
  680. return false;
  681. }
  682. Push(class_info.object_repr_id);
  683. break;
  684. }
  685. case CARBON_KIND(SemIR::ConstType inst): {
  686. Push(inst.inner_id);
  687. break;
  688. }
  689. default:
  690. break;
  691. }
  692. return true;
  693. }
  694. // Makes an empty value representation, which is used for types that have no
  695. // state, such as empty structs and tuples.
  696. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  697. return {.kind = SemIR::ValueRepr::None,
  698. .type_id = context_.GetTupleType({})};
  699. }
  700. // Makes a value representation that uses pass-by-copy, copying the given
  701. // type.
  702. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  703. SemIR::ValueRepr::AggregateKind aggregate_kind =
  704. SemIR::ValueRepr::NotAggregate) const
  705. -> SemIR::ValueRepr {
  706. return {.kind = SemIR::ValueRepr::Copy,
  707. .aggregate_kind = aggregate_kind,
  708. .type_id = rep_id};
  709. }
  710. // Makes a value representation that uses pass-by-address with the given
  711. // pointee type.
  712. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  713. SemIR::ValueRepr::AggregateKind aggregate_kind =
  714. SemIR::ValueRepr::NotAggregate) const
  715. -> SemIR::ValueRepr {
  716. // TODO: Should we add `const` qualification to `pointee_id`?
  717. return {.kind = SemIR::ValueRepr::Pointer,
  718. .aggregate_kind = aggregate_kind,
  719. .type_id = context_.GetPointerType(pointee_id)};
  720. }
  721. // Gets the value representation of a nested type, which should already be
  722. // complete.
  723. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  724. CARBON_CHECK(context_.types().IsComplete(nested_type_id))
  725. << "Nested type should already be complete";
  726. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  727. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown)
  728. << "Complete type should have a value representation";
  729. return value_rep;
  730. };
  731. auto BuildBuiltinValueRepr(SemIR::TypeId type_id,
  732. SemIR::Builtin builtin) const -> SemIR::ValueRepr {
  733. switch (builtin.builtin_kind) {
  734. case SemIR::BuiltinKind::TypeType:
  735. case SemIR::BuiltinKind::Error:
  736. case SemIR::BuiltinKind::Invalid:
  737. case SemIR::BuiltinKind::BoolType:
  738. case SemIR::BuiltinKind::IntType:
  739. case SemIR::BuiltinKind::FloatType:
  740. case SemIR::BuiltinKind::NamespaceType:
  741. case SemIR::BuiltinKind::FunctionType:
  742. case SemIR::BuiltinKind::BoundMethodType:
  743. case SemIR::BuiltinKind::WitnessType:
  744. return MakeCopyValueRepr(type_id);
  745. case SemIR::BuiltinKind::StringType:
  746. // TODO: Decide on string value semantics. This should probably be a
  747. // custom value representation carrying a pointer and size or
  748. // similar.
  749. return MakePointerValueRepr(type_id);
  750. }
  751. llvm_unreachable("All builtin kinds were handled above");
  752. }
  753. auto BuildAnyImportRefValueRepr(SemIR::TypeId type_id,
  754. SemIR::AnyImportRef import_ref) const
  755. -> SemIR::ValueRepr {
  756. auto import_ir_inst =
  757. context_.import_ir_insts().Get(import_ref.import_ir_inst_id);
  758. const auto& import_ir =
  759. context_.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  760. auto import_inst = import_ir->insts().Get(import_ir_inst.inst_id);
  761. CARBON_CHECK(!import_inst.Is<SemIR::AnyImportRef>())
  762. << "If ImportRef can point at another, this would be recursive.";
  763. return BuildValueRepr(type_id, import_inst);
  764. }
  765. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  766. SemIR::TypeId elementwise_rep,
  767. bool same_as_object_rep) const
  768. -> SemIR::ValueRepr {
  769. SemIR::ValueRepr::AggregateKind aggregate_kind =
  770. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  771. : SemIR::ValueRepr::ValueAggregate;
  772. if (num_elements == 1) {
  773. // The value representation for a struct or tuple with a single element
  774. // is a struct or tuple containing the value representation of the
  775. // element.
  776. // TODO: Consider doing the same whenever `elementwise_rep` is
  777. // sufficiently small.
  778. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  779. }
  780. // For a struct or tuple with multiple fields, we use a pointer
  781. // to the elementwise value representation.
  782. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  783. }
  784. auto BuildStructTypeValueRepr(SemIR::TypeId type_id,
  785. SemIR::StructType struct_type) const
  786. -> SemIR::ValueRepr {
  787. // TODO: Share more code with tuples.
  788. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  789. if (fields.empty()) {
  790. return MakeEmptyValueRepr();
  791. }
  792. // Find the value representation for each field, and construct a struct
  793. // of value representations.
  794. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  795. value_rep_fields.reserve(fields.size());
  796. bool same_as_object_rep = true;
  797. for (auto field_id : fields) {
  798. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  799. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  800. if (field_value_rep.type_id != field.field_type_id) {
  801. same_as_object_rep = false;
  802. field.field_type_id = field_value_rep.type_id;
  803. // TODO: Use `TryEvalInst` to form this value.
  804. field_id = context_
  805. .AddConstant(field, context_.constant_values()
  806. .Get(context_.types().GetInstId(
  807. field.field_type_id))
  808. .is_symbolic())
  809. .inst_id();
  810. }
  811. value_rep_fields.push_back(field_id);
  812. }
  813. auto value_rep = same_as_object_rep
  814. ? type_id
  815. : context_.GetStructType(
  816. context_.inst_blocks().Add(value_rep_fields));
  817. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  818. same_as_object_rep);
  819. }
  820. auto BuildTupleTypeValueRepr(SemIR::TypeId type_id,
  821. SemIR::TupleType tuple_type) const
  822. -> SemIR::ValueRepr {
  823. // TODO: Share more code with structs.
  824. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  825. if (elements.empty()) {
  826. return MakeEmptyValueRepr();
  827. }
  828. // Find the value representation for each element, and construct a tuple
  829. // of value representations.
  830. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  831. value_rep_elements.reserve(elements.size());
  832. bool same_as_object_rep = true;
  833. for (auto element_type_id : elements) {
  834. auto element_value_rep = GetNestedValueRepr(element_type_id);
  835. if (element_value_rep.type_id != element_type_id) {
  836. same_as_object_rep = false;
  837. }
  838. value_rep_elements.push_back(element_value_rep.type_id);
  839. }
  840. auto value_rep = same_as_object_rep
  841. ? type_id
  842. : context_.GetTupleType(value_rep_elements);
  843. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  844. same_as_object_rep);
  845. }
  846. // Builds and returns the value representation for the given type. All nested
  847. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  848. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  849. -> SemIR::ValueRepr {
  850. CARBON_KIND_SWITCH(inst) {
  851. case SemIR::AdaptDecl::Kind:
  852. case SemIR::AddrOf::Kind:
  853. case SemIR::AddrPattern::Kind:
  854. case SemIR::ArrayIndex::Kind:
  855. case SemIR::ArrayInit::Kind:
  856. case SemIR::Assign::Kind:
  857. case SemIR::AssociatedConstantDecl::Kind:
  858. case SemIR::AssociatedEntity::Kind:
  859. case SemIR::BaseDecl::Kind:
  860. case SemIR::BindAlias::Kind:
  861. case SemIR::BindName::Kind:
  862. case SemIR::BindValue::Kind:
  863. case SemIR::BlockArg::Kind:
  864. case SemIR::BoolLiteral::Kind:
  865. case SemIR::BoundMethod::Kind:
  866. case SemIR::Branch::Kind:
  867. case SemIR::BranchIf::Kind:
  868. case SemIR::BranchWithArg::Kind:
  869. case SemIR::Call::Kind:
  870. case SemIR::ClassDecl::Kind:
  871. case SemIR::ClassElementAccess::Kind:
  872. case SemIR::ClassInit::Kind:
  873. case SemIR::Converted::Kind:
  874. case SemIR::Deref::Kind:
  875. case SemIR::FacetTypeAccess::Kind:
  876. case SemIR::FieldDecl::Kind:
  877. case SemIR::FunctionDecl::Kind:
  878. case SemIR::ImplDecl::Kind:
  879. case SemIR::ImportRefUnloaded::Kind:
  880. case SemIR::InitializeFrom::Kind:
  881. case SemIR::InterfaceDecl::Kind:
  882. case SemIR::InterfaceWitness::Kind:
  883. case SemIR::InterfaceWitnessAccess::Kind:
  884. case SemIR::IntLiteral::Kind:
  885. case SemIR::NameRef::Kind:
  886. case SemIR::Namespace::Kind:
  887. case SemIR::Param::Kind:
  888. case SemIR::RealLiteral::Kind:
  889. case SemIR::Return::Kind:
  890. case SemIR::ReturnExpr::Kind:
  891. case SemIR::SpliceBlock::Kind:
  892. case SemIR::StringLiteral::Kind:
  893. case SemIR::StructAccess::Kind:
  894. case SemIR::StructTypeField::Kind:
  895. case SemIR::StructLiteral::Kind:
  896. case SemIR::StructInit::Kind:
  897. case SemIR::StructValue::Kind:
  898. case SemIR::Temporary::Kind:
  899. case SemIR::TemporaryStorage::Kind:
  900. case SemIR::TupleAccess::Kind:
  901. case SemIR::TupleIndex::Kind:
  902. case SemIR::TupleLiteral::Kind:
  903. case SemIR::TupleInit::Kind:
  904. case SemIR::TupleValue::Kind:
  905. case SemIR::UnaryOperatorNot::Kind:
  906. case SemIR::ValueAsRef::Kind:
  907. case SemIR::ValueOfInitializer::Kind:
  908. case SemIR::VarStorage::Kind:
  909. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  910. case SemIR::ArrayType::Kind: {
  911. // For arrays, it's convenient to always use a pointer representation,
  912. // even when the array has zero or one element, in order to support
  913. // indexing.
  914. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  915. }
  916. case SemIR::ImportRefLoaded::Kind:
  917. case SemIR::ImportRefUsed::Kind:
  918. return BuildAnyImportRefValueRepr(type_id,
  919. inst.As<SemIR::AnyImportRef>());
  920. case CARBON_KIND(SemIR::StructType struct_type): {
  921. return BuildStructTypeValueRepr(type_id, struct_type);
  922. }
  923. case CARBON_KIND(SemIR::TupleType tuple_type): {
  924. return BuildTupleTypeValueRepr(type_id, tuple_type);
  925. }
  926. case CARBON_KIND(SemIR::ClassType class_type): {
  927. // The value representation for a class is a pointer to the object
  928. // representation.
  929. // TODO: Support customized value representations for classes.
  930. // TODO: Pick a better value representation when possible.
  931. return MakePointerValueRepr(
  932. context_.classes().Get(class_type.class_id).object_repr_id,
  933. SemIR::ValueRepr::ObjectAggregate);
  934. }
  935. case SemIR::InterfaceType::Kind: {
  936. // TODO: Should we model the value representation as a witness?
  937. return MakeEmptyValueRepr();
  938. }
  939. case CARBON_KIND(SemIR::Builtin builtin): {
  940. return BuildBuiltinValueRepr(type_id, builtin);
  941. }
  942. case SemIR::AssociatedEntityType::Kind:
  943. case SemIR::BindSymbolicName::Kind:
  944. case SemIR::IntType::Kind:
  945. case SemIR::PointerType::Kind:
  946. case SemIR::UnboundElementType::Kind:
  947. return MakeCopyValueRepr(type_id);
  948. case CARBON_KIND(SemIR::ConstType const_type): {
  949. // The value representation of `const T` is the same as that of `T`.
  950. // Objects are not modifiable through their value representations.
  951. return GetNestedValueRepr(const_type.inner_id);
  952. }
  953. }
  954. }
  955. enum class Phase : int8_t {
  956. // The next step is to add nested types to the list of types to complete.
  957. AddNestedIncompleteTypes,
  958. // The next step is to build the value representation for the type.
  959. BuildValueRepr,
  960. };
  961. struct WorkItem {
  962. SemIR::TypeId type_id;
  963. Phase phase;
  964. };
  965. Context& context_;
  966. llvm::SmallVector<WorkItem> work_list_;
  967. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  968. diagnoser_;
  969. };
  970. } // namespace
  971. auto Context::TryToCompleteType(
  972. SemIR::TypeId type_id,
  973. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  974. -> bool {
  975. return TypeCompleter(*this, diagnoser).Complete(type_id);
  976. }
  977. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  978. -> SemIR::TypeId {
  979. CARBON_CHECK(constant_id.is_constant())
  980. << "Canonicalizing non-constant type: " << constant_id;
  981. auto [it, added] = type_ids_for_type_constants_.insert(
  982. {constant_id, SemIR::TypeId::Invalid});
  983. if (added) {
  984. it->second = types().Add({.constant_id = constant_id});
  985. }
  986. return it->second;
  987. }
  988. template <typename InstT, typename... EachArgT>
  989. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  990. -> SemIR::TypeId {
  991. // TODO: Remove inst_id parameter from TryEvalInst.
  992. return context.GetTypeIdForTypeConstant(
  993. TryEvalInst(context, SemIR::InstId::Invalid,
  994. InstT{SemIR::TypeId::TypeType, each_arg...}));
  995. }
  996. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  997. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  998. }
  999. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  1000. -> SemIR::TypeId {
  1001. // TODO: Deduplicate the type block here. Currently requesting the same tuple
  1002. // type more than once will create multiple type blocks, all but one of which
  1003. // is unused.
  1004. return GetTypeImpl<SemIR::TupleType>(*this, type_blocks().Add(type_ids));
  1005. }
  1006. auto Context::GetAssociatedEntityType(SemIR::InterfaceId interface_id,
  1007. SemIR::TypeId entity_type_id)
  1008. -> SemIR::TypeId {
  1009. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_id,
  1010. entity_type_id);
  1011. }
  1012. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  1013. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  1014. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  1015. // To keep client code simpler, complete builtin types before returning them.
  1016. bool complete = TryToCompleteType(type_id);
  1017. CARBON_CHECK(complete) << "Failed to complete builtin type";
  1018. return type_id;
  1019. }
  1020. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1021. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  1022. }
  1023. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  1024. SemIR::TypeId element_type_id)
  1025. -> SemIR::TypeId {
  1026. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1027. element_type_id);
  1028. }
  1029. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  1030. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  1031. return const_type->inner_id;
  1032. }
  1033. return type_id;
  1034. }
  1035. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1036. node_stack_.PrintForStackDump(output);
  1037. inst_block_stack_.PrintForStackDump(output);
  1038. param_and_arg_refs_stack_.PrintForStackDump(output);
  1039. args_type_info_stack_.PrintForStackDump(output);
  1040. }
  1041. } // namespace Carbon::Check