file.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 BinaryOperatorAdd::Kind:
  172. case BindName::Kind:
  173. case BindValue::Kind:
  174. case BlockArg::Kind:
  175. case BoolLiteral::Kind:
  176. case BoundMethod::Kind:
  177. case Branch::Kind:
  178. case BranchIf::Kind:
  179. case BranchWithArg::Kind:
  180. case Call::Kind:
  181. case ClassDecl::Kind:
  182. case ClassElementAccess::Kind:
  183. case ClassInit::Kind:
  184. case Converted::Kind:
  185. case Deref::Kind:
  186. case FieldDecl::Kind:
  187. case FunctionDecl::Kind:
  188. case Import::Kind:
  189. case InitializeFrom::Kind:
  190. case IntLiteral::Kind:
  191. case Namespace::Kind:
  192. case NoOp::Kind:
  193. case Param::Kind:
  194. case RealLiteral::Kind:
  195. case Return::Kind:
  196. case ReturnExpr::Kind:
  197. case SelfParam::Kind:
  198. case SpliceBlock::Kind:
  199. case StringLiteral::Kind:
  200. case StructAccess::Kind:
  201. case StructTypeField::Kind:
  202. case StructLiteral::Kind:
  203. case StructInit::Kind:
  204. case StructValue::Kind:
  205. case Temporary::Kind:
  206. case TemporaryStorage::Kind:
  207. case TupleAccess::Kind:
  208. case TupleIndex::Kind:
  209. case TupleLiteral::Kind:
  210. case TupleInit::Kind:
  211. case TupleValue::Kind:
  212. case UnaryOperatorNot::Kind:
  213. case ValueAsRef::Kind:
  214. case ValueOfInitializer::Kind:
  215. case VarStorage::Kind:
  216. CARBON_FATAL() << "GetTypePrecedence for non-type inst kind " << kind;
  217. }
  218. }
  219. auto File::StringifyType(TypeId type_id) const -> std::string {
  220. return StringifyTypeExpr(GetTypeAllowBuiltinTypes(type_id));
  221. }
  222. auto File::StringifyTypeExpr(InstId outer_inst_id) const -> std::string {
  223. std::string str;
  224. llvm::raw_string_ostream out(str);
  225. struct Step {
  226. // The instruction to print.
  227. InstId inst_id;
  228. // The index into inst_id to print. Not used by all types.
  229. int index = 0;
  230. auto Next() const -> Step {
  231. return {.inst_id = inst_id, .index = index + 1};
  232. }
  233. };
  234. llvm::SmallVector<Step> steps = {{.inst_id = outer_inst_id}};
  235. while (!steps.empty()) {
  236. auto step = steps.pop_back_val();
  237. if (!step.inst_id.is_valid()) {
  238. out << "<invalid type>";
  239. continue;
  240. }
  241. // Builtins have designated labels.
  242. if (step.inst_id.index < BuiltinKind::ValidCount) {
  243. out << BuiltinKind::FromInt(step.inst_id.index).label();
  244. continue;
  245. }
  246. auto inst = insts().Get(step.inst_id);
  247. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  248. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  249. switch (inst.kind()) {
  250. case ArrayType::Kind: {
  251. auto array = inst.As<ArrayType>();
  252. if (step.index == 0) {
  253. out << "[";
  254. steps.push_back(step.Next());
  255. steps.push_back(
  256. {.inst_id = GetTypeAllowBuiltinTypes(array.element_type_id)});
  257. } else if (step.index == 1) {
  258. out << "; " << GetArrayBoundValue(array.bound_id) << "]";
  259. }
  260. break;
  261. }
  262. case ClassType::Kind: {
  263. auto class_name_id =
  264. classes().Get(inst.As<ClassType>().class_id).name_id;
  265. out << names().GetFormatted(class_name_id);
  266. break;
  267. }
  268. case ConstType::Kind: {
  269. if (step.index == 0) {
  270. out << "const ";
  271. // Add parentheses if required.
  272. auto inner_type_inst_id =
  273. GetTypeAllowBuiltinTypes(inst.As<ConstType>().inner_id);
  274. if (GetTypePrecedence(insts().Get(inner_type_inst_id).kind()) <
  275. GetTypePrecedence(inst.kind())) {
  276. out << "(";
  277. steps.push_back(step.Next());
  278. }
  279. steps.push_back({.inst_id = inner_type_inst_id});
  280. } else if (step.index == 1) {
  281. out << ")";
  282. }
  283. break;
  284. }
  285. case NameRef::Kind: {
  286. out << names().GetFormatted(inst.As<NameRef>().name_id);
  287. break;
  288. }
  289. case PointerType::Kind: {
  290. if (step.index == 0) {
  291. steps.push_back(step.Next());
  292. steps.push_back({.inst_id = GetTypeAllowBuiltinTypes(
  293. inst.As<PointerType>().pointee_id)});
  294. } else if (step.index == 1) {
  295. out << "*";
  296. }
  297. break;
  298. }
  299. case StructType::Kind: {
  300. auto refs = inst_blocks().Get(inst.As<StructType>().fields_id);
  301. if (refs.empty()) {
  302. out << "{}";
  303. break;
  304. } else if (step.index == 0) {
  305. out << "{";
  306. } else if (step.index < static_cast<int>(refs.size())) {
  307. out << ", ";
  308. } else {
  309. out << "}";
  310. break;
  311. }
  312. steps.push_back(step.Next());
  313. steps.push_back({.inst_id = refs[step.index]});
  314. break;
  315. }
  316. case StructTypeField::Kind: {
  317. auto field = inst.As<StructTypeField>();
  318. out << "." << names().GetFormatted(field.name_id) << ": ";
  319. steps.push_back(
  320. {.inst_id = GetTypeAllowBuiltinTypes(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(
  343. {.inst_id = GetTypeAllowBuiltinTypes(refs[step.index])});
  344. break;
  345. }
  346. case UnboundElementType::Kind: {
  347. if (step.index == 0) {
  348. out << "<unbound element of class ";
  349. steps.push_back(step.Next());
  350. steps.push_back({.inst_id = GetTypeAllowBuiltinTypes(
  351. inst.As<UnboundElementType>().class_type_id)});
  352. } else {
  353. out << ">";
  354. }
  355. break;
  356. }
  357. case AddressOf::Kind:
  358. case ArrayIndex::Kind:
  359. case ArrayInit::Kind:
  360. case Assign::Kind:
  361. case BaseDecl::Kind:
  362. case BinaryOperatorAdd::Kind:
  363. case BindName::Kind:
  364. case BindValue::Kind:
  365. case BlockArg::Kind:
  366. case BoolLiteral::Kind:
  367. case BoundMethod::Kind:
  368. case Branch::Kind:
  369. case BranchIf::Kind:
  370. case BranchWithArg::Kind:
  371. case Builtin::Kind:
  372. case Call::Kind:
  373. case ClassDecl::Kind:
  374. case ClassElementAccess::Kind:
  375. case ClassInit::Kind:
  376. case Converted::Kind:
  377. case CrossRef::Kind:
  378. case Deref::Kind:
  379. case FieldDecl::Kind:
  380. case FunctionDecl::Kind:
  381. case Import::Kind:
  382. case InitializeFrom::Kind:
  383. case IntLiteral::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 Namespace::Kind:
  437. case NoOp::Kind:
  438. case Return::Kind:
  439. case ReturnExpr::Kind:
  440. case StructTypeField::Kind:
  441. return ExprCategory::NotExpr;
  442. case CrossRef::Kind: {
  443. auto xref = inst.As<CrossRef>();
  444. ir = ir->cross_ref_irs().Get(xref.ir_id);
  445. inst_id = xref.inst_id;
  446. continue;
  447. }
  448. case NameRef::Kind: {
  449. inst_id = inst.As<NameRef>().value_id;
  450. continue;
  451. }
  452. case Converted::Kind: {
  453. inst_id = inst.As<Converted>().result_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 IntLiteral::Kind:
  466. case Param::Kind:
  467. case PointerType::Kind:
  468. case RealLiteral::Kind:
  469. case SelfParam::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 UnboundElementType::Kind:
  477. case ValueOfInitializer::Kind:
  478. return value_category;
  479. case Builtin::Kind: {
  480. if (inst.As<Builtin>().builtin_kind == BuiltinKind::Error) {
  481. return ExprCategory::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 ClassElementAccess::Kind: {
  494. inst_id = inst.As<ClassElementAccess>().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 = ExprCategory::EphemeralRef;
  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 ExprCategory::Mixed;
  520. case ArrayInit::Kind:
  521. case Call::Kind:
  522. case InitializeFrom::Kind:
  523. case ClassInit::Kind:
  524. case StructInit::Kind:
  525. case TupleInit::Kind:
  526. return ExprCategory::Initializing;
  527. case Deref::Kind:
  528. case VarStorage::Kind:
  529. return ExprCategory::DurableRef;
  530. case Temporary::Kind:
  531. case TemporaryStorage::Kind:
  532. case ValueAsRef::Kind:
  533. return ExprCategory::EphemeralRef;
  534. }
  535. }
  536. }
  537. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr {
  538. auto value_rep = GetValueRepr(file, type_id);
  539. switch (value_rep.kind) {
  540. case ValueRepr::None:
  541. return {.kind = InitRepr::None};
  542. case ValueRepr::Copy:
  543. // TODO: Use in-place initialization for types that have non-trivial
  544. // destructive move.
  545. return {.kind = InitRepr::ByCopy};
  546. case ValueRepr::Pointer:
  547. case ValueRepr::Custom:
  548. return {.kind = InitRepr::InPlace};
  549. case ValueRepr::Unknown:
  550. CARBON_FATAL()
  551. << "Attempting to perform initialization of incomplete type";
  552. }
  553. }
  554. } // namespace Carbon::SemIR