file.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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/sem_ir/file.h"
  5. #include "common/check.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "toolchain/base/value_store.h"
  9. #include "toolchain/sem_ir/builtin_kind.h"
  10. #include "toolchain/sem_ir/node.h"
  11. #include "toolchain/sem_ir/node_kind.h"
  12. namespace Carbon::SemIR {
  13. auto ValueRepresentation::Print(llvm::raw_ostream& out) const -> void {
  14. out << "{kind: ";
  15. switch (kind) {
  16. case Unknown:
  17. out << "unknown";
  18. break;
  19. case None:
  20. out << "none";
  21. break;
  22. case Copy:
  23. out << "copy";
  24. break;
  25. case Pointer:
  26. out << "pointer";
  27. break;
  28. case Custom:
  29. out << "custom";
  30. break;
  31. }
  32. out << ", type: " << type_id << "}";
  33. }
  34. auto TypeInfo::Print(llvm::raw_ostream& out) const -> void {
  35. out << "{node: " << node_id << ", value_rep: " << value_representation << "}";
  36. }
  37. File::File(SharedValueStores& value_stores)
  38. : value_stores_(&value_stores),
  39. filename_("<builtins>"),
  40. // Builtins are always the first IR, even when self-referential.
  41. cross_reference_irs_({this}),
  42. // Default entry for NodeBlockId::Empty.
  43. node_blocks_(1) {
  44. nodes_.reserve(BuiltinKind::ValidCount);
  45. // Error uses a self-referential type so that it's not accidentally treated as
  46. // a normal type. Every other builtin is a type, including the
  47. // self-referential TypeType.
  48. #define CARBON_SEM_IR_BUILTIN_KIND(Name, ...) \
  49. nodes_.push_back(Builtin{BuiltinKind::Name == BuiltinKind::Error \
  50. ? TypeId::Error \
  51. : TypeId::TypeType, \
  52. BuiltinKind::Name});
  53. #include "toolchain/sem_ir/builtin_kind.def"
  54. CARBON_CHECK(nodes_.size() == BuiltinKind::ValidCount)
  55. << "Builtins should produce " << BuiltinKind::ValidCount
  56. << " nodes, actual: " << nodes_.size();
  57. }
  58. File::File(SharedValueStores& value_stores, std::string filename,
  59. const File* builtins)
  60. : value_stores_(&value_stores),
  61. filename_(std::move(filename)),
  62. // Builtins are always the first IR.
  63. cross_reference_irs_({builtins}),
  64. // Default entry for NodeBlockId::Empty.
  65. node_blocks_(1) {
  66. CARBON_CHECK(builtins != nullptr);
  67. CARBON_CHECK(builtins->cross_reference_irs_[0] == builtins)
  68. << "Not called with builtins!";
  69. // Copy builtins over.
  70. nodes_.reserve(BuiltinKind::ValidCount);
  71. static constexpr auto BuiltinIR = CrossReferenceIRId(0);
  72. for (auto [i, node] : llvm::enumerate(builtins->nodes_)) {
  73. // We can reuse builtin type IDs because they're special-cased values.
  74. nodes_.push_back(
  75. CrossReference{node.type_id(), BuiltinIR, SemIR::NodeId(i)});
  76. }
  77. }
  78. auto File::Verify() const -> ErrorOr<Success> {
  79. // Invariants don't necessarily hold for invalid IR.
  80. if (has_errors_) {
  81. return Success();
  82. }
  83. // Check that every code block has a terminator sequence that appears at the
  84. // end of the block.
  85. for (const Function& function : functions_) {
  86. for (NodeBlockId block_id : function.body_block_ids) {
  87. TerminatorKind prior_kind = TerminatorKind::NotTerminator;
  88. for (NodeId node_id : GetNodeBlock(block_id)) {
  89. TerminatorKind node_kind = GetNode(node_id).kind().terminator_kind();
  90. if (prior_kind == TerminatorKind::Terminator) {
  91. return Error(llvm::formatv("Node {0} in block {1} follows terminator",
  92. node_id, block_id));
  93. }
  94. if (prior_kind > node_kind) {
  95. return Error(
  96. llvm::formatv("Non-terminator node {0} in block {1} follows "
  97. "terminator sequence",
  98. node_id, block_id));
  99. }
  100. prior_kind = node_kind;
  101. }
  102. if (prior_kind != TerminatorKind::Terminator) {
  103. return Error(llvm::formatv("No terminator in block {0}", block_id));
  104. }
  105. }
  106. }
  107. // TODO: Check that a node only references other nodes that are either global
  108. // or that dominate it.
  109. return Success();
  110. }
  111. static constexpr int BaseIndent = 4;
  112. static constexpr int IndentStep = 2;
  113. // Define PrintList for ArrayRef.
  114. template <typename T, typename PrintT =
  115. std::function<void(llvm::raw_ostream&, const T& val)>>
  116. static auto PrintList(
  117. llvm::raw_ostream& out, llvm::StringLiteral name, llvm::ArrayRef<T> list,
  118. PrintT print = [](llvm::raw_ostream& out, const T& val) { out << val; }) {
  119. out.indent(BaseIndent);
  120. out << name << ": [\n";
  121. for (const auto& element : list) {
  122. out.indent(BaseIndent + IndentStep);
  123. print(out, element);
  124. out << ",\n";
  125. }
  126. out.indent(BaseIndent);
  127. out << "]\n";
  128. }
  129. // Adapt PrintList for a vector.
  130. template <typename T, typename PrintT =
  131. std::function<void(llvm::raw_ostream&, const T& val)>>
  132. static auto PrintList(
  133. llvm::raw_ostream& out, llvm::StringLiteral name,
  134. const llvm::SmallVector<T>& list,
  135. PrintT print = [](llvm::raw_ostream& out, const T& val) { out << val; }) {
  136. PrintList(out, name, llvm::ArrayRef(list), print);
  137. }
  138. // PrintBlock is only used for vectors.
  139. template <typename T>
  140. static auto PrintBlock(llvm::raw_ostream& out, llvm::StringLiteral block_name,
  141. const llvm::SmallVector<T>& blocks) {
  142. out.indent(BaseIndent);
  143. out << block_name << ": [\n";
  144. for (const auto& block : blocks) {
  145. out.indent(BaseIndent + IndentStep);
  146. out << "[\n";
  147. for (const auto& node : block) {
  148. out.indent(BaseIndent + 2 * IndentStep);
  149. out << node << ",\n";
  150. }
  151. out.indent(BaseIndent + IndentStep);
  152. out << "],\n";
  153. }
  154. out.indent(BaseIndent);
  155. out << "]\n";
  156. }
  157. auto File::Print(llvm::raw_ostream& out, bool include_builtins) const -> void {
  158. out << "- filename: " << filename_ << "\n"
  159. << " sem_ir:\n"
  160. << " - cross_reference_irs_size: " << cross_reference_irs_.size()
  161. << "\n";
  162. PrintList(out, "functions", functions_);
  163. PrintList(out, "classes", classes_);
  164. PrintList(out, "types", types_);
  165. PrintBlock(out, "type_blocks", type_blocks_);
  166. llvm::ArrayRef nodes = nodes_;
  167. if (!include_builtins) {
  168. nodes = nodes.drop_front(BuiltinKind::ValidCount);
  169. }
  170. PrintList(out, "nodes", nodes);
  171. PrintBlock(out, "node_blocks", node_blocks_);
  172. }
  173. // Map a node kind representing a type into an integer describing the
  174. // precedence of that type's syntax. Higher numbers correspond to higher
  175. // precedence.
  176. static auto GetTypePrecedence(NodeKind kind) -> int {
  177. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  178. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  179. switch (kind) {
  180. case ArrayType::Kind:
  181. case Builtin::Kind:
  182. case ClassDeclaration::Kind:
  183. case NameReference::Kind:
  184. case StructType::Kind:
  185. case TupleType::Kind:
  186. return 0;
  187. case ConstType::Kind:
  188. return -1;
  189. case PointerType::Kind:
  190. return -2;
  191. case CrossReference::Kind:
  192. // TODO: Once we support stringification of cross-references, we'll need
  193. // to determine the precedence of the target of the cross-reference. For
  194. // now, all cross-references refer to builtin types from the prelude.
  195. return 0;
  196. case AddressOf::Kind:
  197. case ArrayIndex::Kind:
  198. case ArrayInit::Kind:
  199. case Assign::Kind:
  200. case BinaryOperatorAdd::Kind:
  201. case BindName::Kind:
  202. case BindValue::Kind:
  203. case BlockArg::Kind:
  204. case BoolLiteral::Kind:
  205. case Branch::Kind:
  206. case BranchIf::Kind:
  207. case BranchWithArg::Kind:
  208. case Call::Kind:
  209. case Dereference::Kind:
  210. case FunctionDeclaration::Kind:
  211. case InitializeFrom::Kind:
  212. case IntegerLiteral::Kind:
  213. case Namespace::Kind:
  214. case NoOp::Kind:
  215. case Parameter::Kind:
  216. case RealLiteral::Kind:
  217. case Return::Kind:
  218. case ReturnExpression::Kind:
  219. case SpliceBlock::Kind:
  220. case StringLiteral::Kind:
  221. case StructAccess::Kind:
  222. case StructTypeField::Kind:
  223. case StructLiteral::Kind:
  224. case StructInit::Kind:
  225. case StructValue::Kind:
  226. case Temporary::Kind:
  227. case TemporaryStorage::Kind:
  228. case TupleAccess::Kind:
  229. case TupleIndex::Kind:
  230. case TupleLiteral::Kind:
  231. case TupleInit::Kind:
  232. case TupleValue::Kind:
  233. case UnaryOperatorNot::Kind:
  234. case ValueAsReference::Kind:
  235. case VarStorage::Kind:
  236. CARBON_FATAL() << "GetTypePrecedence for non-type node kind " << kind;
  237. }
  238. }
  239. auto File::StringifyType(TypeId type_id, bool in_type_context) const
  240. -> std::string {
  241. return StringifyTypeExpression(GetTypeAllowBuiltinTypes(type_id),
  242. in_type_context);
  243. }
  244. auto File::StringifyTypeExpression(NodeId outer_node_id,
  245. bool in_type_context) const -> std::string {
  246. std::string str;
  247. llvm::raw_string_ostream out(str);
  248. struct Step {
  249. // The node to print.
  250. NodeId node_id;
  251. // The index into node_id to print. Not used by all types.
  252. int index = 0;
  253. auto Next() const -> Step {
  254. return {.node_id = node_id, .index = index + 1};
  255. }
  256. };
  257. llvm::SmallVector<Step> steps = {{.node_id = outer_node_id}};
  258. while (!steps.empty()) {
  259. auto step = steps.pop_back_val();
  260. if (!step.node_id.is_valid()) {
  261. out << "<invalid type>";
  262. continue;
  263. }
  264. // Builtins have designated labels.
  265. if (step.node_id.index < BuiltinKind::ValidCount) {
  266. out << BuiltinKind::FromInt(step.node_id.index).label();
  267. continue;
  268. }
  269. auto node = GetNode(step.node_id);
  270. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  271. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  272. switch (node.kind()) {
  273. case ArrayType::Kind: {
  274. auto array = node.As<ArrayType>();
  275. if (step.index == 0) {
  276. out << "[";
  277. steps.push_back(step.Next());
  278. steps.push_back(
  279. {.node_id = GetTypeAllowBuiltinTypes(array.element_type_id)});
  280. } else if (step.index == 1) {
  281. out << "; " << GetArrayBoundValue(array.bound_id) << "]";
  282. }
  283. break;
  284. }
  285. case ClassDeclaration::Kind: {
  286. auto class_name_id =
  287. GetClass(node.As<ClassDeclaration>().class_id).name_id;
  288. out << strings().Get(class_name_id);
  289. break;
  290. }
  291. case ConstType::Kind: {
  292. if (step.index == 0) {
  293. out << "const ";
  294. // Add parentheses if required.
  295. auto inner_type_node_id =
  296. GetTypeAllowBuiltinTypes(node.As<ConstType>().inner_id);
  297. if (GetTypePrecedence(GetNode(inner_type_node_id).kind()) <
  298. GetTypePrecedence(node.kind())) {
  299. out << "(";
  300. steps.push_back(step.Next());
  301. }
  302. steps.push_back({.node_id = inner_type_node_id});
  303. } else if (step.index == 1) {
  304. out << ")";
  305. }
  306. break;
  307. }
  308. case NameReference::Kind: {
  309. out << strings().Get(node.As<NameReference>().name_id);
  310. break;
  311. }
  312. case PointerType::Kind: {
  313. if (step.index == 0) {
  314. steps.push_back(step.Next());
  315. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(
  316. node.As<PointerType>().pointee_id)});
  317. } else if (step.index == 1) {
  318. out << "*";
  319. }
  320. break;
  321. }
  322. case StructType::Kind: {
  323. auto refs = GetNodeBlock(node.As<StructType>().fields_id);
  324. if (refs.empty()) {
  325. out << "{}";
  326. break;
  327. } else if (step.index == 0) {
  328. out << "{";
  329. } else if (step.index < static_cast<int>(refs.size())) {
  330. out << ", ";
  331. } else {
  332. out << "}";
  333. break;
  334. }
  335. steps.push_back(step.Next());
  336. steps.push_back({.node_id = refs[step.index]});
  337. break;
  338. }
  339. case StructTypeField::Kind: {
  340. auto field = node.As<StructTypeField>();
  341. out << "." << strings().Get(field.name_id) << ": ";
  342. steps.push_back(
  343. {.node_id = GetTypeAllowBuiltinTypes(field.field_type_id)});
  344. break;
  345. }
  346. case TupleType::Kind: {
  347. auto refs = GetTypeBlock(node.As<TupleType>().elements_id);
  348. if (refs.empty()) {
  349. out << "()";
  350. break;
  351. } else if (step.index == 0) {
  352. out << "(";
  353. } else if (step.index < static_cast<int>(refs.size())) {
  354. out << ", ";
  355. } else {
  356. // A tuple of one element has a comma to disambiguate from an
  357. // expression.
  358. if (step.index == 1) {
  359. out << ",";
  360. }
  361. out << ")";
  362. break;
  363. }
  364. steps.push_back(step.Next());
  365. steps.push_back(
  366. {.node_id = GetTypeAllowBuiltinTypes(refs[step.index])});
  367. break;
  368. }
  369. case AddressOf::Kind:
  370. case ArrayIndex::Kind:
  371. case ArrayInit::Kind:
  372. case Assign::Kind:
  373. case BinaryOperatorAdd::Kind:
  374. case BindName::Kind:
  375. case BindValue::Kind:
  376. case BlockArg::Kind:
  377. case BoolLiteral::Kind:
  378. case Branch::Kind:
  379. case BranchIf::Kind:
  380. case BranchWithArg::Kind:
  381. case Builtin::Kind:
  382. case Call::Kind:
  383. case CrossReference::Kind:
  384. case Dereference::Kind:
  385. case FunctionDeclaration::Kind:
  386. case InitializeFrom::Kind:
  387. case IntegerLiteral::Kind:
  388. case Namespace::Kind:
  389. case NoOp::Kind:
  390. case Parameter::Kind:
  391. case RealLiteral::Kind:
  392. case Return::Kind:
  393. case ReturnExpression::Kind:
  394. case SpliceBlock::Kind:
  395. case StringLiteral::Kind:
  396. case StructAccess::Kind:
  397. case StructLiteral::Kind:
  398. case StructInit::Kind:
  399. case StructValue::Kind:
  400. case Temporary::Kind:
  401. case TemporaryStorage::Kind:
  402. case TupleAccess::Kind:
  403. case TupleIndex::Kind:
  404. case TupleLiteral::Kind:
  405. case TupleInit::Kind:
  406. case TupleValue::Kind:
  407. case UnaryOperatorNot::Kind:
  408. case ValueAsReference::Kind:
  409. case VarStorage::Kind:
  410. // We don't need to handle stringification for nodes that don't show up
  411. // in errors, but make it clear what's going on so that it's clearer
  412. // when stringification is needed.
  413. out << "<cannot stringify " << step.node_id << ">";
  414. break;
  415. }
  416. }
  417. // For `{}` or any tuple type, we've printed a non-type expression, so add a
  418. // conversion to type `type` if it's not implied by the context.
  419. if (!in_type_context) {
  420. auto outer_node = GetNode(outer_node_id);
  421. if (outer_node.Is<TupleType>() ||
  422. (outer_node.Is<StructType>() &&
  423. GetNodeBlock(outer_node.As<StructType>().fields_id).empty())) {
  424. out << " as type";
  425. }
  426. }
  427. return str;
  428. }
  429. auto GetExpressionCategory(const File& file, NodeId node_id)
  430. -> ExpressionCategory {
  431. const File* ir = &file;
  432. while (true) {
  433. auto node = ir->GetNode(node_id);
  434. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  435. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  436. switch (node.kind()) {
  437. case Assign::Kind:
  438. case Branch::Kind:
  439. case BranchIf::Kind:
  440. case BranchWithArg::Kind:
  441. case FunctionDeclaration::Kind:
  442. case Namespace::Kind:
  443. case NoOp::Kind:
  444. case Return::Kind:
  445. case ReturnExpression::Kind:
  446. case StructTypeField::Kind:
  447. return ExpressionCategory::NotExpression;
  448. case CrossReference::Kind: {
  449. auto xref = node.As<CrossReference>();
  450. ir = &ir->GetCrossReferenceIR(xref.ir_id);
  451. node_id = xref.node_id;
  452. continue;
  453. }
  454. case NameReference::Kind: {
  455. node_id = node.As<NameReference>().value_id;
  456. continue;
  457. }
  458. case AddressOf::Kind:
  459. case ArrayType::Kind:
  460. case BinaryOperatorAdd::Kind:
  461. case BindValue::Kind:
  462. case BlockArg::Kind:
  463. case BoolLiteral::Kind:
  464. case ClassDeclaration::Kind:
  465. case ConstType::Kind:
  466. case IntegerLiteral::Kind:
  467. case Parameter::Kind:
  468. case PointerType::Kind:
  469. case RealLiteral::Kind:
  470. case StringLiteral::Kind:
  471. case StructValue::Kind:
  472. case StructType::Kind:
  473. case TupleValue::Kind:
  474. case TupleType::Kind:
  475. case UnaryOperatorNot::Kind:
  476. return ExpressionCategory::Value;
  477. case Builtin::Kind: {
  478. if (node.As<Builtin>().builtin_kind == BuiltinKind::Error) {
  479. return ExpressionCategory::Error;
  480. }
  481. return ExpressionCategory::Value;
  482. }
  483. case BindName::Kind: {
  484. node_id = node.As<BindName>().value_id;
  485. continue;
  486. }
  487. case ArrayIndex::Kind: {
  488. node_id = node.As<ArrayIndex>().array_id;
  489. continue;
  490. }
  491. case StructAccess::Kind: {
  492. node_id = node.As<StructAccess>().struct_id;
  493. continue;
  494. }
  495. case TupleAccess::Kind: {
  496. node_id = node.As<TupleAccess>().tuple_id;
  497. continue;
  498. }
  499. case TupleIndex::Kind: {
  500. node_id = node.As<TupleIndex>().tuple_id;
  501. continue;
  502. }
  503. case SpliceBlock::Kind: {
  504. node_id = node.As<SpliceBlock>().result_id;
  505. continue;
  506. }
  507. case StructLiteral::Kind:
  508. case TupleLiteral::Kind:
  509. return ExpressionCategory::Mixed;
  510. case ArrayInit::Kind:
  511. case Call::Kind:
  512. case InitializeFrom::Kind:
  513. case StructInit::Kind:
  514. case TupleInit::Kind:
  515. return ExpressionCategory::Initializing;
  516. case Dereference::Kind:
  517. case VarStorage::Kind:
  518. return ExpressionCategory::DurableReference;
  519. case Temporary::Kind:
  520. case TemporaryStorage::Kind:
  521. case ValueAsReference::Kind:
  522. return ExpressionCategory::EphemeralReference;
  523. }
  524. }
  525. }
  526. auto GetInitializingRepresentation(const File& file, TypeId type_id)
  527. -> InitializingRepresentation {
  528. auto value_rep = GetValueRepresentation(file, type_id);
  529. switch (value_rep.kind) {
  530. case ValueRepresentation::None:
  531. return {.kind = InitializingRepresentation::None};
  532. case ValueRepresentation::Copy:
  533. // TODO: Use in-place initialization for types that have non-trivial
  534. // destructive move.
  535. return {.kind = InitializingRepresentation::ByCopy};
  536. case ValueRepresentation::Pointer:
  537. case ValueRepresentation::Custom:
  538. return {.kind = InitializingRepresentation::InPlace};
  539. case ValueRepresentation::Unknown:
  540. CARBON_FATAL()
  541. << "Attempting to perform initialization of incomplete type";
  542. }
  543. }
  544. } // namespace Carbon::SemIR