context.cpp 42 KB

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