file.cpp 19 KB

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