convert.cpp 66 KB

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