context.cpp 41 KB

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