context.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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/declaration_name_stack.h"
  11. #include "toolchain/check/node_block_stack.h"
  12. #include "toolchain/lex/tokenized_buffer.h"
  13. #include "toolchain/parse/node_kind.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/node.h"
  16. #include "toolchain/sem_ir/node_kind.h"
  17. namespace Carbon::Check {
  18. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  19. const Parse::Tree& parse_tree, SemIR::File& semantics_ir,
  20. llvm::raw_ostream* vlog_stream)
  21. : tokens_(&tokens),
  22. emitter_(&emitter),
  23. parse_tree_(&parse_tree),
  24. semantics_ir_(&semantics_ir),
  25. vlog_stream_(vlog_stream),
  26. node_stack_(parse_tree, vlog_stream),
  27. node_block_stack_("node_block_stack_", semantics_ir, vlog_stream),
  28. params_or_args_stack_("params_or_args_stack_", semantics_ir, vlog_stream),
  29. args_type_info_stack_("args_type_info_stack_", semantics_ir, vlog_stream),
  30. declaration_name_stack_(this) {
  31. // Inserts the "Error" and "Type" types as "used types" so that
  32. // canonicalization can skip them. We don't emit either for lowering.
  33. canonical_types_.insert({SemIR::NodeId::BuiltinError, SemIR::TypeId::Error});
  34. canonical_types_.insert(
  35. {SemIR::NodeId::BuiltinTypeType, SemIR::TypeId::TypeType});
  36. }
  37. auto Context::TODO(Parse::Node parse_node, std::string label) -> bool {
  38. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  39. std::string);
  40. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  41. return false;
  42. }
  43. auto Context::VerifyOnFinish() -> void {
  44. // Information in all the various context objects should be cleaned up as
  45. // various pieces of context go out of scope. At this point, nothing should
  46. // remain.
  47. // node_stack_ will still contain top-level entities.
  48. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  49. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  50. CARBON_CHECK(node_block_stack_.empty()) << node_block_stack_.size();
  51. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  52. }
  53. auto Context::AddNode(SemIR::Node node) -> SemIR::NodeId {
  54. auto node_id = node_block_stack_.AddNode(node);
  55. CARBON_VLOG() << "AddNode: " << node << "\n";
  56. return node_id;
  57. }
  58. auto Context::AddNodeAndPush(Parse::Node parse_node, SemIR::Node node) -> void {
  59. auto node_id = AddNode(node);
  60. node_stack_.Push(parse_node, node_id);
  61. }
  62. auto Context::DiagnoseDuplicateName(Parse::Node parse_node,
  63. SemIR::NodeId prev_def_id) -> void {
  64. CARBON_DIAGNOSTIC(NameDeclarationDuplicate, Error,
  65. "Duplicate name being declared in the same scope.");
  66. CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note,
  67. "Name is previously declared here.");
  68. auto prev_def = semantics_ir_->GetNode(prev_def_id);
  69. emitter_->Build(parse_node, NameDeclarationDuplicate)
  70. .Note(prev_def.parse_node(), NameDeclarationPrevious)
  71. .Emit();
  72. }
  73. auto Context::DiagnoseNameNotFound(Parse::Node parse_node, StringId name_id)
  74. -> void {
  75. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  76. llvm::StringRef);
  77. emitter_->Emit(parse_node, NameNotFound,
  78. semantics_ir_->strings().Get(name_id));
  79. }
  80. auto Context::NoteIncompleteClass(SemIR::ClassDeclaration class_decl,
  81. DiagnosticBuilder& builder) -> void {
  82. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  83. "Class was forward declared here.");
  84. builder.Note(class_decl.parse_node, ClassForwardDeclaredHere);
  85. }
  86. auto Context::AddNameToLookup(Parse::Node name_node, StringId name_id,
  87. SemIR::NodeId target_id) -> void {
  88. if (current_scope().names.insert(name_id).second) {
  89. name_lookup_[name_id].push_back(target_id);
  90. } else {
  91. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back());
  92. }
  93. }
  94. auto Context::LookupName(Parse::Node parse_node, StringId name_id,
  95. SemIR::NameScopeId scope_id, bool print_diagnostics)
  96. -> SemIR::NodeId {
  97. if (scope_id == SemIR::NameScopeId::Invalid) {
  98. auto it = name_lookup_.find(name_id);
  99. if (it == name_lookup_.end()) {
  100. if (print_diagnostics) {
  101. DiagnoseNameNotFound(parse_node, name_id);
  102. }
  103. return SemIR::NodeId::BuiltinError;
  104. }
  105. CARBON_CHECK(!it->second.empty())
  106. << "Should have been erased: " << semantics_ir_->strings().Get(name_id);
  107. // TODO: Check for ambiguous lookups.
  108. return it->second.back();
  109. } else {
  110. const auto& scope = semantics_ir_->GetNameScope(scope_id);
  111. auto it = scope.find(name_id);
  112. if (it == scope.end()) {
  113. if (print_diagnostics) {
  114. DiagnoseNameNotFound(parse_node, name_id);
  115. }
  116. return SemIR::NodeId::BuiltinError;
  117. }
  118. return it->second;
  119. }
  120. }
  121. auto Context::PushScope(SemIR::NameScopeId scope_id) -> void {
  122. scope_stack_.push_back({.scope_id = scope_id});
  123. }
  124. auto Context::PopScope() -> void {
  125. auto scope = scope_stack_.pop_back_val();
  126. for (const auto& str_id : scope.names) {
  127. auto it = name_lookup_.find(str_id);
  128. if (it->second.size() == 1) {
  129. // Erase names that no longer resolve.
  130. name_lookup_.erase(it);
  131. } else {
  132. it->second.pop_back();
  133. }
  134. }
  135. }
  136. auto Context::FollowNameReferences(SemIR::NodeId node_id) -> SemIR::NodeId {
  137. while (auto name_ref =
  138. semantics_ir().GetNode(node_id).TryAs<SemIR::NameReference>()) {
  139. node_id = name_ref->value_id;
  140. }
  141. return node_id;
  142. }
  143. template <typename BranchNode, typename... Args>
  144. static auto AddDominatedBlockAndBranchImpl(Context& context,
  145. Parse::Node parse_node, Args... args)
  146. -> SemIR::NodeBlockId {
  147. if (!context.node_block_stack().is_current_block_reachable()) {
  148. return SemIR::NodeBlockId::Unreachable;
  149. }
  150. auto block_id = context.semantics_ir().AddNodeBlockId();
  151. context.AddNode(BranchNode{parse_node, block_id, args...});
  152. return block_id;
  153. }
  154. auto Context::AddDominatedBlockAndBranch(Parse::Node parse_node)
  155. -> SemIR::NodeBlockId {
  156. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, parse_node);
  157. }
  158. auto Context::AddDominatedBlockAndBranchWithArg(Parse::Node parse_node,
  159. SemIR::NodeId arg_id)
  160. -> SemIR::NodeBlockId {
  161. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, parse_node,
  162. arg_id);
  163. }
  164. auto Context::AddDominatedBlockAndBranchIf(Parse::Node parse_node,
  165. SemIR::NodeId cond_id)
  166. -> SemIR::NodeBlockId {
  167. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, parse_node,
  168. cond_id);
  169. }
  170. auto Context::AddConvergenceBlockAndPush(Parse::Node parse_node, int num_blocks)
  171. -> void {
  172. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  173. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  174. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  175. if (node_block_stack().is_current_block_reachable()) {
  176. if (new_block_id == SemIR::NodeBlockId::Unreachable) {
  177. new_block_id = semantics_ir().AddNodeBlockId();
  178. }
  179. AddNode(SemIR::Branch{parse_node, new_block_id});
  180. }
  181. node_block_stack().Pop();
  182. }
  183. node_block_stack().Push(new_block_id);
  184. }
  185. auto Context::AddConvergenceBlockWithArgAndPush(
  186. Parse::Node parse_node, std::initializer_list<SemIR::NodeId> block_args)
  187. -> SemIR::NodeId {
  188. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  189. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  190. for (auto arg_id : block_args) {
  191. if (node_block_stack().is_current_block_reachable()) {
  192. if (new_block_id == SemIR::NodeBlockId::Unreachable) {
  193. new_block_id = semantics_ir().AddNodeBlockId();
  194. }
  195. AddNode(SemIR::BranchWithArg{parse_node, new_block_id, arg_id});
  196. }
  197. node_block_stack().Pop();
  198. }
  199. node_block_stack().Push(new_block_id);
  200. // Acquire the result value.
  201. SemIR::TypeId result_type_id =
  202. semantics_ir().GetNode(*block_args.begin()).type_id();
  203. return AddNode(SemIR::BlockArg{parse_node, result_type_id, new_block_id});
  204. }
  205. // Add the current code block to the enclosing function.
  206. auto Context::AddCurrentCodeBlockToFunction() -> void {
  207. CARBON_CHECK(!node_block_stack().empty()) << "no current code block";
  208. CARBON_CHECK(!return_scope_stack().empty()) << "no current function";
  209. if (!node_block_stack().is_current_block_reachable()) {
  210. // Don't include unreachable blocks in the function.
  211. return;
  212. }
  213. auto function_id =
  214. semantics_ir()
  215. .GetNodeAs<SemIR::FunctionDeclaration>(return_scope_stack().back())
  216. .function_id;
  217. semantics_ir()
  218. .GetFunction(function_id)
  219. .body_block_ids.push_back(node_block_stack().PeekOrAdd());
  220. }
  221. auto Context::is_current_position_reachable() -> bool {
  222. if (!node_block_stack().is_current_block_reachable()) {
  223. return false;
  224. }
  225. // Our current position is at the end of a reachable block. That position is
  226. // reachable unless the previous instruction is a terminator instruction.
  227. auto block_contents = node_block_stack().PeekCurrentBlockContents();
  228. if (block_contents.empty()) {
  229. return true;
  230. }
  231. const auto& last_node = semantics_ir().GetNode(block_contents.back());
  232. return last_node.kind().terminator_kind() !=
  233. SemIR::TerminatorKind::Terminator;
  234. }
  235. auto Context::ParamOrArgStart() -> void { params_or_args_stack_.Push(); }
  236. auto Context::ParamOrArgComma() -> void {
  237. ParamOrArgSave(node_stack_.PopExpression());
  238. }
  239. auto Context::ParamOrArgEndNoPop(Parse::NodeKind start_kind) -> void {
  240. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  241. ParamOrArgSave(node_stack_.PopExpression());
  242. }
  243. }
  244. auto Context::ParamOrArgPop() -> SemIR::NodeBlockId {
  245. return params_or_args_stack_.Pop();
  246. }
  247. auto Context::ParamOrArgEnd(Parse::NodeKind start_kind) -> SemIR::NodeBlockId {
  248. ParamOrArgEndNoPop(start_kind);
  249. return ParamOrArgPop();
  250. }
  251. namespace {
  252. // Worklist-based type completion mechanism.
  253. //
  254. // When attempting to complete a type, we may find other types that also need to
  255. // be completed: types nested within that type, and the value representation of
  256. // the type. In order to complete a type without recursing arbitrarily deeply,
  257. // we use a worklist of tasks:
  258. //
  259. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  260. // nested within a type to the work list.
  261. // - A `BuildValueRepresentation` step computes the value representation for a
  262. // type, once all of its nested types are complete, and marks the type as
  263. // complete.
  264. class TypeCompleter {
  265. public:
  266. TypeCompleter(
  267. Context& context,
  268. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  269. diagnoser)
  270. : context_(context), diagnoser_(diagnoser) {}
  271. // Attempts to complete the given type. Returns true if it is now complete,
  272. // false if it could not be completed.
  273. auto Complete(SemIR::TypeId type_id) -> bool {
  274. Push(type_id);
  275. while (!work_list_.empty()) {
  276. if (!ProcessStep()) {
  277. return false;
  278. }
  279. }
  280. return true;
  281. }
  282. private:
  283. // Adds `type_id` to the work list, if it's not already complete.
  284. auto Push(SemIR::TypeId type_id) -> void {
  285. if (!context_.semantics_ir().IsTypeComplete(type_id)) {
  286. work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes});
  287. }
  288. }
  289. // Runs the next step.
  290. auto ProcessStep() -> bool {
  291. auto [type_id, phase] = work_list_.back();
  292. // We might have enqueued the same type more than once. Just skip the
  293. // type if it's already complete.
  294. if (context_.semantics_ir().IsTypeComplete(type_id)) {
  295. work_list_.pop_back();
  296. return true;
  297. }
  298. auto node_id = context_.semantics_ir().GetTypeAllowBuiltinTypes(type_id);
  299. auto node = context_.semantics_ir().GetNode(node_id);
  300. auto old_work_list_size = work_list_.size();
  301. switch (phase) {
  302. case Phase::AddNestedIncompleteTypes:
  303. if (!AddNestedIncompleteTypes(node)) {
  304. return false;
  305. }
  306. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  307. << "AddNestedIncompleteTypes should not remove work items";
  308. work_list_[old_work_list_size - 1].phase =
  309. Phase::BuildValueRepresentation;
  310. break;
  311. case Phase::BuildValueRepresentation: {
  312. auto value_rep = BuildValueRepresentation(type_id, node);
  313. context_.semantics_ir().CompleteType(type_id, value_rep);
  314. CARBON_CHECK(old_work_list_size == work_list_.size())
  315. << "BuildValueRepresentation should not change work items";
  316. work_list_.pop_back();
  317. // Also complete the value representation type, if necessary. This
  318. // should never fail: the value representation shouldn't require any
  319. // additional nested types to be complete.
  320. if (!context_.semantics_ir().IsTypeComplete(value_rep.type_id)) {
  321. work_list_.push_back(
  322. {value_rep.type_id, Phase::BuildValueRepresentation});
  323. }
  324. break;
  325. }
  326. }
  327. return true;
  328. }
  329. // Adds any types nested within `type_node` that need to be complete for
  330. // `type_node` to be complete to our work list.
  331. auto AddNestedIncompleteTypes(SemIR::Node type_node) -> bool {
  332. switch (type_node.kind()) {
  333. case SemIR::ArrayType::Kind:
  334. Push(type_node.As<SemIR::ArrayType>().element_type_id);
  335. break;
  336. case SemIR::StructType::Kind:
  337. for (auto field_id : context_.semantics_ir().GetNodeBlock(
  338. type_node.As<SemIR::StructType>().fields_id)) {
  339. Push(context_.semantics_ir()
  340. .GetNodeAs<SemIR::StructTypeField>(field_id)
  341. .field_type_id);
  342. }
  343. break;
  344. case SemIR::TupleType::Kind:
  345. for (auto element_type_id : context_.semantics_ir().GetTypeBlock(
  346. type_node.As<SemIR::TupleType>().elements_id)) {
  347. Push(element_type_id);
  348. }
  349. break;
  350. case SemIR::ClassDeclaration::Kind:
  351. // TODO: Support class definitions and complete class types.
  352. if (diagnoser_) {
  353. auto builder = (*diagnoser_)();
  354. context_.NoteIncompleteClass(type_node.As<SemIR::ClassDeclaration>(),
  355. builder);
  356. builder.Emit();
  357. }
  358. return false;
  359. case SemIR::ConstType::Kind:
  360. Push(type_node.As<SemIR::ConstType>().inner_id);
  361. break;
  362. default:
  363. break;
  364. }
  365. return true;
  366. }
  367. // Makes an empty value representation, which is used for types that have no
  368. // state, such as empty structs and tuples.
  369. auto MakeEmptyRepresentation(Parse::Node parse_node) const
  370. -> SemIR::ValueRepresentation {
  371. return {.kind = SemIR::ValueRepresentation::None,
  372. .type_id = context_.CanonicalizeTupleType(parse_node, {})};
  373. }
  374. // Makes a value representation that uses pass-by-copy, copying the given
  375. // type.
  376. auto MakeCopyRepresentation(SemIR::TypeId rep_id) const
  377. -> SemIR::ValueRepresentation {
  378. return {.kind = SemIR::ValueRepresentation::Copy, .type_id = rep_id};
  379. }
  380. // Makes a value representation that uses pass-by-address with the given
  381. // pointee type.
  382. auto MakePointerRepresentation(Parse::Node parse_node,
  383. SemIR::TypeId pointee_id) const
  384. -> SemIR::ValueRepresentation {
  385. // TODO: Should we add `const` qualification to `pointee_id`?
  386. return {.kind = SemIR::ValueRepresentation::Pointer,
  387. .type_id = context_.GetPointerType(parse_node, pointee_id)};
  388. }
  389. // Gets the value representation of a nested type, which should already be
  390. // complete.
  391. auto GetNestedValueRepresentation(SemIR::TypeId nested_type_id) const {
  392. CARBON_CHECK(context_.semantics_ir().IsTypeComplete(nested_type_id))
  393. << "Nested type should already be complete";
  394. auto value_rep =
  395. context_.semantics_ir().GetValueRepresentation(nested_type_id);
  396. CARBON_CHECK(value_rep.kind != SemIR::ValueRepresentation::Unknown)
  397. << "Complete type should have a value representation";
  398. return value_rep;
  399. };
  400. auto BuildCrossReferenceValueRepresentation(SemIR::TypeId type_id,
  401. SemIR::CrossReference xref) const
  402. -> SemIR::ValueRepresentation {
  403. auto xref_node = context_.semantics_ir()
  404. .GetCrossReferenceIR(xref.ir_id)
  405. .GetNode(xref.node_id);
  406. // The canonical description of a type should only have cross-references
  407. // for entities owned by another File, such as builtins, which are owned
  408. // by the prelude, and named entities like classes and interfaces, which
  409. // we don't support yet.
  410. CARBON_CHECK(xref_node.kind() == SemIR::Builtin::Kind)
  411. << "TODO: Handle other kinds of node cross-references";
  412. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  413. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  414. switch (xref_node.As<SemIR::Builtin>().builtin_kind) {
  415. case SemIR::BuiltinKind::TypeType:
  416. case SemIR::BuiltinKind::Error:
  417. case SemIR::BuiltinKind::Invalid:
  418. case SemIR::BuiltinKind::BoolType:
  419. case SemIR::BuiltinKind::IntegerType:
  420. case SemIR::BuiltinKind::FloatingPointType:
  421. case SemIR::BuiltinKind::NamespaceType:
  422. case SemIR::BuiltinKind::FunctionType:
  423. return MakeCopyRepresentation(type_id);
  424. case SemIR::BuiltinKind::StringType:
  425. // TODO: Decide on string value semantics. This should probably be a
  426. // custom value representation carrying a pointer and size or
  427. // similar.
  428. return MakePointerRepresentation(Parse::Node::Invalid, type_id);
  429. }
  430. llvm_unreachable("All builtin kinds were handled above");
  431. }
  432. auto BuildStructTypeValueRepresentation(SemIR::TypeId type_id,
  433. SemIR::StructType struct_type) const
  434. -> SemIR::ValueRepresentation {
  435. // TODO: Share code with tuples.
  436. auto fields = context_.semantics_ir().GetNodeBlock(struct_type.fields_id);
  437. if (fields.empty()) {
  438. return MakeEmptyRepresentation(struct_type.parse_node);
  439. }
  440. // Find the value representation for each field, and construct a struct
  441. // of value representations.
  442. llvm::SmallVector<SemIR::NodeId> value_rep_fields;
  443. value_rep_fields.reserve(fields.size());
  444. bool same_as_object_rep = true;
  445. for (auto field_id : fields) {
  446. auto field =
  447. context_.semantics_ir().GetNodeAs<SemIR::StructTypeField>(field_id);
  448. auto field_value_rep = GetNestedValueRepresentation(field.field_type_id);
  449. if (field_value_rep.type_id != field.field_type_id) {
  450. same_as_object_rep = false;
  451. field.field_type_id = field_value_rep.type_id;
  452. field_id = context_.AddNode(field);
  453. }
  454. value_rep_fields.push_back(field_id);
  455. }
  456. auto value_rep =
  457. same_as_object_rep
  458. ? type_id
  459. : context_.CanonicalizeStructType(
  460. struct_type.parse_node,
  461. context_.semantics_ir().AddNodeBlock(value_rep_fields));
  462. if (fields.size() == 1) {
  463. // The value representation for a struct with a single field is a
  464. // struct containing the value representation of the field.
  465. // TODO: Consider doing the same for structs with multiple small
  466. // fields.
  467. return MakeCopyRepresentation(value_rep);
  468. }
  469. // For a struct with multiple fields, we use a pointer representation.
  470. return MakePointerRepresentation(struct_type.parse_node, value_rep);
  471. }
  472. auto BuildTupleTypeValueRepresentation(SemIR::TypeId type_id,
  473. SemIR::TupleType tuple_type) const
  474. -> SemIR::ValueRepresentation {
  475. // TODO: Share code with structs.
  476. auto elements =
  477. context_.semantics_ir().GetTypeBlock(tuple_type.elements_id);
  478. if (elements.empty()) {
  479. return MakeEmptyRepresentation(tuple_type.parse_node);
  480. }
  481. // Find the value representation for each element, and construct a tuple
  482. // of value representations.
  483. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  484. value_rep_elements.reserve(elements.size());
  485. bool same_as_object_rep = true;
  486. for (auto element_type_id : elements) {
  487. auto element_value_rep = GetNestedValueRepresentation(element_type_id);
  488. if (element_value_rep.type_id != element_type_id) {
  489. same_as_object_rep = false;
  490. }
  491. value_rep_elements.push_back(element_value_rep.type_id);
  492. }
  493. auto value_rep = same_as_object_rep
  494. ? type_id
  495. : context_.CanonicalizeTupleType(tuple_type.parse_node,
  496. value_rep_elements);
  497. if (elements.size() == 1) {
  498. // The value representation for a tuple with a single element is a
  499. // tuple containing the value representation of that element.
  500. // TODO: Consider doing the same for tuples with multiple small
  501. // elements.
  502. return MakeCopyRepresentation(value_rep);
  503. }
  504. // For a tuple with multiple elements, we use a pointer representation.
  505. return MakePointerRepresentation(tuple_type.parse_node, value_rep);
  506. }
  507. // Builds and returns the value representation for the given type. All nested
  508. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  509. auto BuildValueRepresentation(SemIR::TypeId type_id, SemIR::Node node) const
  510. -> SemIR::ValueRepresentation {
  511. // TODO: This can emit new SemIR nodes. Consider emitting them into a
  512. // dedicated file-scope node block where possible, or somewhere else that
  513. // better reflects the definition of the type, rather than wherever the
  514. // type happens to first be required to be complete.
  515. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  516. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  517. switch (node.kind()) {
  518. case SemIR::AddressOf::Kind:
  519. case SemIR::ArrayIndex::Kind:
  520. case SemIR::ArrayInit::Kind:
  521. case SemIR::Assign::Kind:
  522. case SemIR::BinaryOperatorAdd::Kind:
  523. case SemIR::BindName::Kind:
  524. case SemIR::BindValue::Kind:
  525. case SemIR::BlockArg::Kind:
  526. case SemIR::BoolLiteral::Kind:
  527. case SemIR::Branch::Kind:
  528. case SemIR::BranchIf::Kind:
  529. case SemIR::BranchWithArg::Kind:
  530. case SemIR::Call::Kind:
  531. case SemIR::Dereference::Kind:
  532. case SemIR::FunctionDeclaration::Kind:
  533. case SemIR::InitializeFrom::Kind:
  534. case SemIR::IntegerLiteral::Kind:
  535. case SemIR::NameReference::Kind:
  536. case SemIR::Namespace::Kind:
  537. case SemIR::NoOp::Kind:
  538. case SemIR::Parameter::Kind:
  539. case SemIR::RealLiteral::Kind:
  540. case SemIR::Return::Kind:
  541. case SemIR::ReturnExpression::Kind:
  542. case SemIR::SpliceBlock::Kind:
  543. case SemIR::StringLiteral::Kind:
  544. case SemIR::StructAccess::Kind:
  545. case SemIR::StructTypeField::Kind:
  546. case SemIR::StructLiteral::Kind:
  547. case SemIR::StructInit::Kind:
  548. case SemIR::StructValue::Kind:
  549. case SemIR::Temporary::Kind:
  550. case SemIR::TemporaryStorage::Kind:
  551. case SemIR::TupleAccess::Kind:
  552. case SemIR::TupleIndex::Kind:
  553. case SemIR::TupleLiteral::Kind:
  554. case SemIR::TupleInit::Kind:
  555. case SemIR::TupleValue::Kind:
  556. case SemIR::UnaryOperatorNot::Kind:
  557. case SemIR::ValueAsReference::Kind:
  558. case SemIR::VarStorage::Kind:
  559. CARBON_FATAL() << "Type refers to non-type node " << node;
  560. case SemIR::CrossReference::Kind:
  561. return BuildCrossReferenceValueRepresentation(
  562. type_id, node.As<SemIR::CrossReference>());
  563. case SemIR::ArrayType::Kind: {
  564. // For arrays, it's convenient to always use a pointer representation,
  565. // even when the array has zero or one element, in order to support
  566. // indexing.
  567. return MakePointerRepresentation(node.parse_node(), type_id);
  568. }
  569. case SemIR::StructType::Kind:
  570. return BuildStructTypeValueRepresentation(type_id,
  571. node.As<SemIR::StructType>());
  572. case SemIR::TupleType::Kind:
  573. return BuildTupleTypeValueRepresentation(type_id,
  574. node.As<SemIR::TupleType>());
  575. case SemIR::ClassDeclaration::Kind:
  576. // TODO: Support class definitions and complete class types.
  577. CARBON_FATAL() << "Class types are currently never complete";
  578. case SemIR::Builtin::Kind:
  579. CARBON_FATAL() << "Builtins should be named as cross-references";
  580. case SemIR::PointerType::Kind:
  581. return MakeCopyRepresentation(type_id);
  582. case SemIR::ConstType::Kind:
  583. // The value representation of `const T` is the same as that of `T`.
  584. // Objects are not modifiable through their value representations.
  585. return GetNestedValueRepresentation(
  586. node.As<SemIR::ConstType>().inner_id);
  587. }
  588. }
  589. enum class Phase : int8_t {
  590. // The next step is to add nested types to the list of types to complete.
  591. AddNestedIncompleteTypes,
  592. // The next step is to build the value representation for the type.
  593. BuildValueRepresentation,
  594. };
  595. struct WorkItem {
  596. SemIR::TypeId type_id;
  597. Phase phase;
  598. };
  599. Context& context_;
  600. llvm::SmallVector<WorkItem> work_list_;
  601. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  602. diagnoser_;
  603. };
  604. } // namespace
  605. auto Context::TryToCompleteType(
  606. SemIR::TypeId type_id,
  607. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  608. -> bool {
  609. return TypeCompleter(*this, diagnoser).Complete(type_id);
  610. }
  611. auto Context::CanonicalizeTypeImpl(
  612. SemIR::NodeKind kind,
  613. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  614. llvm::function_ref<SemIR::NodeId()> make_node) -> SemIR::TypeId {
  615. llvm::FoldingSetNodeID canonical_id;
  616. kind.Profile(canonical_id);
  617. profile_type(canonical_id);
  618. void* insert_pos;
  619. auto* node =
  620. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  621. if (node != nullptr) {
  622. return node->type_id();
  623. }
  624. auto node_id = make_node();
  625. auto type_id = semantics_ir_->AddType(node_id);
  626. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  627. type_node_storage_.push_back(
  628. std::make_unique<TypeNode>(canonical_id, type_id));
  629. // In a debug build, check that our insertion position is still valid. It
  630. // could have been invalidated by a misbehaving `make_node`.
  631. CARBON_DCHECK([&] {
  632. void* check_insert_pos;
  633. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  634. canonical_id, check_insert_pos);
  635. return !check_node && insert_pos == check_insert_pos;
  636. }()) << "Type was created recursively during canonicalization";
  637. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  638. return type_id;
  639. }
  640. // Compute a fingerprint for a tuple type, for use as a key in a folding set.
  641. static auto ProfileTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids,
  642. llvm::FoldingSetNodeID& canonical_id) -> void {
  643. for (auto type_id : type_ids) {
  644. canonical_id.AddInteger(type_id.index);
  645. }
  646. }
  647. // Compute a fingerprint for a type, for use as a key in a folding set.
  648. static auto ProfileType(Context& semantics_context, SemIR::Node node,
  649. llvm::FoldingSetNodeID& canonical_id) -> void {
  650. switch (node.kind()) {
  651. case SemIR::ArrayType::Kind: {
  652. auto array_type = node.As<SemIR::ArrayType>();
  653. canonical_id.AddInteger(
  654. semantics_context.semantics_ir().GetArrayBoundValue(
  655. array_type.bound_id));
  656. canonical_id.AddInteger(array_type.element_type_id.index);
  657. break;
  658. }
  659. case SemIR::Builtin::Kind:
  660. canonical_id.AddInteger(node.As<SemIR::Builtin>().builtin_kind.AsInt());
  661. break;
  662. case SemIR::ClassDeclaration::Kind:
  663. canonical_id.AddInteger(
  664. node.As<SemIR::ClassDeclaration>().class_id.index);
  665. break;
  666. case SemIR::CrossReference::Kind: {
  667. // TODO: Cross-references should be canonicalized by looking at their
  668. // target rather than treating them as new unique types.
  669. auto xref = node.As<SemIR::CrossReference>();
  670. canonical_id.AddInteger(xref.ir_id.index);
  671. canonical_id.AddInteger(xref.node_id.index);
  672. break;
  673. }
  674. case SemIR::ConstType::Kind:
  675. canonical_id.AddInteger(
  676. semantics_context
  677. .GetUnqualifiedType(node.As<SemIR::ConstType>().inner_id)
  678. .index);
  679. break;
  680. case SemIR::PointerType::Kind:
  681. canonical_id.AddInteger(node.As<SemIR::PointerType>().pointee_id.index);
  682. break;
  683. case SemIR::StructType::Kind: {
  684. auto fields = semantics_context.semantics_ir().GetNodeBlock(
  685. node.As<SemIR::StructType>().fields_id);
  686. for (const auto& field_id : fields) {
  687. auto field =
  688. semantics_context.semantics_ir().GetNodeAs<SemIR::StructTypeField>(
  689. field_id);
  690. canonical_id.AddInteger(field.name_id.index);
  691. canonical_id.AddInteger(field.field_type_id.index);
  692. }
  693. break;
  694. }
  695. case SemIR::TupleType::Kind:
  696. ProfileTupleType(semantics_context.semantics_ir().GetTypeBlock(
  697. node.As<SemIR::TupleType>().elements_id),
  698. canonical_id);
  699. break;
  700. default:
  701. CARBON_FATAL() << "Unexpected type node " << node;
  702. }
  703. }
  704. auto Context::CanonicalizeTypeAndAddNodeIfNew(SemIR::Node node)
  705. -> SemIR::TypeId {
  706. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  707. ProfileType(*this, node, canonical_id);
  708. };
  709. auto make_node = [&] { return AddNode(node); };
  710. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  711. }
  712. auto Context::CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId {
  713. node_id = FollowNameReferences(node_id);
  714. auto it = canonical_types_.find(node_id);
  715. if (it != canonical_types_.end()) {
  716. return it->second;
  717. }
  718. auto node = semantics_ir_->GetNode(node_id);
  719. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  720. ProfileType(*this, node, canonical_id);
  721. };
  722. auto make_node = [&] { return node_id; };
  723. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  724. }
  725. auto Context::CanonicalizeStructType(Parse::Node parse_node,
  726. SemIR::NodeBlockId refs_id)
  727. -> SemIR::TypeId {
  728. return CanonicalizeTypeAndAddNodeIfNew(
  729. SemIR::StructType{parse_node, SemIR::TypeId::TypeType, refs_id});
  730. }
  731. auto Context::CanonicalizeTupleType(Parse::Node parse_node,
  732. llvm::ArrayRef<SemIR::TypeId> type_ids)
  733. -> SemIR::TypeId {
  734. // Defer allocating a SemIR::TypeBlockId until we know this is a new type.
  735. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  736. ProfileTupleType(type_ids, canonical_id);
  737. };
  738. auto make_tuple_node = [&] {
  739. return AddNode(SemIR::TupleType{parse_node, SemIR::TypeId::TypeType,
  740. semantics_ir_->AddTypeBlock(type_ids)});
  741. };
  742. return CanonicalizeTypeImpl(SemIR::TupleType::Kind, profile_tuple,
  743. make_tuple_node);
  744. }
  745. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  746. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  747. auto type_id = CanonicalizeType(SemIR::NodeId::ForBuiltin(kind));
  748. // To keep client code simpler, complete builtin types before returning them.
  749. bool complete = TryToCompleteType(type_id);
  750. CARBON_CHECK(complete) << "Failed to complete builtin type";
  751. return type_id;
  752. }
  753. auto Context::GetPointerType(Parse::Node parse_node,
  754. SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  755. return CanonicalizeTypeAndAddNodeIfNew(
  756. SemIR::PointerType{parse_node, SemIR::TypeId::TypeType, pointee_type_id});
  757. }
  758. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  759. SemIR::Node type_node =
  760. semantics_ir_->GetNode(semantics_ir_->GetTypeAllowBuiltinTypes(type_id));
  761. if (auto const_type = type_node.TryAs<SemIR::ConstType>()) {
  762. return const_type->inner_id;
  763. }
  764. return type_id;
  765. }
  766. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  767. node_stack_.PrintForStackDump(output);
  768. node_block_stack_.PrintForStackDump(output);
  769. params_or_args_stack_.PrintForStackDump(output);
  770. args_type_info_stack_.PrintForStackDump(output);
  771. }
  772. } // namespace Carbon::Check