context.cpp 42 KB

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