context.cpp 32 KB

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