file.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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::AnyBindName>()) {
  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("bind_names", bind_names_.OutputYaml());
  135. map.Add("functions", functions_.OutputYaml());
  136. map.Add("classes", classes_.OutputYaml());
  137. map.Add("types", types_.OutputYaml());
  138. map.Add("type_blocks", type_blocks_.OutputYaml());
  139. map.Add("insts",
  140. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  141. int start =
  142. include_builtins ? 0 : BuiltinKind::ValidCount;
  143. for (int i : llvm::seq(start, insts_.size())) {
  144. auto id = InstId(i);
  145. map.Add(PrintToString(id),
  146. Yaml::OutputScalar(insts_.Get(id)));
  147. }
  148. }));
  149. map.Add("inst_blocks", inst_blocks_.OutputYaml());
  150. }));
  151. });
  152. }
  153. // Map an instruction kind representing a type into an integer describing the
  154. // precedence of that type's syntax. Higher numbers correspond to higher
  155. // precedence.
  156. static auto GetTypePrecedence(InstKind kind) -> int {
  157. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  158. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  159. switch (kind) {
  160. case ArrayType::Kind:
  161. case BindSymbolicName::Kind:
  162. case Builtin::Kind:
  163. case ClassType::Kind:
  164. case NameRef::Kind:
  165. case StructType::Kind:
  166. case TupleType::Kind:
  167. case UnboundElementType::Kind:
  168. return 0;
  169. case ConstType::Kind:
  170. return -1;
  171. case PointerType::Kind:
  172. return -2;
  173. case CrossRef::Kind:
  174. // TODO: Once we support stringification of cross-references, we'll need
  175. // to determine the precedence of the target of the cross-reference. For
  176. // now, all cross-references refer to builtin types from the prelude.
  177. return 0;
  178. case AddressOf::Kind:
  179. case AddrPattern::Kind:
  180. case ArrayIndex::Kind:
  181. case ArrayInit::Kind:
  182. case Assign::Kind:
  183. case BaseDecl::Kind:
  184. case BindName::Kind:
  185. case BindValue::Kind:
  186. case BlockArg::Kind:
  187. case BoolLiteral::Kind:
  188. case BoundMethod::Kind:
  189. case Branch::Kind:
  190. case BranchIf::Kind:
  191. case BranchWithArg::Kind:
  192. case Call::Kind:
  193. case ClassDecl::Kind:
  194. case ClassElementAccess::Kind:
  195. case ClassInit::Kind:
  196. case Converted::Kind:
  197. case Deref::Kind:
  198. case FieldDecl::Kind:
  199. case FunctionDecl::Kind:
  200. case Import::Kind:
  201. case InitializeFrom::Kind:
  202. case InterfaceDecl::Kind:
  203. case IntLiteral::Kind:
  204. case LazyImportRef::Kind:
  205. case Namespace::Kind:
  206. case NoOp::Kind:
  207. case Param::Kind:
  208. case RealLiteral::Kind:
  209. case Return::Kind:
  210. case ReturnExpr::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 ValueAsRef::Kind:
  227. case ValueOfInitializer::Kind:
  228. case VarStorage::Kind:
  229. CARBON_FATAL() << "GetTypePrecedence for non-type inst kind " << kind;
  230. }
  231. }
  232. auto File::StringifyType(TypeId type_id) const -> std::string {
  233. return StringifyTypeExpr(types().GetInstId(type_id));
  234. }
  235. auto File::StringifyTypeExpr(InstId outer_inst_id) const -> std::string {
  236. std::string str;
  237. llvm::raw_string_ostream out(str);
  238. struct Step {
  239. // The instruction to print.
  240. InstId inst_id;
  241. // The index into inst_id to print. Not used by all types.
  242. int index = 0;
  243. auto Next() const -> Step {
  244. return {.inst_id = inst_id, .index = index + 1};
  245. }
  246. };
  247. llvm::SmallVector<Step> steps = {{.inst_id = outer_inst_id}};
  248. while (!steps.empty()) {
  249. auto step = steps.pop_back_val();
  250. if (!step.inst_id.is_valid()) {
  251. out << "<invalid type>";
  252. continue;
  253. }
  254. // Builtins have designated labels.
  255. if (step.inst_id.index < BuiltinKind::ValidCount) {
  256. out << BuiltinKind::FromInt(step.inst_id.index).label();
  257. continue;
  258. }
  259. auto inst = insts().Get(step.inst_id);
  260. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  261. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  262. switch (inst.kind()) {
  263. case ArrayType::Kind: {
  264. auto array = inst.As<ArrayType>();
  265. if (step.index == 0) {
  266. out << "[";
  267. steps.push_back(step.Next());
  268. steps.push_back(
  269. {.inst_id = types().GetInstId(array.element_type_id)});
  270. } else if (step.index == 1) {
  271. out << "; " << GetArrayBoundValue(array.bound_id) << "]";
  272. }
  273. break;
  274. }
  275. case BindSymbolicName::Kind: {
  276. auto name_id = inst.As<BindSymbolicName>().bind_name_id;
  277. out << names().GetFormatted(bind_names().Get(name_id).name_id);
  278. break;
  279. }
  280. case ClassType::Kind: {
  281. auto class_name_id =
  282. classes().Get(inst.As<ClassType>().class_id).name_id;
  283. out << names().GetFormatted(class_name_id);
  284. break;
  285. }
  286. case ConstType::Kind: {
  287. if (step.index == 0) {
  288. out << "const ";
  289. // Add parentheses if required.
  290. auto inner_type_inst_id =
  291. types().GetInstId(inst.As<ConstType>().inner_id);
  292. if (GetTypePrecedence(insts().Get(inner_type_inst_id).kind()) <
  293. GetTypePrecedence(inst.kind())) {
  294. out << "(";
  295. steps.push_back(step.Next());
  296. }
  297. steps.push_back({.inst_id = inner_type_inst_id});
  298. } else if (step.index == 1) {
  299. out << ")";
  300. }
  301. break;
  302. }
  303. case NameRef::Kind: {
  304. out << names().GetFormatted(inst.As<NameRef>().name_id);
  305. break;
  306. }
  307. case PointerType::Kind: {
  308. if (step.index == 0) {
  309. steps.push_back(step.Next());
  310. steps.push_back({.inst_id = types().GetInstId(
  311. inst.As<PointerType>().pointee_id)});
  312. } else if (step.index == 1) {
  313. out << "*";
  314. }
  315. break;
  316. }
  317. case StructType::Kind: {
  318. auto refs = inst_blocks().Get(inst.As<StructType>().fields_id);
  319. if (refs.empty()) {
  320. out << "{}";
  321. break;
  322. } else if (step.index == 0) {
  323. out << "{";
  324. } else if (step.index < static_cast<int>(refs.size())) {
  325. out << ", ";
  326. } else {
  327. out << "}";
  328. break;
  329. }
  330. steps.push_back(step.Next());
  331. steps.push_back({.inst_id = refs[step.index]});
  332. break;
  333. }
  334. case StructTypeField::Kind: {
  335. auto field = inst.As<StructTypeField>();
  336. out << "." << names().GetFormatted(field.name_id) << ": ";
  337. steps.push_back({.inst_id = types().GetInstId(field.field_type_id)});
  338. break;
  339. }
  340. case TupleType::Kind: {
  341. auto refs = type_blocks().Get(inst.As<TupleType>().elements_id);
  342. if (refs.empty()) {
  343. out << "()";
  344. break;
  345. } else if (step.index == 0) {
  346. out << "(";
  347. } else if (step.index < static_cast<int>(refs.size())) {
  348. out << ", ";
  349. } else {
  350. // A tuple of one element has a comma to disambiguate from an
  351. // expression.
  352. if (step.index == 1) {
  353. out << ",";
  354. }
  355. out << ")";
  356. break;
  357. }
  358. steps.push_back(step.Next());
  359. steps.push_back({.inst_id = types().GetInstId(refs[step.index])});
  360. break;
  361. }
  362. case UnboundElementType::Kind: {
  363. if (step.index == 0) {
  364. out << "<unbound element of class ";
  365. steps.push_back(step.Next());
  366. steps.push_back({.inst_id = types().GetInstId(
  367. inst.As<UnboundElementType>().class_type_id)});
  368. } else {
  369. out << ">";
  370. }
  371. break;
  372. }
  373. case AddressOf::Kind:
  374. case AddrPattern::Kind:
  375. case ArrayIndex::Kind:
  376. case ArrayInit::Kind:
  377. case Assign::Kind:
  378. case BaseDecl::Kind:
  379. case BindName::Kind:
  380. case BindValue::Kind:
  381. case BlockArg::Kind:
  382. case BoolLiteral::Kind:
  383. case BoundMethod::Kind:
  384. case Branch::Kind:
  385. case BranchIf::Kind:
  386. case BranchWithArg::Kind:
  387. case Builtin::Kind:
  388. case Call::Kind:
  389. case ClassDecl::Kind:
  390. case ClassElementAccess::Kind:
  391. case ClassInit::Kind:
  392. case Converted::Kind:
  393. case CrossRef::Kind:
  394. case Deref::Kind:
  395. case FieldDecl::Kind:
  396. case FunctionDecl::Kind:
  397. case Import::Kind:
  398. case InitializeFrom::Kind:
  399. case InterfaceDecl::Kind:
  400. case IntLiteral::Kind:
  401. case LazyImportRef::Kind:
  402. case Namespace::Kind:
  403. case NoOp::Kind:
  404. case Param::Kind:
  405. case RealLiteral::Kind:
  406. case Return::Kind:
  407. case ReturnExpr::Kind:
  408. case SpliceBlock::Kind:
  409. case StringLiteral::Kind:
  410. case StructAccess::Kind:
  411. case StructLiteral::Kind:
  412. case StructInit::Kind:
  413. case StructValue::Kind:
  414. case Temporary::Kind:
  415. case TemporaryStorage::Kind:
  416. case TupleAccess::Kind:
  417. case TupleIndex::Kind:
  418. case TupleLiteral::Kind:
  419. case TupleInit::Kind:
  420. case TupleValue::Kind:
  421. case UnaryOperatorNot::Kind:
  422. case ValueAsRef::Kind:
  423. case ValueOfInitializer::Kind:
  424. case VarStorage::Kind:
  425. // We don't need to handle stringification for instructions that don't
  426. // show up in errors, but make it clear what's going on so that it's
  427. // clearer when stringification is needed.
  428. out << "<cannot stringify " << step.inst_id << ">";
  429. break;
  430. }
  431. }
  432. return str;
  433. }
  434. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
  435. const File* ir = &file;
  436. // The overall expression category if the current instruction is a value
  437. // expression.
  438. ExprCategory value_category = ExprCategory::Value;
  439. while (true) {
  440. auto inst = ir->insts().Get(inst_id);
  441. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  442. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  443. switch (inst.kind()) {
  444. case Assign::Kind:
  445. case BaseDecl::Kind:
  446. case Branch::Kind:
  447. case BranchIf::Kind:
  448. case BranchWithArg::Kind:
  449. case ClassDecl::Kind:
  450. case FieldDecl::Kind:
  451. case FunctionDecl::Kind:
  452. case Import::Kind:
  453. case InterfaceDecl::Kind:
  454. case LazyImportRef::Kind:
  455. case Namespace::Kind:
  456. case NoOp::Kind:
  457. case Return::Kind:
  458. case ReturnExpr::Kind:
  459. case StructTypeField::Kind:
  460. return ExprCategory::NotExpr;
  461. case CrossRef::Kind: {
  462. auto xref = inst.As<CrossRef>();
  463. ir = ir->cross_ref_irs().Get(xref.ir_id);
  464. inst_id = xref.inst_id;
  465. continue;
  466. }
  467. case NameRef::Kind: {
  468. inst_id = inst.As<NameRef>().value_id;
  469. continue;
  470. }
  471. case Converted::Kind: {
  472. inst_id = inst.As<Converted>().result_id;
  473. continue;
  474. }
  475. case AddressOf::Kind:
  476. case AddrPattern::Kind:
  477. case ArrayType::Kind:
  478. case BindSymbolicName::Kind:
  479. case BindValue::Kind:
  480. case BlockArg::Kind:
  481. case BoolLiteral::Kind:
  482. case BoundMethod::Kind:
  483. case ClassType::Kind:
  484. case ConstType::Kind:
  485. case IntLiteral::Kind:
  486. case Param::Kind:
  487. case PointerType::Kind:
  488. case RealLiteral::Kind:
  489. case StringLiteral::Kind:
  490. case StructValue::Kind:
  491. case StructType::Kind:
  492. case TupleValue::Kind:
  493. case TupleType::Kind:
  494. case UnaryOperatorNot::Kind:
  495. case UnboundElementType::Kind:
  496. case ValueOfInitializer::Kind:
  497. return value_category;
  498. case Builtin::Kind: {
  499. if (inst.As<Builtin>().builtin_kind == BuiltinKind::Error) {
  500. return ExprCategory::Error;
  501. }
  502. return value_category;
  503. }
  504. case BindName::Kind: {
  505. inst_id = inst.As<BindName>().value_id;
  506. continue;
  507. }
  508. case ArrayIndex::Kind: {
  509. inst_id = inst.As<ArrayIndex>().array_id;
  510. continue;
  511. }
  512. case ClassElementAccess::Kind: {
  513. inst_id = inst.As<ClassElementAccess>().base_id;
  514. // A value of class type is a pointer to an object representation.
  515. // Therefore, if the base is a value, the result is an ephemeral
  516. // reference.
  517. value_category = ExprCategory::EphemeralRef;
  518. continue;
  519. }
  520. case StructAccess::Kind: {
  521. inst_id = inst.As<StructAccess>().struct_id;
  522. continue;
  523. }
  524. case TupleAccess::Kind: {
  525. inst_id = inst.As<TupleAccess>().tuple_id;
  526. continue;
  527. }
  528. case TupleIndex::Kind: {
  529. inst_id = inst.As<TupleIndex>().tuple_id;
  530. continue;
  531. }
  532. case SpliceBlock::Kind: {
  533. inst_id = inst.As<SpliceBlock>().result_id;
  534. continue;
  535. }
  536. case StructLiteral::Kind:
  537. case TupleLiteral::Kind:
  538. return ExprCategory::Mixed;
  539. case ArrayInit::Kind:
  540. case Call::Kind:
  541. case InitializeFrom::Kind:
  542. case ClassInit::Kind:
  543. case StructInit::Kind:
  544. case TupleInit::Kind:
  545. return ExprCategory::Initializing;
  546. case Deref::Kind:
  547. case VarStorage::Kind:
  548. return ExprCategory::DurableRef;
  549. case Temporary::Kind:
  550. case TemporaryStorage::Kind:
  551. case ValueAsRef::Kind:
  552. return ExprCategory::EphemeralRef;
  553. }
  554. }
  555. }
  556. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr {
  557. auto value_rep = GetValueRepr(file, type_id);
  558. switch (value_rep.kind) {
  559. case ValueRepr::None:
  560. return {.kind = InitRepr::None};
  561. case ValueRepr::Copy:
  562. // TODO: Use in-place initialization for types that have non-trivial
  563. // destructive move.
  564. return {.kind = InitRepr::ByCopy};
  565. case ValueRepr::Pointer:
  566. case ValueRepr::Custom:
  567. return {.kind = InitRepr::InPlace};
  568. case ValueRepr::Unknown:
  569. CARBON_FATAL()
  570. << "Attempting to perform initialization of incomplete type";
  571. }
  572. }
  573. } // namespace Carbon::SemIR