context.cpp 38 KB

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