file.cpp 19 KB

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