context.cpp 42 KB

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