file.cpp 19 KB

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