file.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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/ids.h"
  12. #include "toolchain/sem_ir/inst.h"
  13. #include "toolchain/sem_ir/inst_kind.h"
  14. namespace Carbon::SemIR {
  15. auto ValueRepr::Print(llvm::raw_ostream& out) const -> void {
  16. out << "{kind: ";
  17. switch (kind) {
  18. case Unknown:
  19. out << "unknown";
  20. break;
  21. case None:
  22. out << "none";
  23. break;
  24. case Copy:
  25. out << "copy";
  26. break;
  27. case Pointer:
  28. out << "pointer";
  29. break;
  30. case Custom:
  31. out << "custom";
  32. break;
  33. }
  34. out << ", type: " << type_id << "}";
  35. }
  36. auto TypeInfo::Print(llvm::raw_ostream& out) const -> void {
  37. out << "{inst: " << inst_id << ", value_rep: " << value_repr << "}";
  38. }
  39. File::File(SharedValueStores& value_stores)
  40. : value_stores_(&value_stores),
  41. filename_("<builtins>"),
  42. type_blocks_(allocator_),
  43. inst_blocks_(allocator_) {
  44. auto builtins_id = cross_ref_irs_.Add(this);
  45. CARBON_CHECK(builtins_id == CrossRefIRId::Builtins)
  46. << "Builtins must be the first IR, even if self-referential";
  47. // Default entry for InstBlockId::Empty.
  48. inst_blocks_.AddDefaultValue();
  49. insts_.Reserve(BuiltinKind::ValidCount);
  50. // Error uses a self-referential type so that it's not accidentally treated as
  51. // a normal type. Every other builtin is a type, including the
  52. // self-referential TypeType.
  53. #define CARBON_SEM_IR_BUILTIN_KIND(Name, ...) \
  54. insts_.AddInNoBlock(Builtin{BuiltinKind::Name == BuiltinKind::Error \
  55. ? TypeId::Error \
  56. : TypeId::TypeType, \
  57. BuiltinKind::Name});
  58. #include "toolchain/sem_ir/builtin_kind.def"
  59. CARBON_CHECK(insts_.size() == BuiltinKind::ValidCount)
  60. << "Builtins should produce " << BuiltinKind::ValidCount
  61. << " insts, actual: " << insts_.size();
  62. }
  63. File::File(SharedValueStores& value_stores, std::string filename,
  64. const File* builtins)
  65. : value_stores_(&value_stores),
  66. filename_(std::move(filename)),
  67. type_blocks_(allocator_),
  68. inst_blocks_(allocator_) {
  69. CARBON_CHECK(builtins != nullptr);
  70. auto builtins_id = cross_ref_irs_.Add(builtins);
  71. CARBON_CHECK(builtins_id == CrossRefIRId::Builtins)
  72. << "Builtins must be the first IR";
  73. // Default entry for InstBlockId::Empty.
  74. inst_blocks_.AddDefaultValue();
  75. // Copy builtins over.
  76. insts_.Reserve(BuiltinKind::ValidCount);
  77. static constexpr auto BuiltinIR = CrossRefIRId(0);
  78. for (auto [i, inst] : llvm::enumerate(builtins->insts_.array_ref())) {
  79. // We can reuse builtin type IDs because they're special-cased values.
  80. insts_.AddInNoBlock(CrossRef{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_ref_irs_size",
  123. Yaml::OutputScalar(cross_ref_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 NameRef::Kind:
  153. case StructType::Kind:
  154. case TupleType::Kind:
  155. case UnboundElementType::Kind:
  156. return 0;
  157. case ConstType::Kind:
  158. return -1;
  159. case PointerType::Kind:
  160. return -2;
  161. case CrossRef::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 BaseDecl::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 ClassDecl::Kind:
  181. case ClassElementAccess::Kind:
  182. case ClassInit::Kind:
  183. case Converted::Kind:
  184. case Deref::Kind:
  185. case FieldDecl::Kind:
  186. case FunctionDecl::Kind:
  187. case Import::Kind:
  188. case InitializeFrom::Kind:
  189. case InterfaceDecl::Kind:
  190. case IntLiteral::Kind:
  191. case LazyImportRef::Kind:
  192. case Namespace::Kind:
  193. case NoOp::Kind:
  194. case Param::Kind:
  195. case RealLiteral::Kind:
  196. case Return::Kind:
  197. case ReturnExpr::Kind:
  198. case SelfParam::Kind:
  199. case SpliceBlock::Kind:
  200. case StringLiteral::Kind:
  201. case StructAccess::Kind:
  202. case StructTypeField::Kind:
  203. case StructLiteral::Kind:
  204. case StructInit::Kind:
  205. case StructValue::Kind:
  206. case Temporary::Kind:
  207. case TemporaryStorage::Kind:
  208. case TupleAccess::Kind:
  209. case TupleIndex::Kind:
  210. case TupleLiteral::Kind:
  211. case TupleInit::Kind:
  212. case TupleValue::Kind:
  213. case UnaryOperatorNot::Kind:
  214. case ValueAsRef::Kind:
  215. case ValueOfInitializer::Kind:
  216. case VarStorage::Kind:
  217. CARBON_FATAL() << "GetTypePrecedence for non-type inst kind " << kind;
  218. }
  219. }
  220. auto File::StringifyType(TypeId type_id) const -> std::string {
  221. return StringifyTypeExpr(types().GetInstId(type_id));
  222. }
  223. auto File::StringifyTypeExpr(InstId outer_inst_id) const -> std::string {
  224. std::string str;
  225. llvm::raw_string_ostream out(str);
  226. struct Step {
  227. // The instruction to print.
  228. InstId inst_id;
  229. // The index into inst_id to print. Not used by all types.
  230. int index = 0;
  231. auto Next() const -> Step {
  232. return {.inst_id = inst_id, .index = index + 1};
  233. }
  234. };
  235. llvm::SmallVector<Step> steps = {{.inst_id = outer_inst_id}};
  236. while (!steps.empty()) {
  237. auto step = steps.pop_back_val();
  238. if (!step.inst_id.is_valid()) {
  239. out << "<invalid type>";
  240. continue;
  241. }
  242. // Builtins have designated labels.
  243. if (step.inst_id.index < BuiltinKind::ValidCount) {
  244. out << BuiltinKind::FromInt(step.inst_id.index).label();
  245. continue;
  246. }
  247. auto inst = insts().Get(step.inst_id);
  248. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  249. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  250. switch (inst.kind()) {
  251. case ArrayType::Kind: {
  252. auto array = inst.As<ArrayType>();
  253. if (step.index == 0) {
  254. out << "[";
  255. steps.push_back(step.Next());
  256. steps.push_back(
  257. {.inst_id = types().GetInstId(array.element_type_id)});
  258. } else if (step.index == 1) {
  259. out << "; " << GetArrayBoundValue(array.bound_id) << "]";
  260. }
  261. break;
  262. }
  263. case ClassType::Kind: {
  264. auto class_name_id =
  265. classes().Get(inst.As<ClassType>().class_id).name_id;
  266. out << names().GetFormatted(class_name_id);
  267. break;
  268. }
  269. case ConstType::Kind: {
  270. if (step.index == 0) {
  271. out << "const ";
  272. // Add parentheses if required.
  273. auto inner_type_inst_id =
  274. types().GetInstId(inst.As<ConstType>().inner_id);
  275. if (GetTypePrecedence(insts().Get(inner_type_inst_id).kind()) <
  276. GetTypePrecedence(inst.kind())) {
  277. out << "(";
  278. steps.push_back(step.Next());
  279. }
  280. steps.push_back({.inst_id = inner_type_inst_id});
  281. } else if (step.index == 1) {
  282. out << ")";
  283. }
  284. break;
  285. }
  286. case NameRef::Kind: {
  287. out << names().GetFormatted(inst.As<NameRef>().name_id);
  288. break;
  289. }
  290. case PointerType::Kind: {
  291. if (step.index == 0) {
  292. steps.push_back(step.Next());
  293. steps.push_back({.inst_id = types().GetInstId(
  294. inst.As<PointerType>().pointee_id)});
  295. } else if (step.index == 1) {
  296. out << "*";
  297. }
  298. break;
  299. }
  300. case StructType::Kind: {
  301. auto refs = inst_blocks().Get(inst.As<StructType>().fields_id);
  302. if (refs.empty()) {
  303. out << "{}";
  304. break;
  305. } else if (step.index == 0) {
  306. out << "{";
  307. } else if (step.index < static_cast<int>(refs.size())) {
  308. out << ", ";
  309. } else {
  310. out << "}";
  311. break;
  312. }
  313. steps.push_back(step.Next());
  314. steps.push_back({.inst_id = refs[step.index]});
  315. break;
  316. }
  317. case StructTypeField::Kind: {
  318. auto field = inst.As<StructTypeField>();
  319. out << "." << names().GetFormatted(field.name_id) << ": ";
  320. steps.push_back({.inst_id = types().GetInstId(field.field_type_id)});
  321. break;
  322. }
  323. case TupleType::Kind: {
  324. auto refs = type_blocks().Get(inst.As<TupleType>().elements_id);
  325. if (refs.empty()) {
  326. out << "()";
  327. break;
  328. } else if (step.index == 0) {
  329. out << "(";
  330. } else if (step.index < static_cast<int>(refs.size())) {
  331. out << ", ";
  332. } else {
  333. // A tuple of one element has a comma to disambiguate from an
  334. // expression.
  335. if (step.index == 1) {
  336. out << ",";
  337. }
  338. out << ")";
  339. break;
  340. }
  341. steps.push_back(step.Next());
  342. steps.push_back({.inst_id = types().GetInstId(refs[step.index])});
  343. break;
  344. }
  345. case UnboundElementType::Kind: {
  346. if (step.index == 0) {
  347. out << "<unbound element of class ";
  348. steps.push_back(step.Next());
  349. steps.push_back({.inst_id = types().GetInstId(
  350. inst.As<UnboundElementType>().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 BaseDecl::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 ClassDecl::Kind:
  372. case ClassElementAccess::Kind:
  373. case ClassInit::Kind:
  374. case Converted::Kind:
  375. case CrossRef::Kind:
  376. case Deref::Kind:
  377. case FieldDecl::Kind:
  378. case FunctionDecl::Kind:
  379. case Import::Kind:
  380. case InitializeFrom::Kind:
  381. case InterfaceDecl::Kind:
  382. case IntLiteral::Kind:
  383. case LazyImportRef::Kind:
  384. case Namespace::Kind:
  385. case NoOp::Kind:
  386. case Param::Kind:
  387. case RealLiteral::Kind:
  388. case Return::Kind:
  389. case ReturnExpr::Kind:
  390. case SelfParam::Kind:
  391. case SpliceBlock::Kind:
  392. case StringLiteral::Kind:
  393. case StructAccess::Kind:
  394. case StructLiteral::Kind:
  395. case StructInit::Kind:
  396. case StructValue::Kind:
  397. case Temporary::Kind:
  398. case TemporaryStorage::Kind:
  399. case TupleAccess::Kind:
  400. case TupleIndex::Kind:
  401. case TupleLiteral::Kind:
  402. case TupleInit::Kind:
  403. case TupleValue::Kind:
  404. case UnaryOperatorNot::Kind:
  405. case ValueAsRef::Kind:
  406. case ValueOfInitializer::Kind:
  407. case VarStorage::Kind:
  408. // We don't need to handle stringification for instructions that don't
  409. // show up in errors, but make it clear what's going on so that it's
  410. // clearer when stringification is needed.
  411. out << "<cannot stringify " << step.inst_id << ">";
  412. break;
  413. }
  414. }
  415. return str;
  416. }
  417. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
  418. const File* ir = &file;
  419. // The overall expression category if the current instruction is a value
  420. // expression.
  421. ExprCategory value_category = ExprCategory::Value;
  422. while (true) {
  423. auto inst = ir->insts().Get(inst_id);
  424. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  425. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  426. switch (inst.kind()) {
  427. case Assign::Kind:
  428. case BaseDecl::Kind:
  429. case Branch::Kind:
  430. case BranchIf::Kind:
  431. case BranchWithArg::Kind:
  432. case ClassDecl::Kind:
  433. case FieldDecl::Kind:
  434. case FunctionDecl::Kind:
  435. case Import::Kind:
  436. case InterfaceDecl::Kind:
  437. case LazyImportRef::Kind:
  438. case Namespace::Kind:
  439. case NoOp::Kind:
  440. case Return::Kind:
  441. case ReturnExpr::Kind:
  442. case StructTypeField::Kind:
  443. return ExprCategory::NotExpr;
  444. case CrossRef::Kind: {
  445. auto xref = inst.As<CrossRef>();
  446. ir = ir->cross_ref_irs().Get(xref.ir_id);
  447. inst_id = xref.inst_id;
  448. continue;
  449. }
  450. case NameRef::Kind: {
  451. inst_id = inst.As<NameRef>().value_id;
  452. continue;
  453. }
  454. case Converted::Kind: {
  455. inst_id = inst.As<Converted>().result_id;
  456. continue;
  457. }
  458. case AddressOf::Kind:
  459. case ArrayType::Kind:
  460. case BindValue::Kind:
  461. case BlockArg::Kind:
  462. case BoolLiteral::Kind:
  463. case BoundMethod::Kind:
  464. case ClassType::Kind:
  465. case ConstType::Kind:
  466. case IntLiteral::Kind:
  467. case Param::Kind:
  468. case PointerType::Kind:
  469. case RealLiteral::Kind:
  470. case SelfParam::Kind:
  471. case StringLiteral::Kind:
  472. case StructValue::Kind:
  473. case StructType::Kind:
  474. case TupleValue::Kind:
  475. case TupleType::Kind:
  476. case UnaryOperatorNot::Kind:
  477. case UnboundElementType::Kind:
  478. case ValueOfInitializer::Kind:
  479. return value_category;
  480. case Builtin::Kind: {
  481. if (inst.As<Builtin>().builtin_kind == BuiltinKind::Error) {
  482. return ExprCategory::Error;
  483. }
  484. return value_category;
  485. }
  486. case BindName::Kind: {
  487. inst_id = inst.As<BindName>().value_id;
  488. continue;
  489. }
  490. case ArrayIndex::Kind: {
  491. inst_id = inst.As<ArrayIndex>().array_id;
  492. continue;
  493. }
  494. case ClassElementAccess::Kind: {
  495. inst_id = inst.As<ClassElementAccess>().base_id;
  496. // A value of class type is a pointer to an object representation.
  497. // Therefore, if the base is a value, the result is an ephemeral
  498. // reference.
  499. value_category = ExprCategory::EphemeralRef;
  500. continue;
  501. }
  502. case StructAccess::Kind: {
  503. inst_id = inst.As<StructAccess>().struct_id;
  504. continue;
  505. }
  506. case TupleAccess::Kind: {
  507. inst_id = inst.As<TupleAccess>().tuple_id;
  508. continue;
  509. }
  510. case TupleIndex::Kind: {
  511. inst_id = inst.As<TupleIndex>().tuple_id;
  512. continue;
  513. }
  514. case SpliceBlock::Kind: {
  515. inst_id = inst.As<SpliceBlock>().result_id;
  516. continue;
  517. }
  518. case StructLiteral::Kind:
  519. case TupleLiteral::Kind:
  520. return ExprCategory::Mixed;
  521. case ArrayInit::Kind:
  522. case Call::Kind:
  523. case InitializeFrom::Kind:
  524. case ClassInit::Kind:
  525. case StructInit::Kind:
  526. case TupleInit::Kind:
  527. return ExprCategory::Initializing;
  528. case Deref::Kind:
  529. case VarStorage::Kind:
  530. return ExprCategory::DurableRef;
  531. case Temporary::Kind:
  532. case TemporaryStorage::Kind:
  533. case ValueAsRef::Kind:
  534. return ExprCategory::EphemeralRef;
  535. }
  536. }
  537. }
  538. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr {
  539. auto value_rep = GetValueRepr(file, type_id);
  540. switch (value_rep.kind) {
  541. case ValueRepr::None:
  542. return {.kind = InitRepr::None};
  543. case ValueRepr::Copy:
  544. // TODO: Use in-place initialization for types that have non-trivial
  545. // destructive move.
  546. return {.kind = InitRepr::ByCopy};
  547. case ValueRepr::Pointer:
  548. case ValueRepr::Custom:
  549. return {.kind = InitRepr::InPlace};
  550. case ValueRepr::Unknown:
  551. CARBON_FATAL()
  552. << "Attempting to perform initialization of incomplete type";
  553. }
  554. }
  555. } // namespace Carbon::SemIR