context.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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::ImportIRId first_id(import_irs().size());
  154. for (const auto* sem_ir : sem_irs) {
  155. import_irs().Add(sem_ir);
  156. }
  157. if (has_load_error) {
  158. import_irs().Add(nullptr);
  159. }
  160. SemIR::ImportIRId last_id(import_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_import_ir_id = first_id,
  165. .last_import_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 = *import_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. // Support expressions, parameters, and other nodes like `StructFieldValue`
  514. // that produce InstIds.
  515. ParamOrArgSave(node_stack_.Pop<SemIR::InstId>());
  516. }
  517. auto Context::ParamOrArgEndNoPop(Parse::NodeKind start_kind) -> void {
  518. if (!node_stack_.PeekIs(start_kind)) {
  519. // Support expressions, parameters, and other nodes like `StructFieldValue`
  520. // that produce InstIds.
  521. ParamOrArgSave(node_stack_.Pop<SemIR::InstId>());
  522. }
  523. }
  524. auto Context::ParamOrArgPop() -> SemIR::InstBlockId {
  525. return params_or_args_stack_.Pop();
  526. }
  527. auto Context::ParamOrArgEnd(Parse::NodeKind start_kind) -> SemIR::InstBlockId {
  528. ParamOrArgEndNoPop(start_kind);
  529. return ParamOrArgPop();
  530. }
  531. namespace {
  532. // Worklist-based type completion mechanism.
  533. //
  534. // When attempting to complete a type, we may find other types that also need to
  535. // be completed: types nested within that type, and the value representation of
  536. // the type. In order to complete a type without recursing arbitrarily deeply,
  537. // we use a worklist of tasks:
  538. //
  539. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  540. // nested within a type to the work list.
  541. // - A `BuildValueRepr` step computes the value representation for a
  542. // type, once all of its nested types are complete, and marks the type as
  543. // complete.
  544. class TypeCompleter {
  545. public:
  546. TypeCompleter(
  547. Context& context,
  548. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  549. diagnoser)
  550. : context_(context), diagnoser_(diagnoser) {}
  551. // Attempts to complete the given type. Returns true if it is now complete,
  552. // false if it could not be completed.
  553. auto Complete(SemIR::TypeId type_id) -> bool {
  554. Push(type_id);
  555. while (!work_list_.empty()) {
  556. if (!ProcessStep()) {
  557. return false;
  558. }
  559. }
  560. return true;
  561. }
  562. private:
  563. // Adds `type_id` to the work list, if it's not already complete.
  564. auto Push(SemIR::TypeId type_id) -> void {
  565. if (!context_.types().IsComplete(type_id)) {
  566. work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes});
  567. }
  568. }
  569. // Runs the next step.
  570. auto ProcessStep() -> bool {
  571. auto [type_id, phase] = work_list_.back();
  572. // We might have enqueued the same type more than once. Just skip the
  573. // type if it's already complete.
  574. if (context_.types().IsComplete(type_id)) {
  575. work_list_.pop_back();
  576. return true;
  577. }
  578. auto inst_id = context_.types().GetInstId(type_id);
  579. auto inst = context_.insts().Get(inst_id);
  580. auto old_work_list_size = work_list_.size();
  581. switch (phase) {
  582. case Phase::AddNestedIncompleteTypes:
  583. if (!AddNestedIncompleteTypes(inst)) {
  584. return false;
  585. }
  586. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  587. << "AddNestedIncompleteTypes should not remove work items";
  588. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  589. break;
  590. case Phase::BuildValueRepr: {
  591. auto value_rep = BuildValueRepr(type_id, inst);
  592. context_.sem_ir().CompleteType(type_id, value_rep);
  593. CARBON_CHECK(old_work_list_size == work_list_.size())
  594. << "BuildValueRepr should not change work items";
  595. work_list_.pop_back();
  596. // Also complete the value representation type, if necessary. This
  597. // should never fail: the value representation shouldn't require any
  598. // additional nested types to be complete.
  599. if (!context_.types().IsComplete(value_rep.type_id)) {
  600. work_list_.push_back({value_rep.type_id, Phase::BuildValueRepr});
  601. }
  602. // For a pointer representation, the pointee also needs to be complete.
  603. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  604. if (value_rep.type_id == SemIR::TypeId::Error) {
  605. break;
  606. }
  607. auto pointee_type_id =
  608. context_.sem_ir().GetPointeeType(value_rep.type_id);
  609. if (!context_.types().IsComplete(pointee_type_id)) {
  610. work_list_.push_back({pointee_type_id, Phase::BuildValueRepr});
  611. }
  612. }
  613. break;
  614. }
  615. }
  616. return true;
  617. }
  618. // Adds any types nested within `type_inst` that need to be complete for
  619. // `type_inst` to be complete to our work list.
  620. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  621. switch (type_inst.kind()) {
  622. case SemIR::ArrayType::Kind:
  623. Push(type_inst.As<SemIR::ArrayType>().element_type_id);
  624. break;
  625. case SemIR::StructType::Kind:
  626. for (auto field_id : context_.inst_blocks().Get(
  627. type_inst.As<SemIR::StructType>().fields_id)) {
  628. Push(context_.insts()
  629. .GetAs<SemIR::StructTypeField>(field_id)
  630. .field_type_id);
  631. }
  632. break;
  633. case SemIR::TupleType::Kind:
  634. for (auto element_type_id : context_.type_blocks().Get(
  635. type_inst.As<SemIR::TupleType>().elements_id)) {
  636. Push(element_type_id);
  637. }
  638. break;
  639. case SemIR::ClassType::Kind: {
  640. auto class_type = type_inst.As<SemIR::ClassType>();
  641. auto& class_info = context_.classes().Get(class_type.class_id);
  642. if (!class_info.is_defined()) {
  643. if (diagnoser_) {
  644. auto builder = (*diagnoser_)();
  645. context_.NoteIncompleteClass(class_type.class_id, builder);
  646. builder.Emit();
  647. }
  648. return false;
  649. }
  650. Push(class_info.object_repr_id);
  651. break;
  652. }
  653. case SemIR::ConstType::Kind:
  654. Push(type_inst.As<SemIR::ConstType>().inner_id);
  655. break;
  656. default:
  657. break;
  658. }
  659. return true;
  660. }
  661. // Makes an empty value representation, which is used for types that have no
  662. // state, such as empty structs and tuples.
  663. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  664. return {.kind = SemIR::ValueRepr::None,
  665. .type_id = context_.GetTupleType({})};
  666. }
  667. // Makes a value representation that uses pass-by-copy, copying the given
  668. // type.
  669. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  670. SemIR::ValueRepr::AggregateKind aggregate_kind =
  671. SemIR::ValueRepr::NotAggregate) const
  672. -> SemIR::ValueRepr {
  673. return {.kind = SemIR::ValueRepr::Copy,
  674. .aggregate_kind = aggregate_kind,
  675. .type_id = rep_id};
  676. }
  677. // Makes a value representation that uses pass-by-address with the given
  678. // pointee type.
  679. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  680. SemIR::ValueRepr::AggregateKind aggregate_kind =
  681. SemIR::ValueRepr::NotAggregate) const
  682. -> SemIR::ValueRepr {
  683. // TODO: Should we add `const` qualification to `pointee_id`?
  684. return {.kind = SemIR::ValueRepr::Pointer,
  685. .aggregate_kind = aggregate_kind,
  686. .type_id = context_.GetPointerType(pointee_id)};
  687. }
  688. // Gets the value representation of a nested type, which should already be
  689. // complete.
  690. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  691. CARBON_CHECK(context_.types().IsComplete(nested_type_id))
  692. << "Nested type should already be complete";
  693. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  694. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown)
  695. << "Complete type should have a value representation";
  696. return value_rep;
  697. };
  698. auto BuildImportRefUsedValueRepr(SemIR::TypeId type_id,
  699. SemIR::ImportRefUsed import_ref) const
  700. -> SemIR::ValueRepr {
  701. CARBON_CHECK(import_ref.inst_id.is_builtin())
  702. << "TODO: Handle non-builtin ImportRefUsed cases, such as functions, "
  703. "classes, and interfaces";
  704. const auto& import_ir = context_.import_irs().Get(import_ref.ir_id);
  705. auto import_inst = import_ir->insts().Get(import_ref.inst_id);
  706. switch (import_inst.As<SemIR::Builtin>().builtin_kind) {
  707. case SemIR::BuiltinKind::TypeType:
  708. case SemIR::BuiltinKind::Error:
  709. case SemIR::BuiltinKind::Invalid:
  710. case SemIR::BuiltinKind::BoolType:
  711. case SemIR::BuiltinKind::IntType:
  712. case SemIR::BuiltinKind::FloatType:
  713. case SemIR::BuiltinKind::NamespaceType:
  714. case SemIR::BuiltinKind::FunctionType:
  715. case SemIR::BuiltinKind::BoundMethodType:
  716. return MakeCopyValueRepr(type_id);
  717. case SemIR::BuiltinKind::StringType:
  718. // TODO: Decide on string value semantics. This should probably be a
  719. // custom value representation carrying a pointer and size or
  720. // similar.
  721. return MakePointerValueRepr(type_id);
  722. }
  723. llvm_unreachable("All builtin kinds were handled above");
  724. }
  725. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  726. SemIR::TypeId elementwise_rep,
  727. bool same_as_object_rep) const
  728. -> SemIR::ValueRepr {
  729. SemIR::ValueRepr::AggregateKind aggregate_kind =
  730. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  731. : SemIR::ValueRepr::ValueAggregate;
  732. if (num_elements == 1) {
  733. // The value representation for a struct or tuple with a single element
  734. // is a struct or tuple containing the value representation of the
  735. // element.
  736. // TODO: Consider doing the same whenever `elementwise_rep` is
  737. // sufficiently small.
  738. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  739. }
  740. // For a struct or tuple with multiple fields, we use a pointer
  741. // to the elementwise value representation.
  742. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  743. }
  744. auto BuildStructTypeValueRepr(SemIR::TypeId type_id,
  745. SemIR::StructType struct_type) const
  746. -> SemIR::ValueRepr {
  747. // TODO: Share more code with tuples.
  748. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  749. if (fields.empty()) {
  750. return MakeEmptyValueRepr();
  751. }
  752. // Find the value representation for each field, and construct a struct
  753. // of value representations.
  754. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  755. value_rep_fields.reserve(fields.size());
  756. bool same_as_object_rep = true;
  757. for (auto field_id : fields) {
  758. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  759. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  760. if (field_value_rep.type_id != field.field_type_id) {
  761. same_as_object_rep = false;
  762. field.field_type_id = field_value_rep.type_id;
  763. // TODO: Use `TryEvalInst` to form this value.
  764. field_id = context_
  765. .AddConstant(field, context_.constant_values()
  766. .Get(context_.types().GetInstId(
  767. field.field_type_id))
  768. .is_symbolic())
  769. .inst_id();
  770. }
  771. value_rep_fields.push_back(field_id);
  772. }
  773. auto value_rep = same_as_object_rep
  774. ? type_id
  775. : context_.GetStructType(
  776. context_.inst_blocks().Add(value_rep_fields));
  777. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  778. same_as_object_rep);
  779. }
  780. auto BuildTupleTypeValueRepr(SemIR::TypeId type_id,
  781. SemIR::TupleType tuple_type) const
  782. -> SemIR::ValueRepr {
  783. // TODO: Share more code with structs.
  784. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  785. if (elements.empty()) {
  786. return MakeEmptyValueRepr();
  787. }
  788. // Find the value representation for each element, and construct a tuple
  789. // of value representations.
  790. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  791. value_rep_elements.reserve(elements.size());
  792. bool same_as_object_rep = true;
  793. for (auto element_type_id : elements) {
  794. auto element_value_rep = GetNestedValueRepr(element_type_id);
  795. if (element_value_rep.type_id != element_type_id) {
  796. same_as_object_rep = false;
  797. }
  798. value_rep_elements.push_back(element_value_rep.type_id);
  799. }
  800. auto value_rep = same_as_object_rep
  801. ? type_id
  802. : context_.GetTupleType(value_rep_elements);
  803. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  804. same_as_object_rep);
  805. }
  806. // Builds and returns the value representation for the given type. All nested
  807. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  808. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  809. -> SemIR::ValueRepr {
  810. // TODO: This can emit new SemIR instructions. Consider emitting them into a
  811. // dedicated file-scope instruction block where possible, or somewhere else
  812. // that better reflects the definition of the type, rather than wherever the
  813. // type happens to first be required to be complete.
  814. switch (inst.kind()) {
  815. case SemIR::AddrOf::Kind:
  816. case SemIR::AddrPattern::Kind:
  817. case SemIR::ArrayIndex::Kind:
  818. case SemIR::ArrayInit::Kind:
  819. case SemIR::Assign::Kind:
  820. case SemIR::BaseDecl::Kind:
  821. case SemIR::BindName::Kind:
  822. case SemIR::BindValue::Kind:
  823. case SemIR::BlockArg::Kind:
  824. case SemIR::BoolLiteral::Kind:
  825. case SemIR::BoundMethod::Kind:
  826. case SemIR::Branch::Kind:
  827. case SemIR::BranchIf::Kind:
  828. case SemIR::BranchWithArg::Kind:
  829. case SemIR::Call::Kind:
  830. case SemIR::ClassDecl::Kind:
  831. case SemIR::ClassElementAccess::Kind:
  832. case SemIR::ClassInit::Kind:
  833. case SemIR::Converted::Kind:
  834. case SemIR::Deref::Kind:
  835. case SemIR::FieldDecl::Kind:
  836. case SemIR::FunctionDecl::Kind:
  837. case SemIR::Import::Kind:
  838. case SemIR::InitializeFrom::Kind:
  839. case SemIR::InterfaceDecl::Kind:
  840. case SemIR::IntLiteral::Kind:
  841. case SemIR::ImportRefUnused::Kind:
  842. case SemIR::NameRef::Kind:
  843. case SemIR::Namespace::Kind:
  844. case SemIR::Param::Kind:
  845. case SemIR::RealLiteral::Kind:
  846. case SemIR::Return::Kind:
  847. case SemIR::ReturnExpr::Kind:
  848. case SemIR::SpliceBlock::Kind:
  849. case SemIR::StringLiteral::Kind:
  850. case SemIR::StructAccess::Kind:
  851. case SemIR::StructTypeField::Kind:
  852. case SemIR::StructLiteral::Kind:
  853. case SemIR::StructInit::Kind:
  854. case SemIR::StructValue::Kind:
  855. case SemIR::Temporary::Kind:
  856. case SemIR::TemporaryStorage::Kind:
  857. case SemIR::TupleAccess::Kind:
  858. case SemIR::TupleIndex::Kind:
  859. case SemIR::TupleLiteral::Kind:
  860. case SemIR::TupleInit::Kind:
  861. case SemIR::TupleValue::Kind:
  862. case SemIR::UnaryOperatorNot::Kind:
  863. case SemIR::ValueAsRef::Kind:
  864. case SemIR::ValueOfInitializer::Kind:
  865. case SemIR::VarStorage::Kind:
  866. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  867. case SemIR::ArrayType::Kind: {
  868. // For arrays, it's convenient to always use a pointer representation,
  869. // even when the array has zero or one element, in order to support
  870. // indexing.
  871. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  872. }
  873. case SemIR::ImportRefUsed::Kind:
  874. return BuildImportRefUsedValueRepr(type_id,
  875. inst.As<SemIR::ImportRefUsed>());
  876. case SemIR::StructType::Kind:
  877. return BuildStructTypeValueRepr(type_id, inst.As<SemIR::StructType>());
  878. case SemIR::TupleType::Kind:
  879. return BuildTupleTypeValueRepr(type_id, inst.As<SemIR::TupleType>());
  880. case SemIR::ClassType::Kind:
  881. // The value representation for a class is a pointer to the object
  882. // representation.
  883. // TODO: Support customized value representations for classes.
  884. // TODO: Pick a better value representation when possible.
  885. return MakePointerValueRepr(
  886. context_.classes()
  887. .Get(inst.As<SemIR::ClassType>().class_id)
  888. .object_repr_id,
  889. SemIR::ValueRepr::ObjectAggregate);
  890. case SemIR::Builtin::Kind:
  891. CARBON_FATAL() << "Builtins should be named as ImportRefUsed";
  892. case SemIR::BindSymbolicName::Kind:
  893. case SemIR::PointerType::Kind:
  894. case SemIR::UnboundElementType::Kind:
  895. return MakeCopyValueRepr(type_id);
  896. case SemIR::ConstType::Kind:
  897. // The value representation of `const T` is the same as that of `T`.
  898. // Objects are not modifiable through their value representations.
  899. return GetNestedValueRepr(inst.As<SemIR::ConstType>().inner_id);
  900. }
  901. }
  902. enum class Phase : int8_t {
  903. // The next step is to add nested types to the list of types to complete.
  904. AddNestedIncompleteTypes,
  905. // The next step is to build the value representation for the type.
  906. BuildValueRepr,
  907. };
  908. struct WorkItem {
  909. SemIR::TypeId type_id;
  910. Phase phase;
  911. };
  912. Context& context_;
  913. llvm::SmallVector<WorkItem> work_list_;
  914. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  915. diagnoser_;
  916. };
  917. } // namespace
  918. auto Context::TryToCompleteType(
  919. SemIR::TypeId type_id,
  920. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  921. -> bool {
  922. return TypeCompleter(*this, diagnoser).Complete(type_id);
  923. }
  924. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  925. -> SemIR::TypeId {
  926. CARBON_CHECK(constant_id.is_constant()) << "Canonicalizing non-constant type";
  927. auto [it, added] = type_ids_for_type_constants_.insert(
  928. {constant_id, SemIR::TypeId::Invalid});
  929. if (added) {
  930. it->second = types().Add({.constant_id = constant_id});
  931. }
  932. return it->second;
  933. }
  934. template <typename InstT, typename... EachArgT>
  935. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  936. -> SemIR::TypeId {
  937. // TODO: Remove inst_id parameter from TryEvalInst.
  938. return context.GetTypeIdForTypeConstant(
  939. TryEvalInst(context, SemIR::InstId::Invalid,
  940. InstT{SemIR::TypeId::TypeType, each_arg...}));
  941. }
  942. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  943. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  944. }
  945. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  946. -> SemIR::TypeId {
  947. // TODO: Deduplicate the type block here. Currently requesting the same tuple
  948. // type more than once will create multiple type blocks, all but one of which
  949. // is unused.
  950. return GetTypeImpl<SemIR::TupleType>(*this, type_blocks().Add(type_ids));
  951. }
  952. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  953. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  954. auto type_id = GetTypeIdForTypeConstant(
  955. constant_values().Get(SemIR::InstId::ForBuiltin(kind)));
  956. // To keep client code simpler, complete builtin types before returning them.
  957. bool complete = TryToCompleteType(type_id);
  958. CARBON_CHECK(complete) << "Failed to complete builtin type";
  959. return type_id;
  960. }
  961. auto Context::GetClassType(SemIR::ClassId class_id) -> SemIR::TypeId {
  962. return GetTypeImpl<SemIR::ClassType>(*this, class_id);
  963. }
  964. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  965. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  966. }
  967. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  968. SemIR::TypeId element_type_id)
  969. -> SemIR::TypeId {
  970. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  971. element_type_id);
  972. }
  973. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  974. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  975. return const_type->inner_id;
  976. }
  977. return type_id;
  978. }
  979. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  980. node_stack_.PrintForStackDump(output);
  981. inst_block_stack_.PrintForStackDump(output);
  982. params_or_args_stack_.PrintForStackDump(output);
  983. args_type_info_stack_.PrintForStackDump(output);
  984. }
  985. } // namespace Carbon::Check