context.cpp 39 KB

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