context.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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/check/decl_name_stack.h"
  11. #include "toolchain/check/inst_block_stack.h"
  12. #include "toolchain/lex/tokenized_buffer.h"
  13. #include "toolchain/parse/node_kind.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/inst.h"
  17. #include "toolchain/sem_ir/inst_kind.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  21. const Parse::Tree& parse_tree, SemIR::File& sem_ir,
  22. llvm::raw_ostream* vlog_stream)
  23. : tokens_(&tokens),
  24. emitter_(&emitter),
  25. parse_tree_(&parse_tree),
  26. sem_ir_(&sem_ir),
  27. vlog_stream_(vlog_stream),
  28. node_stack_(parse_tree, vlog_stream),
  29. inst_block_stack_("inst_block_stack_", sem_ir, vlog_stream),
  30. params_or_args_stack_("params_or_args_stack_", sem_ir, vlog_stream),
  31. args_type_info_stack_("args_type_info_stack_", sem_ir, vlog_stream),
  32. decl_name_stack_(this) {
  33. // Inserts the "Error" and "Type" types as "used types" so that
  34. // canonicalization can skip them. We don't emit either for lowering.
  35. canonical_types_.insert({SemIR::InstId::BuiltinError, SemIR::TypeId::Error});
  36. canonical_types_.insert(
  37. {SemIR::InstId::BuiltinTypeType, SemIR::TypeId::TypeType});
  38. }
  39. auto Context::TODO(Parse::Node parse_node, std::string label) -> bool {
  40. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  41. std::string);
  42. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  43. return false;
  44. }
  45. auto Context::VerifyOnFinish() -> void {
  46. // Information in all the various context objects should be cleaned up as
  47. // various pieces of context go out of scope. At this point, nothing should
  48. // remain.
  49. // node_stack_ will still contain top-level entities.
  50. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  51. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  52. CARBON_CHECK(inst_block_stack_.empty()) << inst_block_stack_.size();
  53. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  54. }
  55. auto Context::AddInst(SemIR::Inst inst) -> SemIR::InstId {
  56. auto inst_id = inst_block_stack_.AddInst(inst);
  57. CARBON_VLOG() << "AddInst: " << inst << "\n";
  58. return inst_id;
  59. }
  60. auto Context::AddConstantInst(SemIR::Inst inst) -> SemIR::InstId {
  61. auto inst_id = insts().AddInNoBlock(inst);
  62. constants().Add(inst_id);
  63. CARBON_VLOG() << "AddConstantInst: " << inst << "\n";
  64. return inst_id;
  65. }
  66. auto Context::AddInstAndPush(Parse::Node parse_node, SemIR::Inst inst) -> void {
  67. auto inst_id = AddInst(inst);
  68. node_stack_.Push(parse_node, inst_id);
  69. }
  70. auto Context::DiagnoseDuplicateName(Parse::Node parse_node,
  71. SemIR::InstId prev_def_id) -> void {
  72. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  73. "Duplicate name being declared in the same scope.");
  74. CARBON_DIAGNOSTIC(NameDeclPrevious, Note,
  75. "Name is previously declared here.");
  76. auto prev_def = insts().Get(prev_def_id);
  77. emitter_->Build(parse_node, NameDeclDuplicate)
  78. .Note(prev_def.parse_node(), NameDeclPrevious)
  79. .Emit();
  80. }
  81. auto Context::DiagnoseNameNotFound(Parse::Node parse_node,
  82. SemIR::NameId name_id) -> void {
  83. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.", std::string);
  84. emitter_->Emit(parse_node, NameNotFound, names().GetFormatted(name_id).str());
  85. }
  86. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  87. DiagnosticBuilder& builder) -> void {
  88. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  89. "Class was forward declared here.");
  90. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  91. "Class is incomplete within its definition.");
  92. const auto& class_info = classes().Get(class_id);
  93. CARBON_CHECK(!class_info.is_defined()) << "Class is not incomplete";
  94. if (class_info.definition_id.is_valid()) {
  95. builder.Note(insts().Get(class_info.definition_id).parse_node(),
  96. ClassIncompleteWithinDefinition);
  97. } else {
  98. builder.Note(insts().Get(class_info.decl_id).parse_node(),
  99. ClassForwardDeclaredHere);
  100. }
  101. }
  102. auto Context::AddPackageImports(Parse::Node import_node,
  103. IdentifierId package_id,
  104. llvm::ArrayRef<const SemIR::File*> sem_irs,
  105. bool has_load_error) -> void {
  106. CARBON_CHECK(has_load_error || !sem_irs.empty())
  107. << "There should be either a load error or at least one IR.";
  108. auto name_id = SemIR::NameId::ForIdentifier(package_id);
  109. SemIR::CrossRefIRId first_id(cross_ref_irs().size());
  110. for (const auto* sem_ir : sem_irs) {
  111. cross_ref_irs().Add(sem_ir);
  112. }
  113. if (has_load_error) {
  114. cross_ref_irs().Add(nullptr);
  115. }
  116. SemIR::CrossRefIRId last_id(cross_ref_irs().size() - 1);
  117. auto type_id = GetBuiltinType(SemIR::BuiltinKind::NamespaceType);
  118. auto inst_id = AddInst(SemIR::Import{.parse_node = import_node,
  119. .type_id = type_id,
  120. .first_cross_ref_ir_id = first_id,
  121. .last_cross_ref_ir_id = last_id});
  122. if (name_id.is_valid()) {
  123. // Add the import to lookup. Should always succeed because imports will be
  124. // uniquely named.
  125. AddNameToLookup(import_node, name_id, inst_id);
  126. // Add a name for formatted output. This isn't used in name lookup in order
  127. // to reduce indirection, but it's separate from the Import because it
  128. // otherwise fits in an Inst.
  129. AddInst(SemIR::BindName{.parse_node = import_node,
  130. .type_id = type_id,
  131. .name_id = name_id,
  132. .value_id = inst_id});
  133. } else {
  134. // TODO: All names from the current package should be added.
  135. }
  136. }
  137. auto Context::AddNameToLookup(Parse::Node name_node, SemIR::NameId name_id,
  138. SemIR::InstId target_id) -> void {
  139. if (current_scope().names.insert(name_id).second) {
  140. // TODO: Reject if we previously performed a failed lookup for this name in
  141. // this scope or a scope nested within it.
  142. auto& lexical_results = name_lookup_[name_id];
  143. CARBON_CHECK(lexical_results.empty() ||
  144. lexical_results.back().scope_index < current_scope_index())
  145. << "Failed to clean up after scope nested within the current scope";
  146. lexical_results.push_back(
  147. {.node_id = target_id, .scope_index = current_scope_index()});
  148. } else {
  149. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back().node_id);
  150. }
  151. }
  152. auto Context::LookupNameInDecl(Parse::Node parse_node, SemIR::NameId name_id,
  153. SemIR::NameScopeId scope_id) -> SemIR::InstId {
  154. if (scope_id == SemIR::NameScopeId::Invalid) {
  155. // Look for a name in the current scope only. There are two cases where the
  156. // name would be in an outer scope:
  157. //
  158. // - The name is the sole component of the declared name:
  159. //
  160. // class A;
  161. // fn F() {
  162. // class A;
  163. // }
  164. //
  165. // In this case, the inner A is not the same class as the outer A, so
  166. // lookup should not find the outer A.
  167. //
  168. // - The name is a qualifier of some larger declared name:
  169. //
  170. // class A { class B; }
  171. // fn F() {
  172. // class A.B {}
  173. // }
  174. //
  175. // In this case, we're not in the correct scope to define a member of
  176. // class A, so we should reject, and we achieve this by not finding the
  177. // name A from the outer scope.
  178. if (auto name_it = name_lookup_.find(name_id);
  179. name_it != name_lookup_.end()) {
  180. CARBON_CHECK(!name_it->second.empty())
  181. << "Should have been erased: " << names().GetFormatted(name_id);
  182. auto result = name_it->second.back();
  183. if (result.scope_index == current_scope_index()) {
  184. return result.node_id;
  185. }
  186. }
  187. return SemIR::InstId::Invalid;
  188. } else {
  189. // TODO: Once we support `extend`, do not look into `extend`ed scopes here,
  190. // following the same logic as above.
  191. return LookupQualifiedName(parse_node, name_id, scope_id,
  192. /*required=*/false);
  193. }
  194. }
  195. auto Context::LookupUnqualifiedName(Parse::Node parse_node,
  196. SemIR::NameId name_id) -> SemIR::InstId {
  197. // TODO: Check for shadowed lookup results.
  198. // Find the results from enclosing lexical scopes. These will be combined with
  199. // results from non-lexical scopes such as namespaces and classes.
  200. llvm::ArrayRef<LexicalLookupResult> lexical_results;
  201. if (auto name_it = name_lookup_.find(name_id);
  202. name_it != name_lookup_.end()) {
  203. lexical_results = name_it->second;
  204. CARBON_CHECK(!lexical_results.empty())
  205. << "Should have been erased: " << names().GetFormatted(name_id);
  206. }
  207. // Walk the non-lexical scopes and perform lookups into each of them.
  208. for (auto [index, name_scope_id] : llvm::reverse(non_lexical_scope_stack_)) {
  209. // If the innermost lexical result is within this non-lexical scope, then
  210. // it shadows all further non-lexical results and we're done.
  211. if (!lexical_results.empty() &&
  212. lexical_results.back().scope_index > index) {
  213. return lexical_results.back().node_id;
  214. }
  215. auto non_lexical_result =
  216. LookupQualifiedName(parse_node, name_id, name_scope_id,
  217. /*required=*/false);
  218. if (non_lexical_result.is_valid()) {
  219. return non_lexical_result;
  220. }
  221. }
  222. if (!lexical_results.empty()) {
  223. return lexical_results.back().node_id;
  224. }
  225. // We didn't find anything at all.
  226. DiagnoseNameNotFound(parse_node, name_id);
  227. return SemIR::InstId::BuiltinError;
  228. }
  229. auto Context::LookupQualifiedName(Parse::Node parse_node, SemIR::NameId name_id,
  230. SemIR::NameScopeId scope_id, bool required)
  231. -> SemIR::InstId {
  232. CARBON_CHECK(scope_id.is_valid()) << "No scope to perform lookup into";
  233. const auto& scope = name_scopes().Get(scope_id);
  234. auto it = scope.find(name_id);
  235. if (it == scope.end()) {
  236. // TODO: Also perform lookups into `extend`ed scopes.
  237. if (required) {
  238. DiagnoseNameNotFound(parse_node, name_id);
  239. return SemIR::InstId::BuiltinError;
  240. }
  241. return SemIR::InstId::Invalid;
  242. }
  243. return it->second;
  244. }
  245. auto Context::PushScope(SemIR::InstId scope_inst_id,
  246. SemIR::NameScopeId scope_id) -> void {
  247. scope_stack_.push_back({.index = next_scope_index_,
  248. .scope_inst_id = scope_inst_id,
  249. .scope_id = scope_id});
  250. if (scope_id.is_valid()) {
  251. non_lexical_scope_stack_.push_back({next_scope_index_, scope_id});
  252. }
  253. // TODO: Handle this case more gracefully.
  254. CARBON_CHECK(next_scope_index_.index != std::numeric_limits<int32_t>::max())
  255. << "Ran out of scopes";
  256. ++next_scope_index_.index;
  257. }
  258. auto Context::PopScope() -> void {
  259. auto scope = scope_stack_.pop_back_val();
  260. for (const auto& str_id : scope.names) {
  261. auto it = name_lookup_.find(str_id);
  262. CARBON_CHECK(it->second.back().scope_index == scope.index)
  263. << "Inconsistent scope index for name " << names().GetFormatted(str_id);
  264. if (it->second.size() == 1) {
  265. // Erase names that no longer resolve.
  266. name_lookup_.erase(it);
  267. } else {
  268. it->second.pop_back();
  269. }
  270. }
  271. if (scope.scope_id.is_valid()) {
  272. CARBON_CHECK(non_lexical_scope_stack_.back().first == scope.index);
  273. non_lexical_scope_stack_.pop_back();
  274. }
  275. if (scope.has_returned_var) {
  276. CARBON_CHECK(!return_scope_stack_.empty());
  277. CARBON_CHECK(return_scope_stack_.back().returned_var.is_valid());
  278. return_scope_stack_.back().returned_var = SemIR::InstId::Invalid;
  279. }
  280. }
  281. auto Context::PopToScope(ScopeIndex index) -> void {
  282. while (current_scope_index() > index) {
  283. PopScope();
  284. }
  285. CARBON_CHECK(current_scope_index() == index)
  286. << "Scope index " << index << " does not enclose the current scope "
  287. << current_scope_index();
  288. }
  289. auto Context::SetReturnedVarOrGetExisting(SemIR::InstId inst_id)
  290. -> SemIR::InstId {
  291. CARBON_CHECK(!return_scope_stack_.empty()) << "`returned var` in no function";
  292. auto& returned_var = return_scope_stack_.back().returned_var;
  293. if (returned_var.is_valid()) {
  294. return returned_var;
  295. }
  296. returned_var = inst_id;
  297. CARBON_CHECK(!current_scope().has_returned_var)
  298. << "Scope has returned var but none is set";
  299. if (inst_id.is_valid()) {
  300. current_scope().has_returned_var = true;
  301. }
  302. return SemIR::InstId::Invalid;
  303. }
  304. auto Context::FollowNameRefs(SemIR::InstId inst_id) -> SemIR::InstId {
  305. while (auto name_ref = insts().Get(inst_id).TryAs<SemIR::NameRef>()) {
  306. inst_id = name_ref->value_id;
  307. }
  308. return inst_id;
  309. }
  310. auto Context::GetConstantValue(SemIR::InstId inst_id) -> SemIR::InstId {
  311. // TODO: The constant value of an instruction should be computed as we build
  312. // the instruction, or at least cached once computed.
  313. while (true) {
  314. auto inst = insts().Get(inst_id);
  315. switch (inst.kind()) {
  316. case SemIR::NameRef::Kind:
  317. inst_id = inst.As<SemIR::NameRef>().value_id;
  318. break;
  319. case SemIR::BindName::Kind:
  320. inst_id = inst.As<SemIR::BindName>().value_id;
  321. break;
  322. case SemIR::Field::Kind:
  323. case SemIR::FunctionDecl::Kind:
  324. return inst_id;
  325. default:
  326. // TODO: Handle the remaining cases.
  327. return SemIR::InstId::Invalid;
  328. }
  329. }
  330. }
  331. template <typename BranchNode, typename... Args>
  332. static auto AddDominatedBlockAndBranchImpl(Context& context,
  333. Parse::Node parse_node, Args... args)
  334. -> SemIR::InstBlockId {
  335. if (!context.inst_block_stack().is_current_block_reachable()) {
  336. return SemIR::InstBlockId::Unreachable;
  337. }
  338. auto block_id = context.inst_blocks().AddDefaultValue();
  339. context.AddInst(BranchNode{parse_node, block_id, args...});
  340. return block_id;
  341. }
  342. auto Context::AddDominatedBlockAndBranch(Parse::Node parse_node)
  343. -> SemIR::InstBlockId {
  344. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, parse_node);
  345. }
  346. auto Context::AddDominatedBlockAndBranchWithArg(Parse::Node parse_node,
  347. SemIR::InstId arg_id)
  348. -> SemIR::InstBlockId {
  349. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, parse_node,
  350. arg_id);
  351. }
  352. auto Context::AddDominatedBlockAndBranchIf(Parse::Node parse_node,
  353. SemIR::InstId cond_id)
  354. -> SemIR::InstBlockId {
  355. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, parse_node,
  356. cond_id);
  357. }
  358. auto Context::AddConvergenceBlockAndPush(Parse::Node parse_node, int num_blocks)
  359. -> void {
  360. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  361. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  362. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  363. if (inst_block_stack().is_current_block_reachable()) {
  364. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  365. new_block_id = inst_blocks().AddDefaultValue();
  366. }
  367. AddInst(SemIR::Branch{parse_node, new_block_id});
  368. }
  369. inst_block_stack().Pop();
  370. }
  371. inst_block_stack().Push(new_block_id);
  372. }
  373. auto Context::AddConvergenceBlockWithArgAndPush(
  374. Parse::Node parse_node, std::initializer_list<SemIR::InstId> block_args)
  375. -> SemIR::InstId {
  376. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  377. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  378. for (auto arg_id : block_args) {
  379. if (inst_block_stack().is_current_block_reachable()) {
  380. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  381. new_block_id = inst_blocks().AddDefaultValue();
  382. }
  383. AddInst(SemIR::BranchWithArg{parse_node, new_block_id, arg_id});
  384. }
  385. inst_block_stack().Pop();
  386. }
  387. inst_block_stack().Push(new_block_id);
  388. // Acquire the result value.
  389. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  390. return AddInst(SemIR::BlockArg{parse_node, result_type_id, new_block_id});
  391. }
  392. // Add the current code block to the enclosing function.
  393. auto Context::AddCurrentCodeBlockToFunction(Parse::Node parse_node) -> void {
  394. CARBON_CHECK(!inst_block_stack().empty()) << "no current code block";
  395. if (return_scope_stack().empty()) {
  396. CARBON_CHECK(parse_node.is_valid())
  397. << "No current function, but parse_node not provided";
  398. TODO(parse_node,
  399. "Control flow expressions are currently only supported inside "
  400. "functions.");
  401. return;
  402. }
  403. if (!inst_block_stack().is_current_block_reachable()) {
  404. // Don't include unreachable blocks in the function.
  405. return;
  406. }
  407. auto function_id =
  408. insts()
  409. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  410. .function_id;
  411. functions()
  412. .Get(function_id)
  413. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  414. }
  415. auto Context::is_current_position_reachable() -> bool {
  416. if (!inst_block_stack().is_current_block_reachable()) {
  417. return false;
  418. }
  419. // Our current position is at the end of a reachable block. That position is
  420. // reachable unless the previous instruction is a terminator instruction.
  421. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  422. if (block_contents.empty()) {
  423. return true;
  424. }
  425. const auto& last_inst = insts().Get(block_contents.back());
  426. return last_inst.kind().terminator_kind() !=
  427. SemIR::TerminatorKind::Terminator;
  428. }
  429. auto Context::ParamOrArgStart() -> void { params_or_args_stack_.Push(); }
  430. auto Context::ParamOrArgComma() -> void {
  431. ParamOrArgSave(node_stack_.PopExpr());
  432. }
  433. auto Context::ParamOrArgEndNoPop(Parse::NodeKind start_kind) -> void {
  434. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  435. ParamOrArgSave(node_stack_.PopExpr());
  436. }
  437. }
  438. auto Context::ParamOrArgPop() -> SemIR::InstBlockId {
  439. return params_or_args_stack_.Pop();
  440. }
  441. auto Context::ParamOrArgEnd(Parse::NodeKind start_kind) -> SemIR::InstBlockId {
  442. ParamOrArgEndNoPop(start_kind);
  443. return ParamOrArgPop();
  444. }
  445. namespace {
  446. // Worklist-based type completion mechanism.
  447. //
  448. // When attempting to complete a type, we may find other types that also need to
  449. // be completed: types nested within that type, and the value representation of
  450. // the type. In order to complete a type without recursing arbitrarily deeply,
  451. // we use a worklist of tasks:
  452. //
  453. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  454. // nested within a type to the work list.
  455. // - A `BuildValueRepresentation` step computes the value representation for a
  456. // type, once all of its nested types are complete, and marks the type as
  457. // complete.
  458. class TypeCompleter {
  459. public:
  460. TypeCompleter(
  461. Context& context,
  462. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  463. diagnoser)
  464. : context_(context), diagnoser_(diagnoser) {}
  465. // Attempts to complete the given type. Returns true if it is now complete,
  466. // false if it could not be completed.
  467. auto Complete(SemIR::TypeId type_id) -> bool {
  468. Push(type_id);
  469. while (!work_list_.empty()) {
  470. if (!ProcessStep()) {
  471. return false;
  472. }
  473. }
  474. return true;
  475. }
  476. private:
  477. // Adds `type_id` to the work list, if it's not already complete.
  478. auto Push(SemIR::TypeId type_id) -> void {
  479. if (!context_.sem_ir().IsTypeComplete(type_id)) {
  480. work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes});
  481. }
  482. }
  483. // Runs the next step.
  484. auto ProcessStep() -> bool {
  485. auto [type_id, phase] = work_list_.back();
  486. // We might have enqueued the same type more than once. Just skip the
  487. // type if it's already complete.
  488. if (context_.sem_ir().IsTypeComplete(type_id)) {
  489. work_list_.pop_back();
  490. return true;
  491. }
  492. auto inst_id = context_.sem_ir().GetTypeAllowBuiltinTypes(type_id);
  493. auto inst = context_.insts().Get(inst_id);
  494. auto old_work_list_size = work_list_.size();
  495. switch (phase) {
  496. case Phase::AddNestedIncompleteTypes:
  497. if (!AddNestedIncompleteTypes(inst)) {
  498. return false;
  499. }
  500. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  501. << "AddNestedIncompleteTypes should not remove work items";
  502. work_list_[old_work_list_size - 1].phase =
  503. Phase::BuildValueRepresentation;
  504. break;
  505. case Phase::BuildValueRepresentation: {
  506. auto value_rep = BuildValueRepresentation(type_id, inst);
  507. context_.sem_ir().CompleteType(type_id, value_rep);
  508. CARBON_CHECK(old_work_list_size == work_list_.size())
  509. << "BuildValueRepresentation should not change work items";
  510. work_list_.pop_back();
  511. // Also complete the value representation type, if necessary. This
  512. // should never fail: the value representation shouldn't require any
  513. // additional nested types to be complete.
  514. if (!context_.sem_ir().IsTypeComplete(value_rep.type_id)) {
  515. work_list_.push_back(
  516. {value_rep.type_id, Phase::BuildValueRepresentation});
  517. }
  518. // For a pointer representation, the pointee also needs to be complete.
  519. if (value_rep.kind == SemIR::ValueRepresentation::Pointer) {
  520. auto pointee_type_id =
  521. context_.sem_ir().GetPointeeType(value_rep.type_id);
  522. if (!context_.sem_ir().IsTypeComplete(pointee_type_id)) {
  523. work_list_.push_back(
  524. {pointee_type_id, Phase::BuildValueRepresentation});
  525. }
  526. }
  527. break;
  528. }
  529. }
  530. return true;
  531. }
  532. // Adds any types nested within `type_inst` that need to be complete for
  533. // `type_inst` to be complete to our work list.
  534. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  535. switch (type_inst.kind()) {
  536. case SemIR::ArrayType::Kind:
  537. Push(type_inst.As<SemIR::ArrayType>().element_type_id);
  538. break;
  539. case SemIR::StructType::Kind:
  540. for (auto field_id : context_.inst_blocks().Get(
  541. type_inst.As<SemIR::StructType>().fields_id)) {
  542. Push(context_.insts()
  543. .GetAs<SemIR::StructTypeField>(field_id)
  544. .field_type_id);
  545. }
  546. break;
  547. case SemIR::TupleType::Kind:
  548. for (auto element_type_id : context_.type_blocks().Get(
  549. type_inst.As<SemIR::TupleType>().elements_id)) {
  550. Push(element_type_id);
  551. }
  552. break;
  553. case SemIR::ClassType::Kind: {
  554. auto class_type = type_inst.As<SemIR::ClassType>();
  555. auto& class_info = context_.classes().Get(class_type.class_id);
  556. if (!class_info.is_defined()) {
  557. if (diagnoser_) {
  558. auto builder = (*diagnoser_)();
  559. context_.NoteIncompleteClass(class_type.class_id, builder);
  560. builder.Emit();
  561. }
  562. return false;
  563. }
  564. Push(class_info.object_representation_id);
  565. break;
  566. }
  567. case SemIR::ConstType::Kind:
  568. Push(type_inst.As<SemIR::ConstType>().inner_id);
  569. break;
  570. default:
  571. break;
  572. }
  573. return true;
  574. }
  575. // Makes an empty value representation, which is used for types that have no
  576. // state, such as empty structs and tuples.
  577. auto MakeEmptyRepresentation(Parse::Node parse_node) const
  578. -> SemIR::ValueRepresentation {
  579. return {.kind = SemIR::ValueRepresentation::None,
  580. .type_id = context_.CanonicalizeTupleType(parse_node, {})};
  581. }
  582. // Makes a value representation that uses pass-by-copy, copying the given
  583. // type.
  584. auto MakeCopyRepresentation(
  585. SemIR::TypeId rep_id,
  586. SemIR::ValueRepresentation::AggregateKind aggregate_kind =
  587. SemIR::ValueRepresentation::NotAggregate) const
  588. -> SemIR::ValueRepresentation {
  589. return {.kind = SemIR::ValueRepresentation::Copy,
  590. .aggregate_kind = aggregate_kind,
  591. .type_id = rep_id};
  592. }
  593. // Makes a value representation that uses pass-by-address with the given
  594. // pointee type.
  595. auto MakePointerRepresentation(
  596. Parse::Node parse_node, SemIR::TypeId pointee_id,
  597. SemIR::ValueRepresentation::AggregateKind aggregate_kind =
  598. SemIR::ValueRepresentation::NotAggregate) const
  599. -> SemIR::ValueRepresentation {
  600. // TODO: Should we add `const` qualification to `pointee_id`?
  601. return {.kind = SemIR::ValueRepresentation::Pointer,
  602. .aggregate_kind = aggregate_kind,
  603. .type_id = context_.GetPointerType(parse_node, pointee_id)};
  604. }
  605. // Gets the value representation of a nested type, which should already be
  606. // complete.
  607. auto GetNestedValueRepresentation(SemIR::TypeId nested_type_id) const {
  608. CARBON_CHECK(context_.sem_ir().IsTypeComplete(nested_type_id))
  609. << "Nested type should already be complete";
  610. auto value_rep = context_.sem_ir().GetValueRepresentation(nested_type_id);
  611. CARBON_CHECK(value_rep.kind != SemIR::ValueRepresentation::Unknown)
  612. << "Complete type should have a value representation";
  613. return value_rep;
  614. };
  615. auto BuildCrossRefValueRepresentation(SemIR::TypeId type_id,
  616. SemIR::CrossRef xref) const
  617. -> SemIR::ValueRepresentation {
  618. auto xref_inst =
  619. context_.cross_ref_irs().Get(xref.ir_id)->insts().Get(xref.inst_id);
  620. // The canonical description of a type should only have cross-references
  621. // for entities owned by another File, such as builtins, which are owned
  622. // by the prelude, and named entities like classes and interfaces, which
  623. // we don't support yet.
  624. CARBON_CHECK(xref_inst.kind() == SemIR::Builtin::Kind)
  625. << "TODO: Handle other kinds of inst cross-references";
  626. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  627. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  628. switch (xref_inst.As<SemIR::Builtin>().builtin_kind) {
  629. case SemIR::BuiltinKind::TypeType:
  630. case SemIR::BuiltinKind::Error:
  631. case SemIR::BuiltinKind::Invalid:
  632. case SemIR::BuiltinKind::BoolType:
  633. case SemIR::BuiltinKind::IntegerType:
  634. case SemIR::BuiltinKind::FloatingPointType:
  635. case SemIR::BuiltinKind::NamespaceType:
  636. case SemIR::BuiltinKind::FunctionType:
  637. case SemIR::BuiltinKind::BoundMethodType:
  638. return MakeCopyRepresentation(type_id);
  639. case SemIR::BuiltinKind::StringType:
  640. // TODO: Decide on string value semantics. This should probably be a
  641. // custom value representation carrying a pointer and size or
  642. // similar.
  643. return MakePointerRepresentation(Parse::Node::Invalid, type_id);
  644. }
  645. llvm_unreachable("All builtin kinds were handled above");
  646. }
  647. auto BuildStructOrTupleValueRepresentation(Parse::Node parse_node,
  648. std::size_t num_elements,
  649. SemIR::TypeId elementwise_rep,
  650. bool same_as_object_rep) const
  651. -> SemIR::ValueRepresentation {
  652. SemIR::ValueRepresentation::AggregateKind aggregate_kind =
  653. same_as_object_rep ? SemIR::ValueRepresentation::ValueAndObjectAggregate
  654. : SemIR::ValueRepresentation::ValueAggregate;
  655. if (num_elements == 1) {
  656. // The value representation for a struct or tuple with a single element
  657. // is a struct or tuple containing the value representation of the
  658. // element.
  659. // TODO: Consider doing the same whenever `elementwise_rep` is
  660. // sufficiently small.
  661. return MakeCopyRepresentation(elementwise_rep, aggregate_kind);
  662. }
  663. // For a struct or tuple with multiple fields, we use a pointer
  664. // to the elementwise value representation.
  665. return MakePointerRepresentation(parse_node, elementwise_rep,
  666. aggregate_kind);
  667. }
  668. auto BuildStructTypeValueRepresentation(SemIR::TypeId type_id,
  669. SemIR::StructType struct_type) const
  670. -> SemIR::ValueRepresentation {
  671. // TODO: Share more code with tuples.
  672. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  673. if (fields.empty()) {
  674. return MakeEmptyRepresentation(struct_type.parse_node);
  675. }
  676. // Find the value representation for each field, and construct a struct
  677. // of value representations.
  678. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  679. value_rep_fields.reserve(fields.size());
  680. bool same_as_object_rep = true;
  681. for (auto field_id : fields) {
  682. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  683. auto field_value_rep = GetNestedValueRepresentation(field.field_type_id);
  684. if (field_value_rep.type_id != field.field_type_id) {
  685. same_as_object_rep = false;
  686. field.field_type_id = field_value_rep.type_id;
  687. field_id = context_.AddConstantInst(field);
  688. }
  689. value_rep_fields.push_back(field_id);
  690. }
  691. auto value_rep = same_as_object_rep
  692. ? type_id
  693. : context_.CanonicalizeStructType(
  694. struct_type.parse_node,
  695. context_.inst_blocks().Add(value_rep_fields));
  696. return BuildStructOrTupleValueRepresentation(
  697. struct_type.parse_node, fields.size(), value_rep, same_as_object_rep);
  698. }
  699. auto BuildTupleTypeValueRepresentation(SemIR::TypeId type_id,
  700. SemIR::TupleType tuple_type) const
  701. -> SemIR::ValueRepresentation {
  702. // TODO: Share more code with structs.
  703. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  704. if (elements.empty()) {
  705. return MakeEmptyRepresentation(tuple_type.parse_node);
  706. }
  707. // Find the value representation for each element, and construct a tuple
  708. // of value representations.
  709. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  710. value_rep_elements.reserve(elements.size());
  711. bool same_as_object_rep = true;
  712. for (auto element_type_id : elements) {
  713. auto element_value_rep = GetNestedValueRepresentation(element_type_id);
  714. if (element_value_rep.type_id != element_type_id) {
  715. same_as_object_rep = false;
  716. }
  717. value_rep_elements.push_back(element_value_rep.type_id);
  718. }
  719. auto value_rep = same_as_object_rep
  720. ? type_id
  721. : context_.CanonicalizeTupleType(tuple_type.parse_node,
  722. value_rep_elements);
  723. return BuildStructOrTupleValueRepresentation(
  724. tuple_type.parse_node, elements.size(), value_rep, same_as_object_rep);
  725. }
  726. // Builds and returns the value representation for the given type. All nested
  727. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  728. auto BuildValueRepresentation(SemIR::TypeId type_id, SemIR::Inst inst) const
  729. -> SemIR::ValueRepresentation {
  730. // TODO: This can emit new SemIR instructions. Consider emitting them into a
  731. // dedicated file-scope instruction block where possible, or somewhere else
  732. // that better reflects the definition of the type, rather than wherever the
  733. // type happens to first be required to be complete.
  734. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  735. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  736. switch (inst.kind()) {
  737. case SemIR::AddressOf::Kind:
  738. case SemIR::ArrayIndex::Kind:
  739. case SemIR::ArrayInit::Kind:
  740. case SemIR::Assign::Kind:
  741. case SemIR::BinaryOperatorAdd::Kind:
  742. case SemIR::BindName::Kind:
  743. case SemIR::BindValue::Kind:
  744. case SemIR::BlockArg::Kind:
  745. case SemIR::BoolLiteral::Kind:
  746. case SemIR::BoundMethod::Kind:
  747. case SemIR::Branch::Kind:
  748. case SemIR::BranchIf::Kind:
  749. case SemIR::BranchWithArg::Kind:
  750. case SemIR::Call::Kind:
  751. case SemIR::ClassDecl::Kind:
  752. case SemIR::ClassFieldAccess::Kind:
  753. case SemIR::ClassInit::Kind:
  754. case SemIR::Converted::Kind:
  755. case SemIR::Deref::Kind:
  756. case SemIR::Field::Kind:
  757. case SemIR::FunctionDecl::Kind:
  758. case SemIR::Import::Kind:
  759. case SemIR::InitializeFrom::Kind:
  760. case SemIR::IntegerLiteral::Kind:
  761. case SemIR::NameRef::Kind:
  762. case SemIR::Namespace::Kind:
  763. case SemIR::NoOp::Kind:
  764. case SemIR::Param::Kind:
  765. case SemIR::RealLiteral::Kind:
  766. case SemIR::Return::Kind:
  767. case SemIR::ReturnExpr::Kind:
  768. case SemIR::SelfParam::Kind:
  769. case SemIR::SpliceBlock::Kind:
  770. case SemIR::StringLiteral::Kind:
  771. case SemIR::StructAccess::Kind:
  772. case SemIR::StructTypeField::Kind:
  773. case SemIR::StructLiteral::Kind:
  774. case SemIR::StructInit::Kind:
  775. case SemIR::StructValue::Kind:
  776. case SemIR::Temporary::Kind:
  777. case SemIR::TemporaryStorage::Kind:
  778. case SemIR::TupleAccess::Kind:
  779. case SemIR::TupleIndex::Kind:
  780. case SemIR::TupleLiteral::Kind:
  781. case SemIR::TupleInit::Kind:
  782. case SemIR::TupleValue::Kind:
  783. case SemIR::UnaryOperatorNot::Kind:
  784. case SemIR::ValueAsRef::Kind:
  785. case SemIR::ValueOfInitializer::Kind:
  786. case SemIR::VarStorage::Kind:
  787. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  788. case SemIR::CrossRef::Kind:
  789. return BuildCrossRefValueRepresentation(type_id,
  790. inst.As<SemIR::CrossRef>());
  791. case SemIR::ArrayType::Kind: {
  792. // For arrays, it's convenient to always use a pointer representation,
  793. // even when the array has zero or one element, in order to support
  794. // indexing.
  795. return MakePointerRepresentation(
  796. inst.parse_node(), type_id,
  797. SemIR::ValueRepresentation::ObjectAggregate);
  798. }
  799. case SemIR::StructType::Kind:
  800. return BuildStructTypeValueRepresentation(type_id,
  801. inst.As<SemIR::StructType>());
  802. case SemIR::TupleType::Kind:
  803. return BuildTupleTypeValueRepresentation(type_id,
  804. inst.As<SemIR::TupleType>());
  805. case SemIR::ClassType::Kind:
  806. // The value representation for a class is a pointer to the object
  807. // representation.
  808. // TODO: Support customized value representations for classes.
  809. // TODO: Pick a better value representation when possible.
  810. return MakePointerRepresentation(
  811. inst.parse_node(),
  812. context_.classes()
  813. .Get(inst.As<SemIR::ClassType>().class_id)
  814. .object_representation_id,
  815. SemIR::ValueRepresentation::ObjectAggregate);
  816. case SemIR::Builtin::Kind:
  817. CARBON_FATAL() << "Builtins should be named as cross-references";
  818. case SemIR::PointerType::Kind:
  819. case SemIR::UnboundFieldType::Kind:
  820. return MakeCopyRepresentation(type_id);
  821. case SemIR::ConstType::Kind:
  822. // The value representation of `const T` is the same as that of `T`.
  823. // Objects are not modifiable through their value representations.
  824. return GetNestedValueRepresentation(
  825. inst.As<SemIR::ConstType>().inner_id);
  826. }
  827. }
  828. enum class Phase : int8_t {
  829. // The next step is to add nested types to the list of types to complete.
  830. AddNestedIncompleteTypes,
  831. // The next step is to build the value representation for the type.
  832. BuildValueRepresentation,
  833. };
  834. struct WorkItem {
  835. SemIR::TypeId type_id;
  836. Phase phase;
  837. };
  838. Context& context_;
  839. llvm::SmallVector<WorkItem> work_list_;
  840. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  841. diagnoser_;
  842. };
  843. } // namespace
  844. auto Context::TryToCompleteType(
  845. SemIR::TypeId type_id,
  846. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  847. -> bool {
  848. return TypeCompleter(*this, diagnoser).Complete(type_id);
  849. }
  850. auto Context::CanonicalizeTypeImpl(
  851. SemIR::InstKind kind,
  852. llvm::function_ref<bool(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  853. llvm::function_ref<SemIR::InstId()> make_inst) -> SemIR::TypeId {
  854. llvm::FoldingSetNodeID canonical_id;
  855. kind.Profile(canonical_id);
  856. if (!profile_type(canonical_id)) {
  857. return SemIR::TypeId::Error;
  858. }
  859. void* insert_pos;
  860. auto* node =
  861. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  862. if (node != nullptr) {
  863. return node->type_id();
  864. }
  865. auto inst_id = make_inst();
  866. auto type_id = types().Add({.inst_id = inst_id});
  867. CARBON_CHECK(canonical_types_.insert({inst_id, type_id}).second);
  868. type_node_storage_.push_back(
  869. std::make_unique<TypeNode>(canonical_id, type_id));
  870. // In a debug build, check that our insertion position is still valid. It
  871. // could have been invalidated by a misbehaving `make_inst`.
  872. CARBON_DCHECK([&] {
  873. void* check_insert_pos;
  874. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  875. canonical_id, check_insert_pos);
  876. return !check_node && insert_pos == check_insert_pos;
  877. }()) << "Type was created recursively during canonicalization";
  878. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  879. return type_id;
  880. }
  881. // Compute a fingerprint for a tuple type, for use as a key in a folding set.
  882. static auto ProfileTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids,
  883. llvm::FoldingSetNodeID& canonical_id) -> void {
  884. for (auto type_id : type_ids) {
  885. canonical_id.AddInteger(type_id.index);
  886. }
  887. }
  888. // Compute a fingerprint for a type, for use as a key in a folding set. Returns
  889. // false if not supported, which is presently the case for compile-time
  890. // expressions.
  891. // TODO: Once support is more complete, in particular ensuring that various
  892. // valid compile-time expressions are supported, it may be desirable to switch
  893. // the default to a CARBON_FATAL error.
  894. static auto ProfileType(Context& semantics_context, SemIR::Inst inst,
  895. llvm::FoldingSetNodeID& canonical_id) -> bool {
  896. switch (inst.kind()) {
  897. case SemIR::ArrayType::Kind: {
  898. auto array_type = inst.As<SemIR::ArrayType>();
  899. canonical_id.AddInteger(
  900. semantics_context.sem_ir().GetArrayBoundValue(array_type.bound_id));
  901. canonical_id.AddInteger(array_type.element_type_id.index);
  902. break;
  903. }
  904. case SemIR::Builtin::Kind:
  905. canonical_id.AddInteger(inst.As<SemIR::Builtin>().builtin_kind.AsInt());
  906. break;
  907. case SemIR::ClassType::Kind:
  908. canonical_id.AddInteger(inst.As<SemIR::ClassType>().class_id.index);
  909. break;
  910. case SemIR::CrossRef::Kind: {
  911. // TODO: Cross-references should be canonicalized by looking at their
  912. // target rather than treating them as new unique types.
  913. auto xref = inst.As<SemIR::CrossRef>();
  914. canonical_id.AddInteger(xref.ir_id.index);
  915. canonical_id.AddInteger(xref.inst_id.index);
  916. break;
  917. }
  918. case SemIR::ConstType::Kind:
  919. canonical_id.AddInteger(
  920. semantics_context
  921. .GetUnqualifiedType(inst.As<SemIR::ConstType>().inner_id)
  922. .index);
  923. break;
  924. case SemIR::PointerType::Kind:
  925. canonical_id.AddInteger(inst.As<SemIR::PointerType>().pointee_id.index);
  926. break;
  927. case SemIR::StructType::Kind: {
  928. auto fields = semantics_context.inst_blocks().Get(
  929. inst.As<SemIR::StructType>().fields_id);
  930. for (const auto& field_id : fields) {
  931. auto field =
  932. semantics_context.insts().GetAs<SemIR::StructTypeField>(field_id);
  933. canonical_id.AddInteger(field.name_id.index);
  934. canonical_id.AddInteger(field.field_type_id.index);
  935. }
  936. break;
  937. }
  938. case SemIR::TupleType::Kind:
  939. ProfileTupleType(semantics_context.type_blocks().Get(
  940. inst.As<SemIR::TupleType>().elements_id),
  941. canonical_id);
  942. break;
  943. case SemIR::UnboundFieldType::Kind: {
  944. auto unbound_field_type = inst.As<SemIR::UnboundFieldType>();
  945. canonical_id.AddInteger(unbound_field_type.class_type_id.index);
  946. canonical_id.AddInteger(unbound_field_type.field_type_id.index);
  947. break;
  948. }
  949. default: {
  950. // Right now, this is only expected to occur in calls from
  951. // ExprAsType. Diagnostics are issued there.
  952. return false;
  953. }
  954. }
  955. return true;
  956. }
  957. auto Context::CanonicalizeTypeAndAddInstIfNew(SemIR::Inst inst)
  958. -> SemIR::TypeId {
  959. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  960. return ProfileType(*this, inst, canonical_id);
  961. };
  962. auto make_inst = [&] { return AddConstantInst(inst); };
  963. return CanonicalizeTypeImpl(inst.kind(), profile_node, make_inst);
  964. }
  965. auto Context::CanonicalizeType(SemIR::InstId inst_id) -> SemIR::TypeId {
  966. while (auto converted = insts().Get(inst_id).TryAs<SemIR::Converted>()) {
  967. inst_id = converted->result_id;
  968. }
  969. inst_id = FollowNameRefs(inst_id);
  970. auto it = canonical_types_.find(inst_id);
  971. if (it != canonical_types_.end()) {
  972. return it->second;
  973. }
  974. auto inst = insts().Get(inst_id);
  975. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  976. return ProfileType(*this, inst, canonical_id);
  977. };
  978. auto make_inst = [&] { return inst_id; };
  979. return CanonicalizeTypeImpl(inst.kind(), profile_node, make_inst);
  980. }
  981. auto Context::CanonicalizeStructType(Parse::Node parse_node,
  982. SemIR::InstBlockId refs_id)
  983. -> SemIR::TypeId {
  984. return CanonicalizeTypeAndAddInstIfNew(
  985. SemIR::StructType{parse_node, SemIR::TypeId::TypeType, refs_id});
  986. }
  987. auto Context::CanonicalizeTupleType(Parse::Node parse_node,
  988. llvm::ArrayRef<SemIR::TypeId> type_ids)
  989. -> SemIR::TypeId {
  990. // Defer allocating a SemIR::TypeBlockId until we know this is a new type.
  991. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  992. ProfileTupleType(type_ids, canonical_id);
  993. return true;
  994. };
  995. auto make_tuple_inst = [&] {
  996. return AddConstantInst(SemIR::TupleType{parse_node, SemIR::TypeId::TypeType,
  997. type_blocks().Add(type_ids)});
  998. };
  999. return CanonicalizeTypeImpl(SemIR::TupleType::Kind, profile_tuple,
  1000. make_tuple_inst);
  1001. }
  1002. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  1003. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  1004. auto type_id = CanonicalizeType(SemIR::InstId::ForBuiltin(kind));
  1005. // To keep client code simpler, complete builtin types before returning them.
  1006. bool complete = TryToCompleteType(type_id);
  1007. CARBON_CHECK(complete) << "Failed to complete builtin type";
  1008. return type_id;
  1009. }
  1010. auto Context::GetPointerType(Parse::Node parse_node,
  1011. SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1012. return CanonicalizeTypeAndAddInstIfNew(
  1013. SemIR::PointerType{parse_node, SemIR::TypeId::TypeType, pointee_type_id});
  1014. }
  1015. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  1016. SemIR::Inst type_inst =
  1017. insts().Get(sem_ir_->GetTypeAllowBuiltinTypes(type_id));
  1018. if (auto const_type = type_inst.TryAs<SemIR::ConstType>()) {
  1019. return const_type->inner_id;
  1020. }
  1021. return type_id;
  1022. }
  1023. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1024. node_stack_.PrintForStackDump(output);
  1025. inst_block_stack_.PrintForStackDump(output);
  1026. params_or_args_stack_.PrintForStackDump(output);
  1027. args_type_info_stack_.PrintForStackDump(output);
  1028. }
  1029. } // namespace Carbon::Check