file.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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_.array_ref()) {
  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. // Prints a list of elements.
  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. // PrintBlock is only used for vectors.
  130. template <typename T>
  131. static auto PrintBlock(llvm::raw_ostream& out, llvm::StringLiteral block_name,
  132. const llvm::SmallVector<T>& blocks) {
  133. out.indent(BaseIndent);
  134. out << block_name << ": [\n";
  135. for (const auto& block : blocks) {
  136. out.indent(BaseIndent + IndentStep);
  137. out << "[\n";
  138. for (const auto& node : block) {
  139. out.indent(BaseIndent + 2 * IndentStep);
  140. out << node << ",\n";
  141. }
  142. out.indent(BaseIndent + IndentStep);
  143. out << "],\n";
  144. }
  145. out.indent(BaseIndent);
  146. out << "]\n";
  147. }
  148. auto File::Print(llvm::raw_ostream& out, bool include_builtins) const -> void {
  149. out << "- filename: " << filename_ << "\n"
  150. << " sem_ir:\n"
  151. << " - cross_reference_irs_size: " << cross_reference_irs_.size()
  152. << "\n";
  153. PrintList(out, "functions", functions_.array_ref());
  154. PrintList(out, "classes", classes_.array_ref());
  155. PrintList(out, "types", types_.array_ref());
  156. PrintBlock(out, "type_blocks", type_blocks_);
  157. llvm::ArrayRef nodes = nodes_;
  158. if (!include_builtins) {
  159. nodes = nodes.drop_front(BuiltinKind::ValidCount);
  160. }
  161. PrintList(out, "nodes", nodes);
  162. PrintBlock(out, "node_blocks", node_blocks_);
  163. }
  164. // Map a node kind representing a type into an integer describing the
  165. // precedence of that type's syntax. Higher numbers correspond to higher
  166. // precedence.
  167. static auto GetTypePrecedence(NodeKind kind) -> int {
  168. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  169. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  170. switch (kind) {
  171. case ArrayType::Kind:
  172. case Builtin::Kind:
  173. case ClassDeclaration::Kind:
  174. case NameReference::Kind:
  175. case StructType::Kind:
  176. case TupleType::Kind:
  177. case ClassType::Kind:
  178. return 0;
  179. case ConstType::Kind:
  180. return -1;
  181. case PointerType::Kind:
  182. return -2;
  183. case CrossReference::Kind:
  184. // TODO: Once we support stringification of cross-references, we'll need
  185. // to determine the precedence of the target of the cross-reference. For
  186. // now, all cross-references refer to builtin types from the prelude.
  187. return 0;
  188. case AddressOf::Kind:
  189. case ArrayIndex::Kind:
  190. case ArrayInit::Kind:
  191. case Assign::Kind:
  192. case BinaryOperatorAdd::Kind:
  193. case BindName::Kind:
  194. case BindValue::Kind:
  195. case BlockArg::Kind:
  196. case BoolLiteral::Kind:
  197. case Branch::Kind:
  198. case BranchIf::Kind:
  199. case BranchWithArg::Kind:
  200. case Call::Kind:
  201. case Dereference::Kind:
  202. case FunctionDeclaration::Kind:
  203. case InitializeFrom::Kind:
  204. case IntegerLiteral::Kind:
  205. case Namespace::Kind:
  206. case NoOp::Kind:
  207. case Parameter::Kind:
  208. case RealLiteral::Kind:
  209. case Return::Kind:
  210. case ReturnExpression::Kind:
  211. case SpliceBlock::Kind:
  212. case StringLiteral::Kind:
  213. case StructAccess::Kind:
  214. case StructTypeField::Kind:
  215. case StructLiteral::Kind:
  216. case StructInit::Kind:
  217. case StructValue::Kind:
  218. case Temporary::Kind:
  219. case TemporaryStorage::Kind:
  220. case TupleAccess::Kind:
  221. case TupleIndex::Kind:
  222. case TupleLiteral::Kind:
  223. case TupleInit::Kind:
  224. case TupleValue::Kind:
  225. case UnaryOperatorNot::Kind:
  226. case ValueAsReference::Kind:
  227. case VarStorage::Kind:
  228. CARBON_FATAL() << "GetTypePrecedence for non-type node kind " << kind;
  229. }
  230. }
  231. auto File::StringifyType(TypeId type_id, bool in_type_context) const
  232. -> std::string {
  233. return StringifyTypeExpression(GetTypeAllowBuiltinTypes(type_id),
  234. in_type_context);
  235. }
  236. auto File::StringifyTypeExpression(NodeId outer_node_id,
  237. bool in_type_context) const -> std::string {
  238. std::string str;
  239. llvm::raw_string_ostream out(str);
  240. struct Step {
  241. // The node to print.
  242. NodeId node_id;
  243. // The index into node_id to print. Not used by all types.
  244. int index = 0;
  245. auto Next() const -> Step {
  246. return {.node_id = node_id, .index = index + 1};
  247. }
  248. };
  249. llvm::SmallVector<Step> steps = {{.node_id = outer_node_id}};
  250. while (!steps.empty()) {
  251. auto step = steps.pop_back_val();
  252. if (!step.node_id.is_valid()) {
  253. out << "<invalid type>";
  254. continue;
  255. }
  256. // Builtins have designated labels.
  257. if (step.node_id.index < BuiltinKind::ValidCount) {
  258. out << BuiltinKind::FromInt(step.node_id.index).label();
  259. continue;
  260. }
  261. auto node = GetNode(step.node_id);
  262. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  263. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  264. switch (node.kind()) {
  265. case ArrayType::Kind: {
  266. auto array = node.As<ArrayType>();
  267. if (step.index == 0) {
  268. out << "[";
  269. steps.push_back(step.Next());
  270. steps.push_back(
  271. {.node_id = GetTypeAllowBuiltinTypes(array.element_type_id)});
  272. } else if (step.index == 1) {
  273. out << "; " << GetArrayBoundValue(array.bound_id) << "]";
  274. }
  275. break;
  276. }
  277. case ClassType::Kind: {
  278. auto class_name_id =
  279. classes().Get(node.As<ClassType>().class_id).name_id;
  280. out << strings().Get(class_name_id);
  281. break;
  282. }
  283. case ConstType::Kind: {
  284. if (step.index == 0) {
  285. out << "const ";
  286. // Add parentheses if required.
  287. auto inner_type_node_id =
  288. GetTypeAllowBuiltinTypes(node.As<ConstType>().inner_id);
  289. if (GetTypePrecedence(GetNode(inner_type_node_id).kind()) <
  290. GetTypePrecedence(node.kind())) {
  291. out << "(";
  292. steps.push_back(step.Next());
  293. }
  294. steps.push_back({.node_id = inner_type_node_id});
  295. } else if (step.index == 1) {
  296. out << ")";
  297. }
  298. break;
  299. }
  300. case NameReference::Kind: {
  301. out << strings().Get(node.As<NameReference>().name_id);
  302. break;
  303. }
  304. case PointerType::Kind: {
  305. if (step.index == 0) {
  306. steps.push_back(step.Next());
  307. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(
  308. node.As<PointerType>().pointee_id)});
  309. } else if (step.index == 1) {
  310. out << "*";
  311. }
  312. break;
  313. }
  314. case StructType::Kind: {
  315. auto refs = GetNodeBlock(node.As<StructType>().fields_id);
  316. if (refs.empty()) {
  317. out << "{}";
  318. break;
  319. } else if (step.index == 0) {
  320. out << "{";
  321. } else if (step.index < static_cast<int>(refs.size())) {
  322. out << ", ";
  323. } else {
  324. out << "}";
  325. break;
  326. }
  327. steps.push_back(step.Next());
  328. steps.push_back({.node_id = refs[step.index]});
  329. break;
  330. }
  331. case StructTypeField::Kind: {
  332. auto field = node.As<StructTypeField>();
  333. out << "." << strings().Get(field.name_id) << ": ";
  334. steps.push_back(
  335. {.node_id = GetTypeAllowBuiltinTypes(field.field_type_id)});
  336. break;
  337. }
  338. case TupleType::Kind: {
  339. auto refs = GetTypeBlock(node.As<TupleType>().elements_id);
  340. if (refs.empty()) {
  341. out << "()";
  342. break;
  343. } else if (step.index == 0) {
  344. out << "(";
  345. } else if (step.index < static_cast<int>(refs.size())) {
  346. out << ", ";
  347. } else {
  348. // A tuple of one element has a comma to disambiguate from an
  349. // expression.
  350. if (step.index == 1) {
  351. out << ",";
  352. }
  353. out << ")";
  354. break;
  355. }
  356. steps.push_back(step.Next());
  357. steps.push_back(
  358. {.node_id = GetTypeAllowBuiltinTypes(refs[step.index])});
  359. break;
  360. }
  361. case AddressOf::Kind:
  362. case ArrayIndex::Kind:
  363. case ArrayInit::Kind:
  364. case Assign::Kind:
  365. case BinaryOperatorAdd::Kind:
  366. case BindName::Kind:
  367. case BindValue::Kind:
  368. case BlockArg::Kind:
  369. case BoolLiteral::Kind:
  370. case Branch::Kind:
  371. case BranchIf::Kind:
  372. case BranchWithArg::Kind:
  373. case Builtin::Kind:
  374. case Call::Kind:
  375. case ClassDeclaration::Kind:
  376. case CrossReference::Kind:
  377. case Dereference::Kind:
  378. case FunctionDeclaration::Kind:
  379. case InitializeFrom::Kind:
  380. case IntegerLiteral::Kind:
  381. case Namespace::Kind:
  382. case NoOp::Kind:
  383. case Parameter::Kind:
  384. case RealLiteral::Kind:
  385. case Return::Kind:
  386. case ReturnExpression::Kind:
  387. case SpliceBlock::Kind:
  388. case StringLiteral::Kind:
  389. case StructAccess::Kind:
  390. case StructLiteral::Kind:
  391. case StructInit::Kind:
  392. case StructValue::Kind:
  393. case Temporary::Kind:
  394. case TemporaryStorage::Kind:
  395. case TupleAccess::Kind:
  396. case TupleIndex::Kind:
  397. case TupleLiteral::Kind:
  398. case TupleInit::Kind:
  399. case TupleValue::Kind:
  400. case UnaryOperatorNot::Kind:
  401. case ValueAsReference::Kind:
  402. case VarStorage::Kind:
  403. // We don't need to handle stringification for nodes that don't show up
  404. // in errors, but make it clear what's going on so that it's clearer
  405. // when stringification is needed.
  406. out << "<cannot stringify " << step.node_id << ">";
  407. break;
  408. }
  409. }
  410. // For `{}` or any tuple type, we've printed a non-type expression, so add a
  411. // conversion to type `type` if it's not implied by the context.
  412. if (!in_type_context) {
  413. auto outer_node = GetNode(outer_node_id);
  414. if (outer_node.Is<TupleType>() ||
  415. (outer_node.Is<StructType>() &&
  416. GetNodeBlock(outer_node.As<StructType>().fields_id).empty())) {
  417. out << " as type";
  418. }
  419. }
  420. return str;
  421. }
  422. auto GetExpressionCategory(const File& file, NodeId node_id)
  423. -> ExpressionCategory {
  424. const File* ir = &file;
  425. while (true) {
  426. auto node = ir->GetNode(node_id);
  427. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  428. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  429. switch (node.kind()) {
  430. case Assign::Kind:
  431. case Branch::Kind:
  432. case BranchIf::Kind:
  433. case BranchWithArg::Kind:
  434. case ClassDeclaration::Kind:
  435. case FunctionDeclaration::Kind:
  436. case Namespace::Kind:
  437. case NoOp::Kind:
  438. case Return::Kind:
  439. case ReturnExpression::Kind:
  440. case StructTypeField::Kind:
  441. return ExpressionCategory::NotExpression;
  442. case CrossReference::Kind: {
  443. auto xref = node.As<CrossReference>();
  444. ir = &ir->GetCrossReferenceIR(xref.ir_id);
  445. node_id = xref.node_id;
  446. continue;
  447. }
  448. case NameReference::Kind: {
  449. node_id = node.As<NameReference>().value_id;
  450. continue;
  451. }
  452. case AddressOf::Kind:
  453. case ArrayType::Kind:
  454. case BinaryOperatorAdd::Kind:
  455. case BindValue::Kind:
  456. case BlockArg::Kind:
  457. case BoolLiteral::Kind:
  458. case ClassType::Kind:
  459. case ConstType::Kind:
  460. case IntegerLiteral::Kind:
  461. case Parameter::Kind:
  462. case PointerType::Kind:
  463. case RealLiteral::Kind:
  464. case StringLiteral::Kind:
  465. case StructValue::Kind:
  466. case StructType::Kind:
  467. case TupleValue::Kind:
  468. case TupleType::Kind:
  469. case UnaryOperatorNot::Kind:
  470. return ExpressionCategory::Value;
  471. case Builtin::Kind: {
  472. if (node.As<Builtin>().builtin_kind == BuiltinKind::Error) {
  473. return ExpressionCategory::Error;
  474. }
  475. return ExpressionCategory::Value;
  476. }
  477. case BindName::Kind: {
  478. node_id = node.As<BindName>().value_id;
  479. continue;
  480. }
  481. case ArrayIndex::Kind: {
  482. node_id = node.As<ArrayIndex>().array_id;
  483. continue;
  484. }
  485. case StructAccess::Kind: {
  486. node_id = node.As<StructAccess>().struct_id;
  487. continue;
  488. }
  489. case TupleAccess::Kind: {
  490. node_id = node.As<TupleAccess>().tuple_id;
  491. continue;
  492. }
  493. case TupleIndex::Kind: {
  494. node_id = node.As<TupleIndex>().tuple_id;
  495. continue;
  496. }
  497. case SpliceBlock::Kind: {
  498. node_id = node.As<SpliceBlock>().result_id;
  499. continue;
  500. }
  501. case StructLiteral::Kind:
  502. case TupleLiteral::Kind:
  503. return ExpressionCategory::Mixed;
  504. case ArrayInit::Kind:
  505. case Call::Kind:
  506. case InitializeFrom::Kind:
  507. case StructInit::Kind:
  508. case TupleInit::Kind:
  509. return ExpressionCategory::Initializing;
  510. case Dereference::Kind:
  511. case VarStorage::Kind:
  512. return ExpressionCategory::DurableReference;
  513. case Temporary::Kind:
  514. case TemporaryStorage::Kind:
  515. case ValueAsReference::Kind:
  516. return ExpressionCategory::EphemeralReference;
  517. }
  518. }
  519. }
  520. auto GetInitializingRepresentation(const File& file, TypeId type_id)
  521. -> InitializingRepresentation {
  522. auto value_rep = GetValueRepresentation(file, type_id);
  523. switch (value_rep.kind) {
  524. case ValueRepresentation::None:
  525. return {.kind = InitializingRepresentation::None};
  526. case ValueRepresentation::Copy:
  527. // TODO: Use in-place initialization for types that have non-trivial
  528. // destructive move.
  529. return {.kind = InitializingRepresentation::ByCopy};
  530. case ValueRepresentation::Pointer:
  531. case ValueRepresentation::Custom:
  532. return {.kind = InitializingRepresentation::InPlace};
  533. case ValueRepresentation::Unknown:
  534. CARBON_FATAL()
  535. << "Attempting to perform initialization of incomplete type";
  536. }
  537. }
  538. } // namespace Carbon::SemIR