convert.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  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/check/convert.h"
  5. #include <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "common/map.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/action.h"
  12. #include "toolchain/check/context.h"
  13. #include "toolchain/check/control_flow.h"
  14. #include "toolchain/check/diagnostic_helpers.h"
  15. #include "toolchain/check/eval.h"
  16. #include "toolchain/check/impl_lookup.h"
  17. #include "toolchain/check/inst.h"
  18. #include "toolchain/check/operator.h"
  19. #include "toolchain/check/pattern_match.h"
  20. #include "toolchain/check/type.h"
  21. #include "toolchain/check/type_completion.h"
  22. #include "toolchain/diagnostics/format_providers.h"
  23. #include "toolchain/sem_ir/copy_on_write_block.h"
  24. #include "toolchain/sem_ir/expr_info.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/generic.h"
  27. #include "toolchain/sem_ir/ids.h"
  28. #include "toolchain/sem_ir/inst.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. // TODO: This contains a lot of recursion. Consider removing it in order to
  31. // prevent accidents.
  32. // NOLINTBEGIN(misc-no-recursion)
  33. namespace Carbon::Check {
  34. // Marks the initializer `init_id` as initializing `target_id`.
  35. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  36. SemIR::InstId target_id,
  37. PendingBlock& target_block) -> void {
  38. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  39. if (return_slot_arg_id.has_value()) {
  40. // Replace the temporary in the return slot with a reference to our target.
  41. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  42. SemIR::TemporaryStorage::Kind,
  43. "Return slot for initializer does not contain a temporary; "
  44. "initialized multiple times? Have {0}",
  45. sem_ir.insts().Get(return_slot_arg_id));
  46. target_block.MergeReplacing(return_slot_arg_id, target_id);
  47. }
  48. }
  49. // Commits to using a temporary to store the result of the initializing
  50. // expression described by `init_id`, and returns the location of the
  51. // temporary. If `discarded` is `true`, the result is discarded, and no
  52. // temporary will be created if possible; if no temporary is created, the
  53. // return value will be `SemIR::InstId::None`.
  54. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  55. bool discarded) -> SemIR::InstId {
  56. auto& sem_ir = context.sem_ir();
  57. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  58. if (return_slot_arg_id.has_value()) {
  59. // The return slot should already have a materialized temporary in it.
  60. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  61. SemIR::TemporaryStorage::Kind,
  62. "Return slot for initializer does not contain a temporary; "
  63. "initialized multiple times? Have {0}",
  64. sem_ir.insts().Get(return_slot_arg_id));
  65. auto init = sem_ir.insts().Get(init_id);
  66. return AddInst<SemIR::Temporary>(context, sem_ir.insts().GetLocId(init_id),
  67. {.type_id = init.type_id(),
  68. .storage_id = return_slot_arg_id,
  69. .init_id = init_id});
  70. }
  71. if (discarded) {
  72. // Don't invent a temporary that we're going to discard.
  73. return SemIR::InstId::None;
  74. }
  75. // The initializer has no return slot, but we want to produce a temporary
  76. // object. Materialize one now.
  77. // TODO: Consider using `None` to mean that we immediately materialize and
  78. // initialize a temporary, rather than two separate instructions.
  79. auto init = sem_ir.insts().Get(init_id);
  80. auto loc_id = sem_ir.insts().GetLocId(init_id);
  81. auto temporary_id = AddInstWithCleanup<SemIR::TemporaryStorage>(
  82. context, loc_id, {.type_id = init.type_id()});
  83. return AddInst<SemIR::Temporary>(context, loc_id,
  84. {.type_id = init.type_id(),
  85. .storage_id = temporary_id,
  86. .init_id = init_id});
  87. }
  88. // Materialize a temporary to hold the result of the given expression if it is
  89. // an initializing expression.
  90. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  91. -> SemIR::InstId {
  92. if (GetExprCategory(context.sem_ir(), expr_id) ==
  93. SemIR::ExprCategory::Initializing) {
  94. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  95. }
  96. return expr_id;
  97. }
  98. // Helper to allow `MakeElementAccessInst` to call `AddInst` with either a
  99. // `PendingBlock` or `Context` (defined in `inst.h`).
  100. template <typename AccessInstT>
  101. static auto AddInst(PendingBlock& block, SemIR::LocId loc_id, AccessInstT inst)
  102. -> SemIR::InstId {
  103. return block.AddInst<AccessInstT>(loc_id, inst);
  104. }
  105. // Creates and adds an instruction to perform element access into an aggregate.
  106. template <typename AccessInstT, typename InstBlockT>
  107. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  108. SemIR::InstId aggregate_id,
  109. SemIR::TypeId elem_type_id, InstBlockT& block,
  110. size_t i) -> SemIR::InstId {
  111. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  112. // TODO: Add a new instruction kind for indexing an array at a constant
  113. // index so that we don't need an integer literal instruction here, and
  114. // remove this special case.
  115. auto index_id = block.template AddInst<SemIR::IntValue>(
  116. loc_id, {.type_id = GetSingletonType(
  117. context, SemIR::IntLiteralType::SingletonInstId),
  118. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  119. return AddInst<AccessInstT>(block, loc_id,
  120. {elem_type_id, aggregate_id, index_id});
  121. } else {
  122. return AddInst<AccessInstT>(
  123. block, loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  124. }
  125. }
  126. // Converts an element of one aggregate so that it can be used as an element of
  127. // another aggregate.
  128. //
  129. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  130. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  131. // kind of instruction used to access the source element.
  132. //
  133. // For the target: `kind` is the kind of conversion or initialization,
  134. // `target_elem_type` is the element type. For initialization, `target_id` is
  135. // the destination, `target_block` is a pending block for target location
  136. // calculations that will be spliced as the return slot of the initializer if
  137. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  138. // kind of instruction used to access the destination element.
  139. template <typename SourceAccessInstT, typename TargetAccessInstT>
  140. static auto ConvertAggregateElement(
  141. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  142. SemIR::TypeId src_elem_type,
  143. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  144. ConversionTarget::Kind kind, SemIR::InstId target_id,
  145. SemIR::TypeId target_elem_type, PendingBlock* target_block,
  146. size_t src_field_index, size_t target_field_index,
  147. SemIR::InstId vtable_id = SemIR::InstId::None) -> SemIR::InstId {
  148. // Compute the location of the source element. This goes into the current code
  149. // block, not into the target block.
  150. // TODO: Ideally we would discard this instruction if it's unused.
  151. auto src_elem_id = !src_literal_elems.empty()
  152. ? src_literal_elems[src_field_index]
  153. : MakeElementAccessInst<SourceAccessInstT>(
  154. context, loc_id, src_id, src_elem_type, context,
  155. src_field_index);
  156. // If we're performing a conversion rather than an initialization, we won't
  157. // have or need a target.
  158. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  159. if (!target.is_initializer()) {
  160. return Convert(context, loc_id, src_elem_id, target);
  161. }
  162. // Compute the location of the target element and initialize it.
  163. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  164. target.init_block = target_block;
  165. target.init_id = MakeElementAccessInst<TargetAccessInstT>(
  166. context, loc_id, target_id, target_elem_type, *target_block,
  167. target_field_index);
  168. return Convert(context, loc_id, src_elem_id, target, vtable_id);
  169. }
  170. // Performs a conversion from a tuple to an array type. This function only
  171. // converts the type, and does not perform a final conversion to the requested
  172. // expression category.
  173. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  174. SemIR::ArrayType array_type,
  175. SemIR::InstId value_id, ConversionTarget target)
  176. -> SemIR::InstId {
  177. auto& sem_ir = context.sem_ir();
  178. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  179. auto value = sem_ir.insts().Get(value_id);
  180. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  181. // If we're initializing from a tuple literal, we will use its elements
  182. // directly. Otherwise, materialize a temporary if needed and index into the
  183. // result.
  184. llvm::ArrayRef<SemIR::InstId> literal_elems;
  185. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  186. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  187. } else {
  188. value_id = MaterializeIfInitializing(context, value_id);
  189. }
  190. // Check that the tuple is the right size.
  191. std::optional<uint64_t> array_bound =
  192. sem_ir.GetArrayBoundValue(array_type.bound_id);
  193. if (!array_bound) {
  194. // TODO: Should this fall back to using `ImplicitAs`?
  195. if (target.diagnose) {
  196. CARBON_DIAGNOSTIC(ArrayInitDependentBound, Error,
  197. "cannot initialize array with dependent bound from a "
  198. "list of initializers");
  199. context.emitter().Emit(value_loc_id, ArrayInitDependentBound);
  200. }
  201. return SemIR::ErrorInst::SingletonInstId;
  202. }
  203. if (tuple_elem_types.size() != array_bound) {
  204. if (target.diagnose) {
  205. CARBON_DIAGNOSTIC(ArrayInitFromLiteralArgCountMismatch, Error,
  206. "cannot initialize array of {0} element{0:s} from {1} "
  207. "initializer{1:s}",
  208. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  209. CARBON_DIAGNOSTIC(
  210. ArrayInitFromExprArgCountMismatch, Error,
  211. "cannot initialize array of {0} element{0:s} from tuple "
  212. "with {1} element{1:s}",
  213. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  214. context.emitter().Emit(value_loc_id,
  215. literal_elems.empty()
  216. ? ArrayInitFromExprArgCountMismatch
  217. : ArrayInitFromLiteralArgCountMismatch,
  218. *array_bound, tuple_elem_types.size());
  219. }
  220. return SemIR::ErrorInst::SingletonInstId;
  221. }
  222. PendingBlock target_block_storage(&context);
  223. PendingBlock* target_block =
  224. target.init_block ? target.init_block : &target_block_storage;
  225. // Arrays are always initialized in-place. Allocate a temporary as the
  226. // destination for the array initialization if we weren't given one.
  227. SemIR::InstId return_slot_arg_id = target.init_id;
  228. if (!target.init_id.has_value()) {
  229. return_slot_arg_id =
  230. target_block->AddInstWithCleanup<SemIR::TemporaryStorage>(
  231. value_loc_id, {.type_id = target.type_id});
  232. }
  233. // Initialize each element of the array from the corresponding element of the
  234. // tuple.
  235. // TODO: Annotate diagnostics coming from here with the array element index,
  236. // if initializing from a tuple literal.
  237. llvm::SmallVector<SemIR::InstId> inits;
  238. inits.reserve(*array_bound + 1);
  239. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  240. // TODO: This call recurses back into conversion. Switch to an iterative
  241. // approach.
  242. auto init_id =
  243. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  244. context, value_loc_id, value_id, src_type_id, literal_elems,
  245. ConversionTarget::FullInitializer, return_slot_arg_id,
  246. context.types().GetTypeIdForTypeInstId(
  247. array_type.element_type_inst_id),
  248. target_block, i, i);
  249. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  250. return SemIR::ErrorInst::SingletonInstId;
  251. }
  252. inits.push_back(init_id);
  253. }
  254. // Flush the temporary here if we didn't insert it earlier, so we can add a
  255. // reference to the return slot.
  256. target_block->InsertHere();
  257. return AddInst<SemIR::ArrayInit>(context, value_loc_id,
  258. {.type_id = target.type_id,
  259. .inits_id = sem_ir.inst_blocks().Add(inits),
  260. .dest_id = return_slot_arg_id});
  261. }
  262. // Performs a conversion from a tuple to a tuple type. This function only
  263. // converts the type, and does not perform a final conversion to the requested
  264. // expression category.
  265. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  266. SemIR::TupleType dest_type,
  267. SemIR::InstId value_id, ConversionTarget target)
  268. -> SemIR::InstId {
  269. auto& sem_ir = context.sem_ir();
  270. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  271. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  272. auto value = sem_ir.insts().Get(value_id);
  273. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  274. // If we're initializing from a tuple literal, we will use its elements
  275. // directly. Otherwise, materialize a temporary if needed and index into the
  276. // result.
  277. llvm::ArrayRef<SemIR::InstId> literal_elems;
  278. auto literal_elems_id = SemIR::InstBlockId::None;
  279. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  280. literal_elems_id = tuple_literal->elements_id;
  281. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  282. } else {
  283. value_id = MaterializeIfInitializing(context, value_id);
  284. }
  285. // Check that the tuples are the same size.
  286. if (src_elem_types.size() != dest_elem_types.size()) {
  287. if (target.diagnose) {
  288. CARBON_DIAGNOSTIC(
  289. TupleInitElementCountMismatch, Error,
  290. "cannot initialize tuple of {0} element{0:s} from tuple "
  291. "with {1} element{1:s}",
  292. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  293. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  294. dest_elem_types.size(), src_elem_types.size());
  295. }
  296. return SemIR::ErrorInst::SingletonInstId;
  297. }
  298. // If we're forming an initializer, then we want an initializer for each
  299. // element. Otherwise, we want a value representation for each element.
  300. // Perform a final destination store if we're performing an in-place
  301. // initialization.
  302. bool is_init = target.is_initializer();
  303. ConversionTarget::Kind inner_kind =
  304. !is_init ? ConversionTarget::Value
  305. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  306. SemIR::InitRepr::InPlace
  307. ? ConversionTarget::FullInitializer
  308. : ConversionTarget::Initializer;
  309. // Initialize each element of the destination from the corresponding element
  310. // of the source.
  311. // TODO: Annotate diagnostics coming from here with the element index.
  312. auto new_block =
  313. literal_elems_id.has_value()
  314. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  315. : SemIR::CopyOnWriteInstBlock(
  316. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  317. src_elem_types.size()});
  318. for (auto [i, src_type_id, dest_type_id] :
  319. llvm::enumerate(src_elem_types, dest_elem_types)) {
  320. // TODO: This call recurses back into conversion. Switch to an iterative
  321. // approach.
  322. auto init_id =
  323. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  324. context, value_loc_id, value_id, src_type_id, literal_elems,
  325. inner_kind, target.init_id, dest_type_id, target.init_block, i, i);
  326. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  327. return SemIR::ErrorInst::SingletonInstId;
  328. }
  329. new_block.Set(i, init_id);
  330. }
  331. if (is_init) {
  332. target.init_block->InsertHere();
  333. return AddInst<SemIR::TupleInit>(context, value_loc_id,
  334. {.type_id = target.type_id,
  335. .elements_id = new_block.id(),
  336. .dest_id = target.init_id});
  337. } else {
  338. return AddInst<SemIR::TupleValue>(
  339. context, value_loc_id,
  340. {.type_id = target.type_id, .elements_id = new_block.id()});
  341. }
  342. }
  343. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  344. template <typename TargetAccessInstT>
  345. static auto ConvertStructToStructOrClass(
  346. Context& context, SemIR::StructType src_type, SemIR::StructType dest_type,
  347. SemIR::InstId value_id, ConversionTarget target,
  348. SemIR::InstId dest_vtable_id = SemIR::InstId::None) -> SemIR::InstId {
  349. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  350. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  351. constexpr bool ToClass =
  352. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  353. auto& sem_ir = context.sem_ir();
  354. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  355. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  356. bool dest_has_vptr = !dest_elem_fields.empty() &&
  357. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  358. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  359. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  360. auto value = sem_ir.insts().Get(value_id);
  361. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  362. // If we're initializing from a struct literal, we will use its elements
  363. // directly. Otherwise, materialize a temporary if needed and index into the
  364. // result.
  365. llvm::ArrayRef<SemIR::InstId> literal_elems;
  366. auto literal_elems_id = SemIR::InstBlockId::None;
  367. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  368. literal_elems_id = struct_literal->elements_id;
  369. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  370. } else {
  371. value_id = MaterializeIfInitializing(context, value_id);
  372. }
  373. // Check that the structs are the same size.
  374. // TODO: If not, include the name of the first source field that doesn't
  375. // exist in the destination or vice versa in the diagnostic.
  376. if (src_elem_fields.size() != dest_elem_fields_size) {
  377. if (target.diagnose) {
  378. CARBON_DIAGNOSTIC(
  379. StructInitElementCountMismatch, Error,
  380. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  381. "with {2} field{2:s}",
  382. Diagnostics::BoolAsSelect, Diagnostics::IntAsSelect,
  383. Diagnostics::IntAsSelect);
  384. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  385. ToClass, dest_elem_fields_size,
  386. src_elem_fields.size());
  387. }
  388. return SemIR::ErrorInst::SingletonInstId;
  389. }
  390. // Prepare to look up fields in the source by index.
  391. Map<SemIR::NameId, int32_t> src_field_indexes;
  392. if (src_type.fields_id != dest_type.fields_id) {
  393. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  394. auto result = src_field_indexes.Insert(field.name_id, i);
  395. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  396. }
  397. }
  398. // If we're forming an initializer, then we want an initializer for each
  399. // element. Otherwise, we want a value representation for each element.
  400. // Perform a final destination store if we're performing an in-place
  401. // initialization.
  402. bool is_init = target.is_initializer();
  403. ConversionTarget::Kind inner_kind =
  404. !is_init ? ConversionTarget::Value
  405. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  406. SemIR::InitRepr::InPlace
  407. ? ConversionTarget::FullInitializer
  408. : ConversionTarget::Initializer;
  409. // Initialize each element of the destination from the corresponding element
  410. // of the source.
  411. // TODO: Annotate diagnostics coming from here with the element index.
  412. auto new_block =
  413. literal_elems_id.has_value() && !dest_has_vptr
  414. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  415. : SemIR::CopyOnWriteInstBlock(
  416. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  417. dest_elem_fields.size()});
  418. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  419. if (dest_field.name_id == SemIR::NameId::Vptr) {
  420. if constexpr (!ToClass) {
  421. CARBON_FATAL("Only classes should have vptrs.");
  422. }
  423. target.init_block->InsertHere();
  424. auto dest_id =
  425. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  426. {.type_id = dest_field.type_id,
  427. .base_id = target.init_id,
  428. .index = SemIR::ElementIndex(i)});
  429. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  430. context, value_loc_id,
  431. {.type_id = dest_field.type_id, .vtable_id = dest_vtable_id});
  432. auto init_id =
  433. AddInst<SemIR::InitializeFrom>(context, value_loc_id,
  434. {.type_id = dest_field.type_id,
  435. .src_id = vtable_ptr_id,
  436. .dest_id = dest_id});
  437. new_block.Set(i, init_id);
  438. continue;
  439. }
  440. // Find the matching source field.
  441. auto src_field_index = i;
  442. if (src_type.fields_id != dest_type.fields_id) {
  443. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  444. src_field_index = lookup.value();
  445. } else {
  446. if (target.diagnose) {
  447. if (literal_elems_id.has_value()) {
  448. CARBON_DIAGNOSTIC(
  449. StructInitMissingFieldInLiteral, Error,
  450. "missing value for field `{0}` in struct initialization",
  451. SemIR::NameId);
  452. context.emitter().Emit(value_loc_id,
  453. StructInitMissingFieldInLiteral,
  454. dest_field.name_id);
  455. } else {
  456. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  457. "cannot convert from struct type {0} to {1}: "
  458. "missing field `{2}` in source type",
  459. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  460. context.emitter().Emit(value_loc_id,
  461. StructInitMissingFieldInConversion, value_id,
  462. target.type_id, dest_field.name_id);
  463. }
  464. }
  465. return SemIR::ErrorInst::SingletonInstId;
  466. }
  467. }
  468. auto src_field = src_elem_fields[src_field_index];
  469. // TODO: This call recurses back into conversion. Switch to an iterative
  470. // approach.
  471. auto init_id =
  472. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  473. context, value_loc_id, value_id, src_field.type_id, literal_elems,
  474. inner_kind, target.init_id, dest_field.type_id, target.init_block,
  475. src_field_index, src_field_index + dest_vptr_offset,
  476. dest_vtable_id);
  477. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  478. return SemIR::ErrorInst::SingletonInstId;
  479. }
  480. new_block.Set(i, init_id);
  481. }
  482. if (ToClass) {
  483. target.init_block->InsertHere();
  484. CARBON_CHECK(is_init,
  485. "Converting directly to a class value is not supported");
  486. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  487. {.type_id = target.type_id,
  488. .elements_id = new_block.id(),
  489. .dest_id = target.init_id});
  490. } else if (is_init) {
  491. target.init_block->InsertHere();
  492. return AddInst<SemIR::StructInit>(context, value_loc_id,
  493. {.type_id = target.type_id,
  494. .elements_id = new_block.id(),
  495. .dest_id = target.init_id});
  496. } else {
  497. return AddInst<SemIR::StructValue>(
  498. context, value_loc_id,
  499. {.type_id = target.type_id, .elements_id = new_block.id()});
  500. }
  501. }
  502. // Performs a conversion from a struct to a struct type. This function only
  503. // converts the type, and does not perform a final conversion to the requested
  504. // expression category.
  505. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  506. SemIR::StructType dest_type,
  507. SemIR::InstId value_id,
  508. ConversionTarget target) -> SemIR::InstId {
  509. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  510. context, src_type, dest_type, value_id, target);
  511. }
  512. // Performs a conversion from a struct to a class type. This function only
  513. // converts the type, and does not perform a final conversion to the requested
  514. // expression category.
  515. static auto ConvertStructToClass(
  516. Context& context, SemIR::StructType src_type, SemIR::ClassType dest_type,
  517. SemIR::InstId value_id, ConversionTarget target,
  518. SemIR::InstId dest_vtable_id = SemIR::InstId::None) -> SemIR::InstId {
  519. PendingBlock target_block(&context);
  520. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  521. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  522. auto object_repr_id =
  523. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  524. if (object_repr_id == SemIR::ErrorInst::SingletonTypeId) {
  525. return SemIR::ErrorInst::SingletonInstId;
  526. }
  527. auto dest_struct_type =
  528. context.types().GetAs<SemIR::StructType>(object_repr_id);
  529. // If we're trying to create a class value, form a temporary for the value to
  530. // point to.
  531. bool need_temporary = !target.is_initializer();
  532. if (need_temporary) {
  533. target.kind = ConversionTarget::Initializer;
  534. target.init_block = &target_block;
  535. target.init_id = target_block.AddInstWithCleanup<SemIR::TemporaryStorage>(
  536. context.insts().GetLocId(value_id), {.type_id = target.type_id});
  537. }
  538. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  539. context, src_type, dest_struct_type, value_id, target,
  540. dest_vtable_id.has_value() ? dest_vtable_id : dest_class_info.vtable_id);
  541. if (need_temporary) {
  542. target_block.InsertHere();
  543. result_id =
  544. AddInst<SemIR::Temporary>(context, context.insts().GetLocId(value_id),
  545. {.type_id = target.type_id,
  546. .storage_id = target.init_id,
  547. .init_id = result_id});
  548. }
  549. return result_id;
  550. }
  551. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  552. // in order from derived to base.
  553. using InheritancePath =
  554. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  555. // Computes the inheritance path from class `derived_id` to class `base_id`.
  556. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  557. static auto ComputeInheritancePath(Context& context, SemIRLoc loc,
  558. SemIR::TypeId derived_id,
  559. SemIR::TypeId base_id)
  560. -> std::optional<InheritancePath> {
  561. // We intend for NRVO to be applied to `result`. All `return` statements in
  562. // this function should `return result;`.
  563. std::optional<InheritancePath> result(std::in_place);
  564. if (!TryToCompleteType(context, derived_id, loc)) {
  565. // TODO: Should we give an error here? If we don't, and there is an
  566. // inheritance path when the class is defined, we may have a coherence
  567. // problem.
  568. result = std::nullopt;
  569. return result;
  570. }
  571. while (derived_id != base_id) {
  572. auto derived_class_type =
  573. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  574. if (!derived_class_type) {
  575. result = std::nullopt;
  576. break;
  577. }
  578. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  579. auto base_type_id = derived_class.GetBaseType(
  580. context.sem_ir(), derived_class_type->specific_id);
  581. if (!base_type_id.has_value()) {
  582. result = std::nullopt;
  583. break;
  584. }
  585. result->push_back({derived_class.base_id, base_type_id});
  586. derived_id = base_type_id;
  587. }
  588. return result;
  589. }
  590. // Performs a conversion from a derived class value or reference to a base class
  591. // value or reference.
  592. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  593. SemIR::InstId value_id,
  594. const InheritancePath& path) -> SemIR::InstId {
  595. // Materialize a temporary if necessary.
  596. value_id = ConvertToValueOrRefExpr(context, value_id);
  597. // Add a series of `.base` accesses.
  598. for (auto [base_id, base_type_id] : path) {
  599. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  600. value_id = AddInst<SemIR::ClassElementAccess>(context, loc_id,
  601. {.type_id = base_type_id,
  602. .base_id = value_id,
  603. .index = base_decl.index});
  604. }
  605. return value_id;
  606. }
  607. // Performs a conversion from a derived class pointer to a base class pointer.
  608. static auto ConvertDerivedPointerToBasePointer(
  609. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  610. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  611. const InheritancePath& path) -> SemIR::InstId {
  612. // Form `*p`.
  613. ptr_id = ConvertToValueExpr(context, ptr_id);
  614. auto ref_id = AddInst<SemIR::Deref>(
  615. context, loc_id,
  616. {.type_id =
  617. context.types().GetTypeIdForTypeInstId(src_ptr_type.pointee_id),
  618. .pointer_id = ptr_id});
  619. // Convert as a reference expression.
  620. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  621. // Take the address.
  622. return AddInst<SemIR::AddrOf>(
  623. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  624. }
  625. // Returns whether `category` is a valid expression category to produce as a
  626. // result of a conversion with kind `target_kind`, or at most needs a temporary
  627. // to be materialized.
  628. static auto IsValidExprCategoryForConversionTarget(
  629. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  630. switch (target_kind) {
  631. case ConversionTarget::Value:
  632. return category == SemIR::ExprCategory::Value;
  633. case ConversionTarget::ValueOrRef:
  634. case ConversionTarget::Discarded:
  635. return category == SemIR::ExprCategory::Value ||
  636. category == SemIR::ExprCategory::DurableRef ||
  637. category == SemIR::ExprCategory::EphemeralRef ||
  638. category == SemIR::ExprCategory::Initializing;
  639. case ConversionTarget::ExplicitAs:
  640. return true;
  641. case ConversionTarget::Initializer:
  642. case ConversionTarget::FullInitializer:
  643. return category == SemIR::ExprCategory::Initializing;
  644. }
  645. }
  646. // Determines whether the initialization representation of the type is a copy of
  647. // the value representation.
  648. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  649. SemIR::TypeId type_id) -> bool {
  650. // The initializing representation is a copy of the value representation if
  651. // they're both copies of the object representation.
  652. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  653. SemIR::ValueRepr::ForType(sem_ir, type_id)
  654. .IsCopyOfObjectRepr(sem_ir, type_id);
  655. }
  656. // Determines whether we can pull a value directly out of an initializing
  657. // expression of type `type_id` to initialize a target of type `type_id` and
  658. // kind `target_kind`.
  659. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  660. SemIR::TypeId type_id,
  661. ConversionTarget::Kind target_kind)
  662. -> bool {
  663. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  664. target_kind)) {
  665. // We don't want a value expression.
  666. return false;
  667. }
  668. // We can pull a value out of an initializing expression if it holds one.
  669. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  670. }
  671. // Returns the non-adapter type that is compatible with the specified type.
  672. static auto GetTransitiveAdaptedType(Context& context, SemIR::TypeId type_id)
  673. -> SemIR::TypeId {
  674. // If the type is an adapter, its object representation type is its compatible
  675. // non-adapter type.
  676. while (auto class_type =
  677. context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  678. auto& class_info = context.classes().Get(class_type->class_id);
  679. auto adapted_type_id =
  680. class_info.GetAdaptedType(context.sem_ir(), class_type->specific_id);
  681. if (!adapted_type_id.has_value()) {
  682. break;
  683. }
  684. type_id = adapted_type_id;
  685. }
  686. // Otherwise, the type itself is a non-adapter type.
  687. return type_id;
  688. }
  689. static auto DiagnoseConversionFailureToConstraintValue(
  690. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  691. SemIR::TypeId target_type_id) -> void {
  692. CARBON_DCHECK(target_type_id == SemIR::TypeType::SingletonTypeId ||
  693. context.types().Is<SemIR::FacetType>(target_type_id));
  694. auto type_of_expr_id = context.insts().Get(expr_id).type_id();
  695. CARBON_CHECK(context.types().IsFacetType(type_of_expr_id));
  696. // If the source type is/has a facet value, then we can include its
  697. // FacetType in the diagnostic to help explain what interfaces the
  698. // source type implements.
  699. auto facet_value_inst_id = SemIR::InstId::None;
  700. if (auto facet_access_type =
  701. context.insts().TryGetAs<SemIR::FacetAccessType>(expr_id)) {
  702. facet_value_inst_id = facet_access_type->facet_value_inst_id;
  703. } else if (context.types().Is<SemIR::FacetType>(type_of_expr_id)) {
  704. facet_value_inst_id = expr_id;
  705. }
  706. if (facet_value_inst_id.has_value()) {
  707. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  708. "cannot convert type {0} that implements {1} into type "
  709. "implementing {2}",
  710. InstIdAsType, TypeOfInstId, SemIR::TypeId);
  711. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  712. facet_value_inst_id, target_type_id);
  713. } else {
  714. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  715. "cannot convert type {0} into type implementing {1}",
  716. InstIdAsType, SemIR::TypeId);
  717. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  718. target_type_id);
  719. }
  720. }
  721. static auto PerformBuiltinConversion(
  722. Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  723. ConversionTarget target, SemIR::InstId vtable_id = SemIR::InstId::None)
  724. -> SemIR::InstId {
  725. auto& sem_ir = context.sem_ir();
  726. auto value = sem_ir.insts().Get(value_id);
  727. auto value_type_id = value.type_id();
  728. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  729. // Various forms of implicit conversion are supported as builtin conversions,
  730. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  731. // prelude. There are a few reasons we need to perform some of these
  732. // conversions as builtins:
  733. //
  734. // 1) Conversions from struct and tuple *literals* have special rules that
  735. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  736. // recurse into the elements of the literal before performing
  737. // initialization in order to avoid unnecessary conversions between
  738. // expression categories that would be performed by `ImplicitAs.Convert`.
  739. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  740. // the value of the facet, not only its type, and therefore cannot be
  741. // modeled by `ImplicitAs`.
  742. // 3) Some of these conversions are used while checking the library
  743. // definition of `ImplicitAs` itself or implementations of it.
  744. //
  745. // We also expect to see better performance by avoiding an `impl` lookup for
  746. // common conversions.
  747. //
  748. // TODO: We should provide a debugging flag to turn off as many of these
  749. // builtin conversions as we can so that we can test that they do the same
  750. // thing as the library implementations.
  751. //
  752. // The builtin conversions that correspond to `impl`s in the library all
  753. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  754. // being specialized in any of these cases.
  755. // If the value is already of the right kind and expression category, there's
  756. // nothing to do. Performing a conversion would decompose and rebuild tuples
  757. // and structs, so it's important that we bail out early in this case.
  758. if (value_type_id == target.type_id) {
  759. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  760. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  761. return value_id;
  762. }
  763. // If the source is an initializing expression, we may be able to pull a
  764. // value right out of it.
  765. if (value_cat == SemIR::ExprCategory::Initializing &&
  766. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  767. return AddInst<SemIR::ValueOfInitializer>(
  768. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  769. }
  770. // PerformBuiltinConversion converts each part of a tuple or struct, even
  771. // when the types are the same. This is not done for classes since they have
  772. // to define their conversions as part of their api.
  773. //
  774. // If a class adapts a tuple or struct, we convert each of its parts when
  775. // there's no other conversion going on (the source and target types are the
  776. // same). To do so, we have to insert a conversion of the value up to the
  777. // foundation and back down, and a conversion of the initializing object if
  778. // there is one.
  779. //
  780. // Implementation note: We do the conversion through a call to
  781. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  782. // extraneous `converted` semir instructions on the adapted types, and as a
  783. // shortcut to doing the explicit calls to walk the parts of the
  784. // tuple/struct which happens inside PerformBuiltinConversion().
  785. if (auto foundation_type_id =
  786. GetTransitiveAdaptedType(context, value_type_id);
  787. foundation_type_id != value_type_id &&
  788. (context.types().Is<SemIR::TupleType>(foundation_type_id) ||
  789. context.types().Is<SemIR::StructType>(foundation_type_id))) {
  790. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  791. context, loc_id,
  792. {.type_id = foundation_type_id, .source_id = value_id});
  793. auto foundation_init_id = target.init_id;
  794. if (foundation_init_id != SemIR::InstId::None) {
  795. foundation_init_id = target.init_block->AddInst<SemIR::AsCompatible>(
  796. loc_id,
  797. {.type_id = foundation_type_id, .source_id = target.init_id});
  798. }
  799. {
  800. // While the types are the same, the conversion can still fail if it
  801. // performs a copy while converting the value to another category, and
  802. // the type (or some part of it) is not copyable.
  803. Diagnostics::AnnotationScope annotate_diagnostics(
  804. &context.emitter(), [&](auto& builder) {
  805. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  806. builder.Note(value_id, InCopy, value_id);
  807. });
  808. foundation_value_id =
  809. PerformBuiltinConversion(context, loc_id, foundation_value_id,
  810. {.kind = target.kind,
  811. .type_id = foundation_type_id,
  812. .init_id = foundation_init_id,
  813. .init_block = target.init_block,
  814. .diagnose = target.diagnose});
  815. if (foundation_value_id == SemIR::ErrorInst::SingletonInstId) {
  816. return SemIR::ErrorInst::SingletonInstId;
  817. }
  818. }
  819. return AddInst<SemIR::AsCompatible>(
  820. context, loc_id,
  821. {.type_id = target.type_id, .source_id = foundation_value_id});
  822. }
  823. }
  824. // T explicitly converts to U if T is compatible with U.
  825. if (target.kind == ConversionTarget::Kind::ExplicitAs &&
  826. target.type_id != value_type_id) {
  827. auto target_foundation_id =
  828. GetTransitiveAdaptedType(context, target.type_id);
  829. auto value_foundation_id = GetTransitiveAdaptedType(context, value_type_id);
  830. if (target_foundation_id == value_foundation_id) {
  831. // For a struct or tuple literal, perform a category conversion if
  832. // necessary.
  833. if (SemIR::GetExprCategory(context.sem_ir(), value_id) ==
  834. SemIR::ExprCategory::Mixed) {
  835. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  836. {.kind = ConversionTarget::Value,
  837. .type_id = value_type_id,
  838. .diagnose = target.diagnose});
  839. }
  840. return AddInst<SemIR::AsCompatible>(
  841. context, loc_id, {.type_id = target.type_id, .source_id = value_id});
  842. }
  843. }
  844. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  845. // converts to Ui.
  846. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  847. if (auto src_tuple_type =
  848. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  849. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  850. value_id, target);
  851. }
  852. }
  853. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  854. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  855. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  856. // to Ui.
  857. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  858. if (auto src_struct_type =
  859. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  860. return ConvertStructToStruct(context, *src_struct_type,
  861. *target_struct_type, value_id, target);
  862. }
  863. }
  864. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  865. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  866. if (auto src_tuple_type =
  867. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  868. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  869. value_id, target);
  870. }
  871. }
  872. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  873. // if it converts to the struct type that is the class's representation type
  874. // (a struct with the same fields as the class, plus a base field where
  875. // relevant).
  876. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  877. if (auto src_struct_type =
  878. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  879. if (!context.classes()
  880. .Get(target_class_type->class_id)
  881. .adapt_id.has_value()) {
  882. return ConvertStructToClass(context, *src_struct_type,
  883. *target_class_type, value_id, target,
  884. vtable_id);
  885. }
  886. }
  887. // An expression of type T converts to U if T is a class derived from U.
  888. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  889. target.type_id);
  890. path && !path->empty()) {
  891. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  892. }
  893. }
  894. // A pointer T* converts to U* if T is a class derived from U.
  895. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  896. if (auto src_pointer_type =
  897. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  898. if (auto path =
  899. ComputeInheritancePath(context, loc_id,
  900. context.types().GetTypeIdForTypeInstId(
  901. src_pointer_type->pointee_id),
  902. context.types().GetTypeIdForTypeInstId(
  903. target_pointer_type->pointee_id));
  904. path && !path->empty()) {
  905. return ConvertDerivedPointerToBasePointer(
  906. context, loc_id, *src_pointer_type, target.type_id, value_id,
  907. *path);
  908. }
  909. }
  910. }
  911. if (target.type_id == SemIR::TypeType::SingletonTypeId) {
  912. // A tuple of types converts to type `type`.
  913. // TODO: This should apply even for non-literal tuples.
  914. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  915. llvm::SmallVector<SemIR::TypeId> type_ids;
  916. for (auto tuple_inst_id :
  917. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  918. // TODO: This call recurses back into conversion. Switch to an
  919. // iterative approach.
  920. type_ids.push_back(
  921. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose)
  922. .type_id);
  923. }
  924. auto tuple_type_id = GetTupleType(context, type_ids);
  925. return sem_ir.types().GetInstId(tuple_type_id);
  926. }
  927. // `{}` converts to `{} as type`.
  928. // TODO: This conversion should also be performed for a non-literal value
  929. // of type `{}`.
  930. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  931. struct_literal &&
  932. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  933. value_id = sem_ir.types().GetInstId(value_type_id);
  934. }
  935. // Facet type conversions: a value T of facet type F1 can be implicitly
  936. // converted to facet type F2 if T satisfies the requirements of F2.
  937. //
  938. // TODO: Support this conversion in general. For now we only support it in
  939. // the case where F1 is a facet type and F2 is `type`.
  940. // TODO: Support converting tuple and struct values to facet types,
  941. // combining the above conversions and this one in a single conversion.
  942. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  943. return AddInst<SemIR::FacetAccessType>(
  944. context, loc_id,
  945. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  946. }
  947. }
  948. if (target.type_id != value_type_id &&
  949. sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  950. (sem_ir.types().Is<SemIR::TypeType>(value_type_id) ||
  951. sem_ir.types().Is<SemIR::FacetType>(value_type_id))) {
  952. // The value is a type or facet value, so it has a constant value. We get
  953. // that to unwrap things like NameRef and get to the underlying type or
  954. // facet value instruction so that we can use `TryGetAs`.
  955. auto const_value_id = sem_ir.constant_values().GetConstantInstId(value_id);
  956. // TODO: Runtime facet values should be allowed to convert based on their
  957. // FacetTypes, but we assume constant values for impl lookup at the moment.
  958. if (!const_value_id.has_value()) {
  959. context.TODO(loc_id, "conversion of runtime facet value");
  960. const_value_id = SemIR::ErrorInst::SingletonInstId;
  961. }
  962. if (auto facet_access_type_inst =
  963. sem_ir.insts().TryGetAs<SemIR::FacetAccessType>(const_value_id)) {
  964. // Conversion from a `FacetAccessType` to a `FacetValue` of the target
  965. // `FacetType` if the instruction in the `FacetAccessType` is of a
  966. // `FacetType` that satisfies the requirements of the target `FacetType`.
  967. // If the `FacetType` exactly matches the target `FacetType` then we can
  968. // shortcut and use that value, and avoid impl lookup.
  969. auto facet_value_inst_id = facet_access_type_inst->facet_value_inst_id;
  970. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  971. return facet_value_inst_id;
  972. }
  973. }
  974. // Conversion from a facet value (which has type `FacetType`) or a type
  975. // value (which has type `TypeType`) to a facet value. We can do this if the
  976. // type satisfies the requirements of the target `FacetType`, as determined
  977. // by finding impl witnesses for the target FacetType.
  978. auto lookup_result = LookupImplWitness(
  979. context, loc_id, sem_ir.constant_values().Get(const_value_id),
  980. sem_ir.types().GetConstantId(target.type_id));
  981. if (lookup_result.has_value()) {
  982. if (lookup_result.has_error_value()) {
  983. return SemIR::ErrorInst::SingletonInstId;
  984. } else {
  985. // We bind the input value to the target `FacetType` with a
  986. // `FacetValue`, which requires an instruction of type `TypeType`. So if
  987. // we are converting from a facet value, we get its `type` via an extra
  988. // `FacetAccessType` instruction.
  989. auto type_inst_id = SemIR::InstId::None;
  990. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  991. type_inst_id =
  992. AddInst(context, loc_id,
  993. SemIR::FacetAccessType{
  994. .type_id = SemIR::TypeType::SingletonTypeId,
  995. .facet_value_inst_id = const_value_id,
  996. });
  997. } else {
  998. type_inst_id = const_value_id;
  999. }
  1000. return AddInst<SemIR::FacetValue>(
  1001. context, loc_id,
  1002. {.type_id = target.type_id,
  1003. .type_inst_id = type_inst_id,
  1004. .witnesses_block_id = lookup_result.inst_block_id()});
  1005. }
  1006. } else {
  1007. // If impl lookup fails, don't keep looking for another way to convert.
  1008. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1009. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1010. // the error add notes explaining failure.
  1011. if (target.diagnose) {
  1012. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1013. target.type_id);
  1014. }
  1015. return SemIR::ErrorInst::SingletonInstId;
  1016. }
  1017. }
  1018. // No builtin conversion applies.
  1019. return value_id;
  1020. }
  1021. // Given a value expression, form a corresponding initializer that copies from
  1022. // that value, if it is possible to do so.
  1023. static auto PerformCopy(Context& context, SemIR::InstId expr_id, bool diagnose)
  1024. -> SemIR::InstId {
  1025. auto expr = context.insts().Get(expr_id);
  1026. auto type_id = expr.type_id();
  1027. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  1028. return SemIR::ErrorInst::SingletonInstId;
  1029. }
  1030. if (InitReprIsCopyOfValueRepr(context.sem_ir(), type_id)) {
  1031. // For simple by-value types, no explicit action is required. Initializing
  1032. // from a value expression is treated as copying the value.
  1033. return expr_id;
  1034. }
  1035. // TODO: We don't yet have rules for whether and when a class type is
  1036. // copyable, or how to perform the copy.
  1037. if (diagnose) {
  1038. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1039. "cannot copy value of type {0}", TypeOfInstId);
  1040. context.emitter().Emit(expr_id, CopyOfUncopyableType, expr_id);
  1041. }
  1042. return SemIR::ErrorInst::SingletonInstId;
  1043. }
  1044. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1045. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1046. return Convert(
  1047. context, loc_id, action.inst_id,
  1048. {.kind = ConversionTarget::Value, .type_id = action.target_type_id});
  1049. }
  1050. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1051. ConversionTarget target, SemIR::InstId vtable_id)
  1052. -> SemIR::InstId {
  1053. auto& sem_ir = context.sem_ir();
  1054. auto orig_expr_id = expr_id;
  1055. // Start by making sure both sides are non-errors. If any part is an error,
  1056. // the result is an error and we shouldn't diagnose.
  1057. if (sem_ir.insts().Get(expr_id).type_id() ==
  1058. SemIR::ErrorInst::SingletonTypeId ||
  1059. target.type_id == SemIR::ErrorInst::SingletonTypeId) {
  1060. return SemIR::ErrorInst::SingletonInstId;
  1061. }
  1062. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  1063. // TODO: We currently encounter this for use of namespaces and functions.
  1064. // We should provide a better diagnostic for inappropriate use of
  1065. // namespace names, and allow use of functions as values.
  1066. if (target.diagnose) {
  1067. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1068. "expression cannot be used as a value");
  1069. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1070. }
  1071. return SemIR::ErrorInst::SingletonInstId;
  1072. }
  1073. // We can only perform initialization for complete, non-abstract types. Note
  1074. // that `RequireConcreteType` returns true for facet types, since their
  1075. // representation is fixed. This allows us to support using the `Self` of an
  1076. // interface inside its definition.
  1077. if (!RequireConcreteType(
  1078. context, target.type_id, loc_id,
  1079. [&] {
  1080. CARBON_CHECK(!target.is_initializer(),
  1081. "Initialization of incomplete types is expected to be "
  1082. "caught elsewhere.");
  1083. if (!target.diagnose) {
  1084. return context.emitter().BuildSuppressed();
  1085. }
  1086. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1087. "forming value of incomplete type {0}",
  1088. SemIR::TypeId);
  1089. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1090. "invalid use of incomplete type {0}",
  1091. SemIR::TypeId);
  1092. return context.emitter().Build(
  1093. loc_id,
  1094. target.kind == ConversionTarget::Value
  1095. ? IncompleteTypeInValueConversion
  1096. : IncompleteTypeInConversion,
  1097. target.type_id);
  1098. },
  1099. [&] {
  1100. if (!target.diagnose || !target.is_initializer()) {
  1101. return context.emitter().BuildSuppressed();
  1102. }
  1103. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1104. "initialization of abstract type {0}",
  1105. SemIR::TypeId);
  1106. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1107. target.type_id);
  1108. })) {
  1109. return SemIR::ErrorInst::SingletonInstId;
  1110. }
  1111. // Check whether any builtin conversion applies.
  1112. expr_id =
  1113. PerformBuiltinConversion(context, loc_id, expr_id, target, vtable_id);
  1114. if (expr_id == SemIR::ErrorInst::SingletonInstId) {
  1115. return expr_id;
  1116. }
  1117. // Defer the action if it's dependent. We do this now rather than before
  1118. // attempting any conversion so that we can still perform builtin conversions
  1119. // on dependent arguments. This matters for things like converting a
  1120. // `template T:! SomeInterface` to `type`, where it's important to form a
  1121. // `FacetAccessType` when checking the template. But when running the action
  1122. // later, we need to try builtin conversions again, because one may apply that
  1123. // didn't apply in the template definition.
  1124. // TODO: Support this for targets other than `Value`.
  1125. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1126. target.kind == ConversionTarget::Value &&
  1127. (OperandIsDependent(context, expr_id) ||
  1128. OperandIsDependent(context, target.type_id))) {
  1129. return AddDependentActionSplice(
  1130. context, loc_id,
  1131. SemIR::ConvertToValueAction{.type_id = SemIR::InstType::SingletonTypeId,
  1132. .inst_id = expr_id,
  1133. .target_type_id = target.type_id},
  1134. target.type_id);
  1135. }
  1136. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1137. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1138. SemIR::InstId interface_args[] = {
  1139. context.types().GetInstId(target.type_id)};
  1140. Operator op = {
  1141. .interface_name = target.kind == ConversionTarget::ExplicitAs
  1142. ? llvm::StringLiteral("As")
  1143. : llvm::StringLiteral("ImplicitAs"),
  1144. .interface_args_ref = interface_args,
  1145. .op_name = "Convert",
  1146. };
  1147. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1148. if (!target.diagnose) {
  1149. return context.emitter().BuildSuppressed();
  1150. }
  1151. if (target.type_id == SemIR::TypeType::SingletonTypeId ||
  1152. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1153. CARBON_DIAGNOSTIC(
  1154. ConversionFailureNonTypeToFacet, Error,
  1155. "cannot{0:| implicitly} convert non-type value of type {1} "
  1156. "{2:to|into type implementing} {3}{0: with `as`|}",
  1157. Diagnostics::BoolAsSelect, TypeOfInstId, Diagnostics::BoolAsSelect,
  1158. SemIR::TypeId);
  1159. return context.emitter().Build(
  1160. loc_id, ConversionFailureNonTypeToFacet,
  1161. target.kind == ConversionTarget::ExplicitAs, expr_id,
  1162. target.type_id == SemIR::TypeType::SingletonTypeId, target.type_id);
  1163. } else {
  1164. CARBON_DIAGNOSTIC(ConversionFailure, Error,
  1165. "cannot{0:| implicitly} convert expression of type "
  1166. "{1} to {2}{0: with `as`|}",
  1167. Diagnostics::BoolAsSelect, TypeOfInstId,
  1168. SemIR::TypeId);
  1169. return context.emitter().Build(
  1170. loc_id, ConversionFailure,
  1171. target.kind == ConversionTarget::ExplicitAs, expr_id,
  1172. target.type_id);
  1173. }
  1174. });
  1175. // Pull a value directly out of the initializer if possible and wanted.
  1176. if (expr_id != SemIR::ErrorInst::SingletonInstId &&
  1177. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1178. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1179. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1180. }
  1181. }
  1182. // Track that we performed a type conversion, if we did so.
  1183. if (orig_expr_id != expr_id) {
  1184. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1185. {.type_id = target.type_id,
  1186. .original_id = orig_expr_id,
  1187. .result_id = expr_id});
  1188. }
  1189. // For `as`, don't perform any value category conversions. In particular, an
  1190. // identity conversion shouldn't change the expression category.
  1191. if (target.kind == ConversionTarget::ExplicitAs) {
  1192. return expr_id;
  1193. }
  1194. // Now perform any necessary value category conversions.
  1195. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  1196. case SemIR::ExprCategory::NotExpr:
  1197. case SemIR::ExprCategory::Mixed:
  1198. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1199. sem_ir.insts().Get(expr_id));
  1200. case SemIR::ExprCategory::Error:
  1201. return SemIR::ErrorInst::SingletonInstId;
  1202. case SemIR::ExprCategory::Initializing:
  1203. if (target.is_initializer()) {
  1204. if (orig_expr_id == expr_id) {
  1205. // Don't fill in the return slot if we created the expression through
  1206. // a conversion. In that case, we will have created it with the
  1207. // target already set.
  1208. // TODO: Find a better way to track whether we need to do this.
  1209. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  1210. *target.init_block);
  1211. }
  1212. break;
  1213. }
  1214. // Commit to using a temporary for this initializing expression.
  1215. // TODO: Don't create a temporary if the initializing representation
  1216. // is already a value representation.
  1217. expr_id = FinalizeTemporary(context, expr_id,
  1218. target.kind == ConversionTarget::Discarded);
  1219. // We now have an ephemeral reference.
  1220. [[fallthrough]];
  1221. case SemIR::ExprCategory::DurableRef:
  1222. case SemIR::ExprCategory::EphemeralRef:
  1223. // If a reference expression is an acceptable result, we're done.
  1224. if (target.kind == ConversionTarget::ValueOrRef ||
  1225. target.kind == ConversionTarget::Discarded) {
  1226. break;
  1227. }
  1228. // If we have a reference and don't want one, form a value binding.
  1229. // TODO: Support types with custom value representations.
  1230. expr_id = AddInst<SemIR::BindValue>(
  1231. context, context.insts().GetLocId(expr_id),
  1232. {.type_id = target.type_id, .value_id = expr_id});
  1233. // We now have a value expression.
  1234. [[fallthrough]];
  1235. case SemIR::ExprCategory::Value:
  1236. // When initializing from a value, perform a copy.
  1237. if (target.is_initializer()) {
  1238. expr_id = PerformCopy(context, expr_id, target.diagnose);
  1239. }
  1240. break;
  1241. }
  1242. // Perform a final destination store, if necessary.
  1243. if (target.kind == ConversionTarget::FullInitializer) {
  1244. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1245. init_rep.kind == SemIR::InitRepr::ByCopy) {
  1246. target.init_block->InsertHere();
  1247. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1248. {.type_id = target.type_id,
  1249. .src_id = expr_id,
  1250. .dest_id = target.init_id});
  1251. }
  1252. }
  1253. return expr_id;
  1254. }
  1255. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1256. SemIR::InstId value_id) -> SemIR::InstId {
  1257. PendingBlock target_block(&context);
  1258. return Convert(context, loc_id, value_id,
  1259. {.kind = ConversionTarget::Initializer,
  1260. .type_id = context.insts().Get(target_id).type_id(),
  1261. .init_id = target_id,
  1262. .init_block = &target_block});
  1263. }
  1264. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1265. -> SemIR::InstId {
  1266. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1267. {.kind = ConversionTarget::Value,
  1268. .type_id = context.insts().Get(expr_id).type_id()});
  1269. }
  1270. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1271. -> SemIR::InstId {
  1272. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1273. {.kind = ConversionTarget::ValueOrRef,
  1274. .type_id = context.insts().Get(expr_id).type_id()});
  1275. }
  1276. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1277. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1278. -> SemIR::InstId {
  1279. return Convert(context, loc_id, expr_id,
  1280. {.kind = ConversionTarget::Value, .type_id = type_id});
  1281. }
  1282. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1283. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1284. -> SemIR::InstId {
  1285. return Convert(context, loc_id, expr_id,
  1286. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1287. }
  1288. // Like ConvertToValueOfType but failure to convert does not result in
  1289. // diagnostics. An ErrorInst instruction is still returned on failure.
  1290. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1291. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1292. -> SemIR::InstId {
  1293. return Convert(
  1294. context, loc_id, expr_id,
  1295. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1296. }
  1297. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1298. SemIR::InstId value_id) -> SemIR::InstId {
  1299. return ConvertToValueOfType(
  1300. context, loc_id, value_id,
  1301. GetSingletonType(context, SemIR::BoolType::SingletonInstId));
  1302. }
  1303. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1304. SemIR::InstId value_id, SemIR::TypeId type_id)
  1305. -> SemIR::InstId {
  1306. return Convert(context, as_node, value_id,
  1307. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  1308. }
  1309. // TODO: Consider moving this to pattern_match.h.
  1310. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1311. SemIR::InstId self_id,
  1312. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1313. SemIR::InstId return_slot_arg_id,
  1314. const SemIR::Function& callee,
  1315. SemIR::SpecificId callee_specific_id)
  1316. -> SemIR::InstBlockId {
  1317. // The callee reference can be invalidated by conversions, so ensure all reads
  1318. // from it are done before conversion calls.
  1319. auto callee_decl_id = callee.latest_decl_id();
  1320. auto param_patterns =
  1321. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1322. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1323. // The caller should have ensured this callee has the right arity.
  1324. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1325. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1326. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1327. "missing object argument in method call");
  1328. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1329. context.emitter()
  1330. .Build(call_loc_id, MissingObjectInMethodCall)
  1331. .Note(callee_decl_id, InCallToFunction)
  1332. .Emit();
  1333. self_id = SemIR::ErrorInst::SingletonInstId;
  1334. }
  1335. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1336. callee.param_patterns_id, return_slot_pattern_id,
  1337. self_id, arg_refs, return_slot_arg_id);
  1338. }
  1339. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1340. bool diagnose) -> TypeExpr {
  1341. auto type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1342. SemIR::TypeType::SingletonTypeId);
  1343. if (type_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1344. return {.inst_id = type_inst_id,
  1345. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1346. }
  1347. auto type_const_id = context.constant_values().Get(type_inst_id);
  1348. if (!type_const_id.is_constant()) {
  1349. if (diagnose) {
  1350. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1351. "cannot evaluate type expression");
  1352. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1353. }
  1354. return {.inst_id = SemIR::ErrorInst::SingletonInstId,
  1355. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1356. }
  1357. return {.inst_id = type_inst_id,
  1358. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1359. }
  1360. } // namespace Carbon::Check
  1361. // NOLINTEND(misc-no-recursion)