file.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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/kind_switch.h"
  9. #include "toolchain/base/value_store.h"
  10. #include "toolchain/base/yaml.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/sem_ir/builtin_kind.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/inst_kind.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::SemIR {
  18. auto Function::GetParamFromParamRefId(const File& sem_ir, InstId param_ref_id)
  19. -> std::pair<InstId, Param> {
  20. auto ref = sem_ir.insts().Get(param_ref_id);
  21. if (auto addr_pattern = ref.TryAs<SemIR::AddrPattern>()) {
  22. param_ref_id = addr_pattern->inner_id;
  23. ref = sem_ir.insts().Get(param_ref_id);
  24. }
  25. if (auto bind_name = ref.TryAs<SemIR::AnyBindName>()) {
  26. param_ref_id = bind_name->value_id;
  27. ref = sem_ir.insts().Get(param_ref_id);
  28. }
  29. return {param_ref_id, ref.As<SemIR::Param>()};
  30. }
  31. auto ValueRepr::Print(llvm::raw_ostream& out) const -> void {
  32. out << "{kind: ";
  33. switch (kind) {
  34. case Unknown:
  35. out << "unknown";
  36. break;
  37. case None:
  38. out << "none";
  39. break;
  40. case Copy:
  41. out << "copy";
  42. break;
  43. case Pointer:
  44. out << "pointer";
  45. break;
  46. case Custom:
  47. out << "custom";
  48. break;
  49. }
  50. out << ", type: " << type_id << "}";
  51. }
  52. auto TypeInfo::Print(llvm::raw_ostream& out) const -> void {
  53. out << "{constant: " << constant_id << ", value_rep: " << value_repr << "}";
  54. }
  55. File::File(SharedValueStores& value_stores, std::string filename,
  56. const File* builtins, llvm::function_ref<void()> init_builtins)
  57. : value_stores_(&value_stores),
  58. filename_(std::move(filename)),
  59. type_blocks_(allocator_),
  60. constant_values_(ConstantId::NotConstant),
  61. inst_blocks_(allocator_),
  62. constants_(*this, allocator_) {
  63. CARBON_CHECK(builtins != nullptr);
  64. auto builtins_id =
  65. import_irs_.Add({.node_id = Parse::NodeId::Invalid, .sem_ir = builtins});
  66. CARBON_CHECK(builtins_id == ImportIRId::Builtins)
  67. << "Builtins must be the first IR";
  68. auto api_placeholder_id =
  69. import_irs_.Add({.node_id = Parse::NodeId::Invalid, .sem_ir = nullptr});
  70. CARBON_CHECK(api_placeholder_id == ImportIRId::ApiForImpl)
  71. << "ApiForImpl must be the second IR";
  72. insts_.Reserve(BuiltinKind::ValidCount);
  73. init_builtins();
  74. CARBON_CHECK(insts_.size() == BuiltinKind::ValidCount)
  75. << "Builtins should produce " << BuiltinKind::ValidCount
  76. << " insts, actual: " << insts_.size();
  77. for (auto i : llvm::seq(BuiltinKind::ValidCount)) {
  78. auto builtin_id = SemIR::InstId(i);
  79. constant_values_.Set(builtin_id,
  80. SemIR::ConstantId::ForTemplateConstant(builtin_id));
  81. }
  82. }
  83. File::File(SharedValueStores& value_stores)
  84. : File(value_stores, "<builtins>", this, [&]() {
  85. // Error uses a self-referential type so that it's not accidentally treated as
  86. // a normal type. Every other builtin is a type, including the
  87. // self-referential TypeType.
  88. #define CARBON_SEM_IR_BUILTIN_KIND(Name, ...) \
  89. insts_.AddInNoBlock( \
  90. {Builtin{BuiltinKind::Name == BuiltinKind::Error ? TypeId::Error \
  91. : TypeId::TypeType, \
  92. BuiltinKind::Name}});
  93. #include "toolchain/sem_ir/builtin_kind.def"
  94. }) {
  95. }
  96. File::File(SharedValueStores& value_stores, std::string filename,
  97. const File* builtins)
  98. : File(value_stores, filename, builtins, [&]() {
  99. for (auto [i, inst] : llvm::enumerate(builtins->insts_.array_ref())) {
  100. // We can reuse the type_id from the builtin IR's inst because they're
  101. // special-cased values.
  102. auto import_ir_inst_id = import_ir_insts_.Add(
  103. {.ir_id = ImportIRId::Builtins, .inst_id = SemIR::InstId(i)});
  104. insts_.AddInNoBlock(
  105. ImportRefLoaded{inst.type_id(), import_ir_inst_id});
  106. }
  107. }) {}
  108. auto File::Verify() const -> ErrorOr<Success> {
  109. // Invariants don't necessarily hold for invalid IR.
  110. if (has_errors_) {
  111. return Success();
  112. }
  113. // Check that every code block has a terminator sequence that appears at the
  114. // end of the block.
  115. for (const Function& function : functions_.array_ref()) {
  116. for (InstBlockId block_id : function.body_block_ids) {
  117. TerminatorKind prior_kind = TerminatorKind::NotTerminator;
  118. for (InstId inst_id : inst_blocks().Get(block_id)) {
  119. TerminatorKind inst_kind =
  120. insts().Get(inst_id).kind().terminator_kind();
  121. if (prior_kind == TerminatorKind::Terminator) {
  122. return Error(llvm::formatv("Inst {0} in block {1} follows terminator",
  123. inst_id, block_id));
  124. }
  125. if (prior_kind > inst_kind) {
  126. return Error(
  127. llvm::formatv("Non-terminator inst {0} in block {1} follows "
  128. "terminator sequence",
  129. inst_id, block_id));
  130. }
  131. prior_kind = inst_kind;
  132. }
  133. if (prior_kind != TerminatorKind::Terminator) {
  134. return Error(llvm::formatv("No terminator in block {0}", block_id));
  135. }
  136. }
  137. }
  138. // TODO: Check that an instruction only references other instructions that are
  139. // either global or that dominate it.
  140. return Success();
  141. }
  142. auto File::OutputYaml(bool include_builtins) const -> Yaml::OutputMapping {
  143. return Yaml::OutputMapping([this,
  144. include_builtins](Yaml::OutputMapping::Map map) {
  145. map.Add("filename", filename_);
  146. map.Add(
  147. "sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  148. map.Add("import_irs_size", Yaml::OutputScalar(import_irs_.size()));
  149. map.Add("name_scopes", name_scopes_.OutputYaml());
  150. map.Add("bind_names", bind_names_.OutputYaml());
  151. map.Add("functions", functions_.OutputYaml());
  152. map.Add("classes", classes_.OutputYaml());
  153. map.Add("types", types_.OutputYaml());
  154. map.Add("type_blocks", type_blocks_.OutputYaml());
  155. map.Add("insts",
  156. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  157. int start = include_builtins ? 0 : BuiltinKind::ValidCount;
  158. for (int i : llvm::seq(start, insts_.size())) {
  159. auto id = InstId(i);
  160. map.Add(PrintToString(id),
  161. Yaml::OutputScalar(insts_.Get(id)));
  162. }
  163. }));
  164. map.Add("constant_values",
  165. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  166. int start = include_builtins ? 0 : BuiltinKind::ValidCount;
  167. for (int i : llvm::seq(start, insts_.size())) {
  168. auto id = InstId(i);
  169. auto value = constant_values_.Get(id);
  170. if (!value.is_valid() || value.is_constant()) {
  171. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  172. }
  173. }
  174. }));
  175. map.Add("inst_blocks", inst_blocks_.OutputYaml());
  176. }));
  177. });
  178. }
  179. // Map an instruction kind representing a type into an integer describing the
  180. // precedence of that type's syntax. Higher numbers correspond to higher
  181. // precedence.
  182. static auto GetTypePrecedence(InstKind kind) -> int {
  183. switch (kind) {
  184. case ArrayType::Kind:
  185. case AssociatedEntityType::Kind:
  186. case BindAlias::Kind:
  187. case BindSymbolicName::Kind:
  188. case Builtin::Kind:
  189. case ClassType::Kind:
  190. case ExternType::Kind:
  191. case FacetTypeAccess::Kind:
  192. case FloatType::Kind:
  193. case ImportRefLoaded::Kind:
  194. case ImportRefUsed::Kind:
  195. case InterfaceType::Kind:
  196. case IntType::Kind:
  197. case NameRef::Kind:
  198. case StructType::Kind:
  199. case TupleType::Kind:
  200. case UnboundElementType::Kind:
  201. return 0;
  202. case ConstType::Kind:
  203. return -1;
  204. case PointerType::Kind:
  205. return -2;
  206. case AdaptDecl::Kind:
  207. case AddrOf::Kind:
  208. case AddrPattern::Kind:
  209. case ArrayIndex::Kind:
  210. case ArrayInit::Kind:
  211. case AsCompatible::Kind:
  212. case Assign::Kind:
  213. case AssociatedConstantDecl::Kind:
  214. case AssociatedEntity::Kind:
  215. case BaseDecl::Kind:
  216. case BindName::Kind:
  217. case BindValue::Kind:
  218. case BlockArg::Kind:
  219. case BoolLiteral::Kind:
  220. case BoundMethod::Kind:
  221. case Branch::Kind:
  222. case BranchIf::Kind:
  223. case BranchWithArg::Kind:
  224. case Call::Kind:
  225. case ClassDecl::Kind:
  226. case ClassElementAccess::Kind:
  227. case ClassInit::Kind:
  228. case Converted::Kind:
  229. case Deref::Kind:
  230. case ExternDecl::Kind:
  231. case FieldDecl::Kind:
  232. case FloatLiteral::Kind:
  233. case FunctionDecl::Kind:
  234. case ImplDecl::Kind:
  235. case ImportRefUnloaded::Kind:
  236. case InitializeFrom::Kind:
  237. case InterfaceDecl::Kind:
  238. case InterfaceWitness::Kind:
  239. case InterfaceWitnessAccess::Kind:
  240. case IntLiteral::Kind:
  241. case Namespace::Kind:
  242. case Param::Kind:
  243. case RealLiteral::Kind:
  244. case Return::Kind:
  245. case ReturnExpr::Kind:
  246. case SpliceBlock::Kind:
  247. case StringLiteral::Kind:
  248. case StructAccess::Kind:
  249. case StructTypeField::Kind:
  250. case StructLiteral::Kind:
  251. case StructInit::Kind:
  252. case StructValue::Kind:
  253. case Temporary::Kind:
  254. case TemporaryStorage::Kind:
  255. case TupleAccess::Kind:
  256. case TupleIndex::Kind:
  257. case TupleLiteral::Kind:
  258. case TupleInit::Kind:
  259. case TupleValue::Kind:
  260. case UnaryOperatorNot::Kind:
  261. case ValueAsRef::Kind:
  262. case ValueOfInitializer::Kind:
  263. case VarStorage::Kind:
  264. CARBON_FATAL() << "GetTypePrecedence for non-type inst kind " << kind;
  265. }
  266. }
  267. // Implements File::StringifyTypeExpr. Static to prevent accidental use of
  268. // member functions while traversing IRs.
  269. static auto StringifyTypeExprImpl(const SemIR::File& outer_sem_ir,
  270. InstId outer_inst_id) {
  271. std::string str;
  272. llvm::raw_string_ostream out(str);
  273. struct Step {
  274. // The instruction's file.
  275. const File& sem_ir;
  276. // The instruction to print.
  277. InstId inst_id;
  278. // The index into inst_id to print. Not used by all types.
  279. int index = 0;
  280. auto Next() const -> Step {
  281. return {.sem_ir = sem_ir, .inst_id = inst_id, .index = index + 1};
  282. }
  283. };
  284. llvm::SmallVector<Step> steps = {
  285. Step{.sem_ir = outer_sem_ir, .inst_id = outer_inst_id}};
  286. while (!steps.empty()) {
  287. auto step = steps.pop_back_val();
  288. if (!step.inst_id.is_valid()) {
  289. out << "<invalid type>";
  290. continue;
  291. }
  292. // Builtins have designated labels.
  293. if (step.inst_id.is_builtin()) {
  294. out << step.inst_id.builtin_kind().label();
  295. continue;
  296. }
  297. const auto& sem_ir = step.sem_ir;
  298. // Helper for instructions with the current sem_ir.
  299. auto push_inst_id = [&](InstId inst_id) {
  300. steps.push_back({.sem_ir = sem_ir, .inst_id = inst_id});
  301. };
  302. auto untyped_inst = sem_ir.insts().Get(step.inst_id);
  303. CARBON_KIND_SWITCH(untyped_inst) {
  304. case CARBON_KIND(ArrayType inst): {
  305. if (step.index == 0) {
  306. out << "[";
  307. steps.push_back(step.Next());
  308. push_inst_id(sem_ir.types().GetInstId(inst.element_type_id));
  309. } else if (step.index == 1) {
  310. out << "; " << sem_ir.GetArrayBoundValue(inst.bound_id) << "]";
  311. }
  312. break;
  313. }
  314. case CARBON_KIND(AssociatedEntityType inst): {
  315. if (step.index == 0) {
  316. out << "<associated ";
  317. steps.push_back(step.Next());
  318. push_inst_id(sem_ir.types().GetInstId(inst.entity_type_id));
  319. } else {
  320. auto interface_name_id =
  321. sem_ir.interfaces().Get(inst.interface_id).name_id;
  322. out << " in " << sem_ir.names().GetFormatted(interface_name_id)
  323. << ">";
  324. }
  325. break;
  326. }
  327. case BindAlias::Kind:
  328. case BindSymbolicName::Kind: {
  329. auto name_id = untyped_inst.As<AnyBindName>().bind_name_id;
  330. out << sem_ir.names().GetFormatted(
  331. sem_ir.bind_names().Get(name_id).name_id);
  332. break;
  333. }
  334. case CARBON_KIND(ClassType inst): {
  335. auto class_name_id = sem_ir.classes().Get(inst.class_id).name_id;
  336. out << sem_ir.names().GetFormatted(class_name_id);
  337. break;
  338. }
  339. case CARBON_KIND(ConstType inst): {
  340. if (step.index == 0) {
  341. out << "const ";
  342. // Add parentheses if required.
  343. auto inner_type_inst_id = sem_ir.types().GetInstId(inst.inner_id);
  344. if (GetTypePrecedence(sem_ir.insts().Get(inner_type_inst_id).kind()) <
  345. GetTypePrecedence(SemIR::ConstType::Kind)) {
  346. out << "(";
  347. steps.push_back(step.Next());
  348. }
  349. push_inst_id(inner_type_inst_id);
  350. } else if (step.index == 1) {
  351. out << ")";
  352. }
  353. break;
  354. }
  355. case CARBON_KIND(ExternType inst): {
  356. out << "extern ";
  357. push_inst_id(sem_ir.types().GetInstId(inst.non_extern_type_id));
  358. break;
  359. }
  360. case CARBON_KIND(FacetTypeAccess inst): {
  361. // Print `T as type` as simply `T`.
  362. push_inst_id(inst.facet_id);
  363. break;
  364. }
  365. case CARBON_KIND(FloatType inst): {
  366. // TODO: Is this okay?
  367. if (step.index == 1) {
  368. out << ")";
  369. } else if (auto width_value =
  370. sem_ir.insts().TryGetAs<IntLiteral>(inst.bit_width_id)) {
  371. out << "f";
  372. sem_ir.ints().Get(width_value->int_id).print(out, /*isSigned=*/false);
  373. } else {
  374. out << "Core.Float(";
  375. steps.push_back(step.Next());
  376. push_inst_id(inst.bit_width_id);
  377. }
  378. break;
  379. }
  380. case ImportRefLoaded::Kind:
  381. case ImportRefUsed::Kind: {
  382. auto import_ir_inst = sem_ir.import_ir_insts().Get(
  383. untyped_inst.As<AnyImportRef>().import_ir_inst_id);
  384. steps.push_back(
  385. {.sem_ir = *sem_ir.import_irs().Get(import_ir_inst.ir_id).sem_ir,
  386. .inst_id = import_ir_inst.inst_id});
  387. break;
  388. }
  389. case CARBON_KIND(InterfaceType inst): {
  390. auto interface_name_id =
  391. sem_ir.interfaces().Get(inst.interface_id).name_id;
  392. out << sem_ir.names().GetFormatted(interface_name_id);
  393. break;
  394. }
  395. case CARBON_KIND(IntType inst): {
  396. if (step.index == 1) {
  397. out << ")";
  398. } else if (auto width_value =
  399. sem_ir.insts().TryGetAs<IntLiteral>(inst.bit_width_id)) {
  400. out << (inst.int_kind.is_signed() ? "i" : "u");
  401. sem_ir.ints().Get(width_value->int_id).print(out, /*isSigned=*/false);
  402. } else {
  403. out << (inst.int_kind.is_signed() ? "Core.Int(" : "Core.UInt(");
  404. steps.push_back(step.Next());
  405. push_inst_id(inst.bit_width_id);
  406. }
  407. break;
  408. }
  409. case CARBON_KIND(NameRef inst): {
  410. out << sem_ir.names().GetFormatted(inst.name_id);
  411. break;
  412. }
  413. case CARBON_KIND(PointerType inst): {
  414. if (step.index == 0) {
  415. steps.push_back(step.Next());
  416. push_inst_id(sem_ir.types().GetInstId(inst.pointee_id));
  417. } else if (step.index == 1) {
  418. out << "*";
  419. }
  420. break;
  421. }
  422. case CARBON_KIND(StructType inst): {
  423. auto refs = sem_ir.inst_blocks().Get(inst.fields_id);
  424. if (refs.empty()) {
  425. out << "{}";
  426. break;
  427. } else if (step.index == 0) {
  428. out << "{";
  429. } else if (step.index < static_cast<int>(refs.size())) {
  430. out << ", ";
  431. } else {
  432. out << "}";
  433. break;
  434. }
  435. steps.push_back(step.Next());
  436. push_inst_id(refs[step.index]);
  437. break;
  438. }
  439. case CARBON_KIND(StructTypeField inst): {
  440. out << "." << sem_ir.names().GetFormatted(inst.name_id) << ": ";
  441. push_inst_id(sem_ir.types().GetInstId(inst.field_type_id));
  442. break;
  443. }
  444. case CARBON_KIND(TupleType inst): {
  445. auto refs = sem_ir.type_blocks().Get(inst.elements_id);
  446. if (refs.empty()) {
  447. out << "()";
  448. break;
  449. } else if (step.index == 0) {
  450. out << "(";
  451. } else if (step.index < static_cast<int>(refs.size())) {
  452. out << ", ";
  453. } else {
  454. // A tuple of one element has a comma to disambiguate from an
  455. // expression.
  456. if (step.index == 1) {
  457. out << ",";
  458. }
  459. out << ")";
  460. break;
  461. }
  462. steps.push_back(step.Next());
  463. push_inst_id(sem_ir.types().GetInstId(refs[step.index]));
  464. break;
  465. }
  466. case CARBON_KIND(UnboundElementType inst): {
  467. if (step.index == 0) {
  468. out << "<unbound element of class ";
  469. steps.push_back(step.Next());
  470. push_inst_id(sem_ir.types().GetInstId(inst.class_type_id));
  471. } else {
  472. out << ">";
  473. }
  474. break;
  475. }
  476. case AdaptDecl::Kind:
  477. case AddrOf::Kind:
  478. case AddrPattern::Kind:
  479. case ArrayIndex::Kind:
  480. case ArrayInit::Kind:
  481. case AsCompatible::Kind:
  482. case Assign::Kind:
  483. case AssociatedConstantDecl::Kind:
  484. case AssociatedEntity::Kind:
  485. case BaseDecl::Kind:
  486. case BindName::Kind:
  487. case BindValue::Kind:
  488. case BlockArg::Kind:
  489. case BoolLiteral::Kind:
  490. case BoundMethod::Kind:
  491. case Branch::Kind:
  492. case BranchIf::Kind:
  493. case BranchWithArg::Kind:
  494. case Builtin::Kind:
  495. case Call::Kind:
  496. case ClassDecl::Kind:
  497. case ClassElementAccess::Kind:
  498. case ClassInit::Kind:
  499. case Converted::Kind:
  500. case Deref::Kind:
  501. case ExternDecl::Kind:
  502. case FieldDecl::Kind:
  503. case FloatLiteral::Kind:
  504. case FunctionDecl::Kind:
  505. case ImplDecl::Kind:
  506. case ImportRefUnloaded::Kind:
  507. case InitializeFrom::Kind:
  508. case InterfaceDecl::Kind:
  509. case InterfaceWitness::Kind:
  510. case InterfaceWitnessAccess::Kind:
  511. case IntLiteral::Kind:
  512. case Namespace::Kind:
  513. case Param::Kind:
  514. case RealLiteral::Kind:
  515. case Return::Kind:
  516. case ReturnExpr::Kind:
  517. case SpliceBlock::Kind:
  518. case StringLiteral::Kind:
  519. case StructAccess::Kind:
  520. case StructLiteral::Kind:
  521. case StructInit::Kind:
  522. case StructValue::Kind:
  523. case Temporary::Kind:
  524. case TemporaryStorage::Kind:
  525. case TupleAccess::Kind:
  526. case TupleIndex::Kind:
  527. case TupleLiteral::Kind:
  528. case TupleInit::Kind:
  529. case TupleValue::Kind:
  530. case UnaryOperatorNot::Kind:
  531. case ValueAsRef::Kind:
  532. case ValueOfInitializer::Kind:
  533. case VarStorage::Kind:
  534. // We don't need to handle stringification for instructions that don't
  535. // show up in errors, but make it clear what's going on so that it's
  536. // clearer when stringification is needed.
  537. out << "<cannot stringify " << step.inst_id << ">";
  538. break;
  539. }
  540. }
  541. return str;
  542. }
  543. auto File::StringifyType(TypeId type_id) const -> std::string {
  544. return StringifyTypeExprImpl(*this, types().GetInstId(type_id));
  545. }
  546. auto File::StringifyTypeExpr(InstId outer_inst_id) const -> std::string {
  547. return StringifyTypeExprImpl(*this, outer_inst_id);
  548. }
  549. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
  550. const File* ir = &file;
  551. // The overall expression category if the current instruction is a value
  552. // expression.
  553. ExprCategory value_category = ExprCategory::Value;
  554. while (true) {
  555. auto untyped_inst = ir->insts().Get(inst_id);
  556. CARBON_KIND_SWITCH(untyped_inst) {
  557. case AdaptDecl::Kind:
  558. case Assign::Kind:
  559. case BaseDecl::Kind:
  560. case Branch::Kind:
  561. case BranchIf::Kind:
  562. case BranchWithArg::Kind:
  563. case FieldDecl::Kind:
  564. case FunctionDecl::Kind:
  565. case ImplDecl::Kind:
  566. case ImportRefUnloaded::Kind:
  567. case Namespace::Kind:
  568. case Return::Kind:
  569. case ReturnExpr::Kind:
  570. case StructTypeField::Kind:
  571. return ExprCategory::NotExpr;
  572. case ImportRefLoaded::Kind:
  573. case ImportRefUsed::Kind: {
  574. auto import_ir_inst = ir->import_ir_insts().Get(
  575. untyped_inst.As<AnyImportRef>().import_ir_inst_id);
  576. ir = ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  577. inst_id = import_ir_inst.inst_id;
  578. continue;
  579. }
  580. case CARBON_KIND(AsCompatible inst): {
  581. inst_id = inst.source_id;
  582. continue;
  583. }
  584. case CARBON_KIND(BindAlias inst): {
  585. inst_id = inst.value_id;
  586. continue;
  587. }
  588. case CARBON_KIND(NameRef inst): {
  589. inst_id = inst.value_id;
  590. continue;
  591. }
  592. case CARBON_KIND(Converted inst): {
  593. inst_id = inst.result_id;
  594. continue;
  595. }
  596. case AddrOf::Kind:
  597. case AddrPattern::Kind:
  598. case ArrayType::Kind:
  599. case AssociatedConstantDecl::Kind:
  600. case AssociatedEntity::Kind:
  601. case AssociatedEntityType::Kind:
  602. case BindSymbolicName::Kind:
  603. case BindValue::Kind:
  604. case BlockArg::Kind:
  605. case BoolLiteral::Kind:
  606. case BoundMethod::Kind:
  607. case ClassDecl::Kind:
  608. case ClassType::Kind:
  609. case ConstType::Kind:
  610. case ExternDecl::Kind:
  611. case ExternType::Kind:
  612. case FacetTypeAccess::Kind:
  613. case FloatLiteral::Kind:
  614. case FloatType::Kind:
  615. case InterfaceDecl::Kind:
  616. case InterfaceType::Kind:
  617. case InterfaceWitness::Kind:
  618. case InterfaceWitnessAccess::Kind:
  619. case IntLiteral::Kind:
  620. case IntType::Kind:
  621. case Param::Kind:
  622. case PointerType::Kind:
  623. case RealLiteral::Kind:
  624. case StringLiteral::Kind:
  625. case StructValue::Kind:
  626. case StructType::Kind:
  627. case TupleValue::Kind:
  628. case TupleType::Kind:
  629. case UnaryOperatorNot::Kind:
  630. case UnboundElementType::Kind:
  631. case ValueOfInitializer::Kind:
  632. return value_category;
  633. case CARBON_KIND(Builtin inst): {
  634. if (inst.builtin_kind == BuiltinKind::Error) {
  635. return ExprCategory::Error;
  636. }
  637. return value_category;
  638. }
  639. case CARBON_KIND(BindName inst): {
  640. inst_id = inst.value_id;
  641. continue;
  642. }
  643. case CARBON_KIND(ArrayIndex inst): {
  644. inst_id = inst.array_id;
  645. continue;
  646. }
  647. case CARBON_KIND(ClassElementAccess inst): {
  648. inst_id = inst.base_id;
  649. // A value of class type is a pointer to an object representation.
  650. // Therefore, if the base is a value, the result is an ephemeral
  651. // reference.
  652. value_category = ExprCategory::EphemeralRef;
  653. continue;
  654. }
  655. case CARBON_KIND(StructAccess inst): {
  656. inst_id = inst.struct_id;
  657. continue;
  658. }
  659. case CARBON_KIND(TupleAccess inst): {
  660. inst_id = inst.tuple_id;
  661. continue;
  662. }
  663. case CARBON_KIND(TupleIndex inst): {
  664. inst_id = inst.tuple_id;
  665. continue;
  666. }
  667. case CARBON_KIND(SpliceBlock inst): {
  668. inst_id = inst.result_id;
  669. continue;
  670. }
  671. case StructLiteral::Kind:
  672. case TupleLiteral::Kind:
  673. return ExprCategory::Mixed;
  674. case ArrayInit::Kind:
  675. case Call::Kind:
  676. case InitializeFrom::Kind:
  677. case ClassInit::Kind:
  678. case StructInit::Kind:
  679. case TupleInit::Kind:
  680. return ExprCategory::Initializing;
  681. case Deref::Kind:
  682. case VarStorage::Kind:
  683. return ExprCategory::DurableRef;
  684. case Temporary::Kind:
  685. case TemporaryStorage::Kind:
  686. case ValueAsRef::Kind:
  687. return ExprCategory::EphemeralRef;
  688. }
  689. }
  690. }
  691. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr {
  692. auto value_rep = GetValueRepr(file, type_id);
  693. switch (value_rep.kind) {
  694. case ValueRepr::None:
  695. return {.kind = InitRepr::None};
  696. case ValueRepr::Copy:
  697. // TODO: Use in-place initialization for types that have non-trivial
  698. // destructive move.
  699. return {.kind = InitRepr::ByCopy};
  700. case ValueRepr::Pointer:
  701. case ValueRepr::Custom:
  702. return {.kind = InitRepr::InPlace};
  703. case ValueRepr::Unknown:
  704. CARBON_FATAL()
  705. << "Attempting to perform initialization of incomplete type";
  706. }
  707. }
  708. } // namespace Carbon::SemIR