file.cpp 19 KB

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