file.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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_inst_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 CompleteTypeInfo::Print(llvm::raw_ostream& out) const -> void {
  53. out << "{value_rep: " << value_repr << "}";
  54. }
  55. File::File(CheckIRId check_ir_id, IdentifierId package_id,
  56. StringLiteralValueId library_id, SharedValueStores& value_stores,
  57. std::string filename)
  58. : check_ir_id_(check_ir_id),
  59. package_id_(package_id),
  60. library_id_(library_id),
  61. value_stores_(&value_stores),
  62. filename_(std::move(filename)),
  63. type_blocks_(allocator_),
  64. name_scopes_(&insts_),
  65. constant_values_(ConstantId::NotConstant),
  66. inst_blocks_(allocator_),
  67. constants_(*this, allocator_) {
  68. // `type` and the error type are both complete types.
  69. types_.SetValueRepr(TypeId::TypeType,
  70. {.kind = ValueRepr::Copy, .type_id = TypeId::TypeType});
  71. types_.SetValueRepr(TypeId::Error,
  72. {.kind = ValueRepr::Copy, .type_id = TypeId::Error});
  73. insts_.Reserve(BuiltinInstKind::ValidCount);
  74. // Error uses a self-referential type so that it's not accidentally treated as
  75. // a normal type. Every other builtin is a type, including the
  76. // self-referential TypeType.
  77. #define CARBON_SEM_IR_BUILTIN_INST_KIND(Name, ...) \
  78. insts_.AddInNoBlock(LocIdAndInst::NoLoc<BuiltinInst>( \
  79. {.type_id = BuiltinInstKind::Name == BuiltinInstKind::Error \
  80. ? TypeId::Error \
  81. : TypeId::TypeType, \
  82. .builtin_inst_kind = BuiltinInstKind::Name}));
  83. #include "toolchain/sem_ir/builtin_inst_kind.def"
  84. CARBON_CHECK(insts_.size() == BuiltinInstKind::ValidCount)
  85. << "Builtins should produce " << BuiltinInstKind::ValidCount
  86. << " insts, actual: " << insts_.size();
  87. for (auto i : llvm::seq(BuiltinInstKind::ValidCount)) {
  88. auto builtin_id = SemIR::InstId(i);
  89. constant_values_.Set(builtin_id,
  90. SemIR::ConstantId::ForTemplateConstant(builtin_id));
  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(
  132. "sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  133. map.Add("import_irs", import_irs_.OutputYaml());
  134. map.Add("import_ir_insts", import_ir_insts_.OutputYaml());
  135. map.Add("name_scopes", name_scopes_.OutputYaml());
  136. map.Add("entity_names", entity_names_.OutputYaml());
  137. map.Add("functions", functions_.OutputYaml());
  138. map.Add("classes", classes_.OutputYaml());
  139. map.Add("generics", generics_.OutputYaml());
  140. map.Add("specifics", specifics_.OutputYaml());
  141. map.Add("types", types_.OutputYaml());
  142. map.Add("type_blocks", type_blocks_.OutputYaml());
  143. map.Add(
  144. "insts", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  145. int start = include_builtins ? 0 : BuiltinInstKind::ValidCount;
  146. for (int i : llvm::seq(start, insts_.size())) {
  147. auto id = InstId(i);
  148. map.Add(PrintToString(id),
  149. Yaml::OutputScalar(insts_.Get(id)));
  150. }
  151. }));
  152. map.Add("constant_values",
  153. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  154. int start =
  155. include_builtins ? 0 : BuiltinInstKind::ValidCount;
  156. for (int i : llvm::seq(start, insts_.size())) {
  157. auto id = InstId(i);
  158. auto value = constant_values_.Get(id);
  159. if (!value.is_valid() || value.is_constant()) {
  160. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  161. }
  162. }
  163. }));
  164. map.Add(
  165. "symbolic_constants",
  166. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  167. for (const auto& [i, symbolic] :
  168. llvm::enumerate(constant_values().symbolic_constants())) {
  169. map.Add(
  170. PrintToString(ConstantId::ForSymbolicConstantIndex(i)),
  171. Yaml::OutputScalar(symbolic));
  172. }
  173. }));
  174. map.Add("inst_blocks", inst_blocks_.OutputYaml());
  175. }));
  176. });
  177. }
  178. auto File::CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  179. -> void {
  180. mem_usage.Add(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
  181. mem_usage.Collect(MemUsage::ConcatLabel(label, "entity_names_"),
  182. entity_names_);
  183. mem_usage.Collect(MemUsage::ConcatLabel(label, "functions_"), functions_);
  184. mem_usage.Collect(MemUsage::ConcatLabel(label, "classes_"), classes_);
  185. mem_usage.Collect(MemUsage::ConcatLabel(label, "interfaces_"), interfaces_);
  186. mem_usage.Collect(MemUsage::ConcatLabel(label, "impls_"), impls_);
  187. mem_usage.Collect(MemUsage::ConcatLabel(label, "generics_"), generics_);
  188. mem_usage.Collect(MemUsage::ConcatLabel(label, "specifics_"), specifics_);
  189. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_irs_"), import_irs_);
  190. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_ir_insts_"),
  191. import_ir_insts_);
  192. mem_usage.Collect(MemUsage::ConcatLabel(label, "type_blocks_"), type_blocks_);
  193. mem_usage.Collect(MemUsage::ConcatLabel(label, "insts_"), insts_);
  194. mem_usage.Collect(MemUsage::ConcatLabel(label, "name_scopes_"), name_scopes_);
  195. mem_usage.Collect(MemUsage::ConcatLabel(label, "constant_values_"),
  196. constant_values_);
  197. mem_usage.Collect(MemUsage::ConcatLabel(label, "inst_blocks_"), inst_blocks_);
  198. mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
  199. mem_usage.Collect(MemUsage::ConcatLabel(label, "types_"), types_);
  200. }
  201. // Map an instruction kind representing a type into an integer describing the
  202. // precedence of that type's syntax. Higher numbers correspond to higher
  203. // precedence.
  204. static auto GetTypePrecedence(InstKind kind) -> int {
  205. CARBON_CHECK(kind.is_type() != InstIsType::Never)
  206. << "Only called for kinds which can define a type.";
  207. if (kind == ConstType::Kind) {
  208. return -1;
  209. }
  210. if (kind == PointerType::Kind) {
  211. return -2;
  212. }
  213. return 0;
  214. }
  215. // Implements File::StringifyTypeExpr. Static to prevent accidental use of
  216. // member functions while traversing IRs.
  217. static auto StringifyTypeExprImpl(const SemIR::File& outer_sem_ir,
  218. InstId outer_inst_id) {
  219. std::string str;
  220. llvm::raw_string_ostream out(str);
  221. struct Step {
  222. // The instruction's file.
  223. const File& sem_ir;
  224. // The instruction to print.
  225. InstId inst_id;
  226. // The index into inst_id to print. Not used by all types.
  227. int index = 0;
  228. auto Next() const -> Step {
  229. return {.sem_ir = sem_ir, .inst_id = inst_id, .index = index + 1};
  230. }
  231. };
  232. llvm::SmallVector<Step> steps = {
  233. Step{.sem_ir = outer_sem_ir, .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.is_builtin()) {
  242. out << step.inst_id.builtin_inst_kind().label();
  243. continue;
  244. }
  245. const auto& sem_ir = step.sem_ir;
  246. // Helper for instructions with the current sem_ir.
  247. auto push_inst_id = [&](InstId inst_id) {
  248. steps.push_back({.sem_ir = sem_ir, .inst_id = inst_id});
  249. };
  250. auto untyped_inst = sem_ir.insts().Get(step.inst_id);
  251. CARBON_KIND_SWITCH(untyped_inst) {
  252. case CARBON_KIND(ArrayType inst): {
  253. if (step.index == 0) {
  254. out << "[";
  255. steps.push_back(step.Next());
  256. push_inst_id(sem_ir.types().GetInstId(inst.element_type_id));
  257. } else if (step.index == 1) {
  258. out << "; " << sem_ir.GetArrayBoundValue(inst.bound_id) << "]";
  259. }
  260. break;
  261. }
  262. case CARBON_KIND(AssociatedEntityType inst): {
  263. if (step.index == 0) {
  264. out << "<associated ";
  265. steps.push_back(step.Next());
  266. push_inst_id(sem_ir.types().GetInstId(inst.entity_type_id));
  267. } else {
  268. auto interface_name_id =
  269. sem_ir.interfaces().Get(inst.interface_id).name_id;
  270. out << " in " << sem_ir.names().GetFormatted(interface_name_id)
  271. << ">";
  272. }
  273. break;
  274. }
  275. case BindAlias::Kind:
  276. case BindSymbolicName::Kind:
  277. case ExportDecl::Kind: {
  278. auto name_id =
  279. untyped_inst.As<AnyBindNameOrExportDecl>().entity_name_id;
  280. out << sem_ir.names().GetFormatted(
  281. sem_ir.entity_names().Get(name_id).name_id);
  282. break;
  283. }
  284. case CARBON_KIND(ClassType inst): {
  285. auto class_name_id = sem_ir.classes().Get(inst.class_id).name_id;
  286. out << sem_ir.names().GetFormatted(class_name_id);
  287. break;
  288. }
  289. case CARBON_KIND(ConstType inst): {
  290. if (step.index == 0) {
  291. out << "const ";
  292. // Add parentheses if required.
  293. auto inner_type_inst_id = sem_ir.types().GetInstId(inst.inner_id);
  294. if (GetTypePrecedence(sem_ir.insts().Get(inner_type_inst_id).kind()) <
  295. GetTypePrecedence(SemIR::ConstType::Kind)) {
  296. out << "(";
  297. steps.push_back(step.Next());
  298. }
  299. push_inst_id(inner_type_inst_id);
  300. } else if (step.index == 1) {
  301. out << ")";
  302. }
  303. break;
  304. }
  305. case CARBON_KIND(FacetTypeAccess inst): {
  306. // Print `T as type` as simply `T`.
  307. push_inst_id(inst.facet_id);
  308. break;
  309. }
  310. case CARBON_KIND(FloatType inst): {
  311. // TODO: Is this okay?
  312. if (step.index == 1) {
  313. out << ")";
  314. } else if (auto width_value =
  315. sem_ir.insts().TryGetAs<IntLiteral>(inst.bit_width_id)) {
  316. out << "f";
  317. sem_ir.ints().Get(width_value->int_id).print(out, /*isSigned=*/false);
  318. } else {
  319. out << "Core.Float(";
  320. steps.push_back(step.Next());
  321. push_inst_id(inst.bit_width_id);
  322. }
  323. break;
  324. }
  325. case CARBON_KIND(FunctionType inst): {
  326. auto fn_name_id = sem_ir.functions().Get(inst.function_id).name_id;
  327. out << "<type of " << sem_ir.names().GetFormatted(fn_name_id) << ">";
  328. break;
  329. }
  330. case CARBON_KIND(GenericClassType inst): {
  331. auto class_name_id = sem_ir.classes().Get(inst.class_id).name_id;
  332. out << "<type of " << sem_ir.names().GetFormatted(class_name_id) << ">";
  333. break;
  334. }
  335. case CARBON_KIND(GenericInterfaceType inst): {
  336. auto interface_name_id =
  337. sem_ir.interfaces().Get(inst.interface_id).name_id;
  338. out << "<type of " << sem_ir.names().GetFormatted(interface_name_id)
  339. << ">";
  340. break;
  341. }
  342. case CARBON_KIND(InterfaceType inst): {
  343. auto interface_name_id =
  344. sem_ir.interfaces().Get(inst.interface_id).name_id;
  345. out << sem_ir.names().GetFormatted(interface_name_id);
  346. break;
  347. }
  348. case CARBON_KIND(IntType inst): {
  349. if (step.index == 1) {
  350. out << ")";
  351. } else if (auto width_value =
  352. sem_ir.insts().TryGetAs<IntLiteral>(inst.bit_width_id)) {
  353. out << (inst.int_kind.is_signed() ? "i" : "u");
  354. sem_ir.ints().Get(width_value->int_id).print(out, /*isSigned=*/false);
  355. } else {
  356. out << (inst.int_kind.is_signed() ? "Core.Int(" : "Core.UInt(");
  357. steps.push_back(step.Next());
  358. push_inst_id(inst.bit_width_id);
  359. }
  360. break;
  361. }
  362. case CARBON_KIND(NameRef inst): {
  363. out << sem_ir.names().GetFormatted(inst.name_id);
  364. break;
  365. }
  366. case CARBON_KIND(PointerType inst): {
  367. if (step.index == 0) {
  368. steps.push_back(step.Next());
  369. push_inst_id(sem_ir.types().GetInstId(inst.pointee_id));
  370. } else if (step.index == 1) {
  371. out << "*";
  372. }
  373. break;
  374. }
  375. case CARBON_KIND(StructType inst): {
  376. auto refs = sem_ir.inst_blocks().Get(inst.fields_id);
  377. if (refs.empty()) {
  378. out << "{}";
  379. break;
  380. } else if (step.index == 0) {
  381. out << "{";
  382. } else if (step.index < static_cast<int>(refs.size())) {
  383. out << ", ";
  384. } else {
  385. out << "}";
  386. break;
  387. }
  388. steps.push_back(step.Next());
  389. push_inst_id(refs[step.index]);
  390. break;
  391. }
  392. case CARBON_KIND(StructTypeField inst): {
  393. out << "." << sem_ir.names().GetFormatted(inst.name_id) << ": ";
  394. push_inst_id(sem_ir.types().GetInstId(inst.field_type_id));
  395. break;
  396. }
  397. case CARBON_KIND(TupleType inst): {
  398. auto refs = sem_ir.type_blocks().Get(inst.elements_id);
  399. if (refs.empty()) {
  400. out << "()";
  401. break;
  402. } else if (step.index == 0) {
  403. out << "(";
  404. } else if (step.index < static_cast<int>(refs.size())) {
  405. out << ", ";
  406. } else {
  407. // A tuple of one element has a comma to disambiguate from an
  408. // expression.
  409. if (step.index == 1) {
  410. out << ",";
  411. }
  412. out << ")";
  413. break;
  414. }
  415. steps.push_back(step.Next());
  416. push_inst_id(sem_ir.types().GetInstId(refs[step.index]));
  417. break;
  418. }
  419. case CARBON_KIND(UnboundElementType inst): {
  420. if (step.index == 0) {
  421. out << "<unbound element of class ";
  422. steps.push_back(step.Next());
  423. push_inst_id(sem_ir.types().GetInstId(inst.class_type_id));
  424. } else {
  425. out << ">";
  426. }
  427. break;
  428. }
  429. case AdaptDecl::Kind:
  430. case AddrOf::Kind:
  431. case AddrPattern::Kind:
  432. case ArrayIndex::Kind:
  433. case ArrayInit::Kind:
  434. case AsCompatible::Kind:
  435. case Assign::Kind:
  436. case AssociatedConstantDecl::Kind:
  437. case AssociatedEntity::Kind:
  438. case BaseDecl::Kind:
  439. case BindName::Kind:
  440. case BindValue::Kind:
  441. case BlockArg::Kind:
  442. case BoolLiteral::Kind:
  443. case BoundMethod::Kind:
  444. case Branch::Kind:
  445. case BranchIf::Kind:
  446. case BranchWithArg::Kind:
  447. case BuiltinInst::Kind:
  448. case Call::Kind:
  449. case ClassDecl::Kind:
  450. case ClassElementAccess::Kind:
  451. case ClassInit::Kind:
  452. case Converted::Kind:
  453. case Deref::Kind:
  454. case FieldDecl::Kind:
  455. case FloatLiteral::Kind:
  456. case FunctionDecl::Kind:
  457. case ImplDecl::Kind:
  458. case ImportDecl::Kind:
  459. case ImportRefLoaded::Kind:
  460. case ImportRefUnloaded::Kind:
  461. case InitializeFrom::Kind:
  462. case SpecificConstant::Kind:
  463. case InterfaceDecl::Kind:
  464. case InterfaceWitness::Kind:
  465. case InterfaceWitnessAccess::Kind:
  466. case IntLiteral::Kind:
  467. case Namespace::Kind:
  468. case Param::Kind:
  469. case Return::Kind:
  470. case ReturnExpr::Kind:
  471. case SpliceBlock::Kind:
  472. case StringLiteral::Kind:
  473. case StructAccess::Kind:
  474. case StructLiteral::Kind:
  475. case StructInit::Kind:
  476. case StructValue::Kind:
  477. case Temporary::Kind:
  478. case TemporaryStorage::Kind:
  479. case TupleAccess::Kind:
  480. case TupleIndex::Kind:
  481. case TupleLiteral::Kind:
  482. case TupleInit::Kind:
  483. case TupleValue::Kind:
  484. case UnaryOperatorNot::Kind:
  485. case ValueAsRef::Kind:
  486. case ValueOfInitializer::Kind:
  487. case VarStorage::Kind:
  488. // We don't need to handle stringification for instructions that don't
  489. // show up in errors, but make it clear what's going on so that it's
  490. // clearer when stringification is needed.
  491. out << "<cannot stringify " << step.inst_id << ">";
  492. break;
  493. }
  494. }
  495. return str;
  496. }
  497. auto File::StringifyType(TypeId type_id) const -> std::string {
  498. return StringifyTypeExprImpl(*this, types().GetInstId(type_id));
  499. }
  500. auto File::StringifyType(ConstantId type_const_id) const -> std::string {
  501. return StringifyTypeExprImpl(*this,
  502. constant_values().GetInstId(type_const_id));
  503. }
  504. auto File::StringifyTypeExpr(InstId outer_inst_id) const -> std::string {
  505. return StringifyTypeExprImpl(*this, outer_inst_id);
  506. }
  507. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
  508. const File* ir = &file;
  509. // The overall expression category if the current instruction is a value
  510. // expression.
  511. ExprCategory value_category = ExprCategory::Value;
  512. while (true) {
  513. auto untyped_inst = ir->insts().Get(inst_id);
  514. CARBON_KIND_SWITCH(untyped_inst) {
  515. case AdaptDecl::Kind:
  516. case Assign::Kind:
  517. case BaseDecl::Kind:
  518. case Branch::Kind:
  519. case BranchIf::Kind:
  520. case BranchWithArg::Kind:
  521. case FieldDecl::Kind:
  522. case FunctionDecl::Kind:
  523. case ImplDecl::Kind:
  524. case Namespace::Kind:
  525. case Return::Kind:
  526. case ReturnExpr::Kind:
  527. case StructTypeField::Kind:
  528. return ExprCategory::NotExpr;
  529. case ImportRefUnloaded::Kind:
  530. case ImportRefLoaded::Kind: {
  531. auto import_ir_inst = ir->import_ir_insts().Get(
  532. untyped_inst.As<SemIR::AnyImportRef>().import_ir_inst_id);
  533. ir = ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  534. inst_id = import_ir_inst.inst_id;
  535. continue;
  536. }
  537. case CARBON_KIND(AsCompatible inst): {
  538. inst_id = inst.source_id;
  539. continue;
  540. }
  541. case CARBON_KIND(BindAlias inst): {
  542. inst_id = inst.value_id;
  543. continue;
  544. }
  545. case CARBON_KIND(ExportDecl inst): {
  546. inst_id = inst.value_id;
  547. continue;
  548. }
  549. case CARBON_KIND(NameRef inst): {
  550. inst_id = inst.value_id;
  551. continue;
  552. }
  553. case CARBON_KIND(Converted inst): {
  554. inst_id = inst.result_id;
  555. continue;
  556. }
  557. case CARBON_KIND(SpecificConstant inst): {
  558. inst_id = inst.inst_id;
  559. continue;
  560. }
  561. case AddrOf::Kind:
  562. case AddrPattern::Kind:
  563. case ArrayType::Kind:
  564. case AssociatedConstantDecl::Kind:
  565. case AssociatedEntity::Kind:
  566. case AssociatedEntityType::Kind:
  567. case BindSymbolicName::Kind:
  568. case BindValue::Kind:
  569. case BlockArg::Kind:
  570. case BoolLiteral::Kind:
  571. case BoundMethod::Kind:
  572. case ClassDecl::Kind:
  573. case ClassType::Kind:
  574. case ConstType::Kind:
  575. case FacetTypeAccess::Kind:
  576. case FloatLiteral::Kind:
  577. case FloatType::Kind:
  578. case FunctionType::Kind:
  579. case GenericClassType::Kind:
  580. case GenericInterfaceType::Kind:
  581. case ImportDecl::Kind:
  582. case InterfaceDecl::Kind:
  583. case InterfaceType::Kind:
  584. case InterfaceWitness::Kind:
  585. case InterfaceWitnessAccess::Kind:
  586. case IntLiteral::Kind:
  587. case IntType::Kind:
  588. case Param::Kind:
  589. case PointerType::Kind:
  590. case StringLiteral::Kind:
  591. case StructValue::Kind:
  592. case StructType::Kind:
  593. case TupleValue::Kind:
  594. case TupleType::Kind:
  595. case UnaryOperatorNot::Kind:
  596. case UnboundElementType::Kind:
  597. case ValueOfInitializer::Kind:
  598. return value_category;
  599. case CARBON_KIND(BuiltinInst inst): {
  600. if (inst.builtin_inst_kind == BuiltinInstKind::Error) {
  601. return ExprCategory::Error;
  602. }
  603. return value_category;
  604. }
  605. case CARBON_KIND(BindName inst): {
  606. inst_id = inst.value_id;
  607. continue;
  608. }
  609. case CARBON_KIND(ArrayIndex inst): {
  610. inst_id = inst.array_id;
  611. continue;
  612. }
  613. case CARBON_KIND(ClassElementAccess inst): {
  614. inst_id = inst.base_id;
  615. // A value of class type is a pointer to an object representation.
  616. // Therefore, if the base is a value, the result is an ephemeral
  617. // reference.
  618. value_category = ExprCategory::EphemeralRef;
  619. continue;
  620. }
  621. case CARBON_KIND(StructAccess inst): {
  622. inst_id = inst.struct_id;
  623. continue;
  624. }
  625. case CARBON_KIND(TupleAccess inst): {
  626. inst_id = inst.tuple_id;
  627. continue;
  628. }
  629. case CARBON_KIND(TupleIndex inst): {
  630. inst_id = inst.tuple_id;
  631. continue;
  632. }
  633. case CARBON_KIND(SpliceBlock inst): {
  634. inst_id = inst.result_id;
  635. continue;
  636. }
  637. case StructLiteral::Kind:
  638. case TupleLiteral::Kind:
  639. return ExprCategory::Mixed;
  640. case ArrayInit::Kind:
  641. case Call::Kind:
  642. case InitializeFrom::Kind:
  643. case ClassInit::Kind:
  644. case StructInit::Kind:
  645. case TupleInit::Kind:
  646. return ExprCategory::Initializing;
  647. case Deref::Kind:
  648. case VarStorage::Kind:
  649. return ExprCategory::DurableRef;
  650. case Temporary::Kind:
  651. case TemporaryStorage::Kind:
  652. case ValueAsRef::Kind:
  653. return ExprCategory::EphemeralRef;
  654. }
  655. }
  656. }
  657. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr {
  658. auto value_rep = GetValueRepr(file, type_id);
  659. switch (value_rep.kind) {
  660. case ValueRepr::None:
  661. return {.kind = InitRepr::None};
  662. case ValueRepr::Copy:
  663. // TODO: Use in-place initialization for types that have non-trivial
  664. // destructive move.
  665. return {.kind = InitRepr::ByCopy};
  666. case ValueRepr::Pointer:
  667. case ValueRepr::Custom:
  668. return {.kind = InitRepr::InPlace};
  669. case ValueRepr::Unknown:
  670. CARBON_FATAL()
  671. << "Attempting to perform initialization of incomplete type "
  672. << file.types().GetAsInst(type_id);
  673. }
  674. }
  675. } // namespace Carbon::SemIR