convert.cpp 66 KB

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