convert.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044
  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/core_identifier.h"
  16. #include "toolchain/check/diagnostic_helpers.h"
  17. #include "toolchain/check/eval.h"
  18. #include "toolchain/check/impl_lookup.h"
  19. #include "toolchain/check/import_ref.h"
  20. #include "toolchain/check/inst.h"
  21. #include "toolchain/check/operator.h"
  22. #include "toolchain/check/pattern_match.h"
  23. #include "toolchain/check/type.h"
  24. #include "toolchain/check/type_completion.h"
  25. #include "toolchain/diagnostics/format_providers.h"
  26. #include "toolchain/sem_ir/copy_on_write_block.h"
  27. #include "toolchain/sem_ir/expr_info.h"
  28. #include "toolchain/sem_ir/file.h"
  29. #include "toolchain/sem_ir/generic.h"
  30. #include "toolchain/sem_ir/ids.h"
  31. #include "toolchain/sem_ir/inst.h"
  32. #include "toolchain/sem_ir/type.h"
  33. #include "toolchain/sem_ir/type_info.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. // TODO: This contains a lot of recursion. Consider removing it in order to
  36. // prevent accidents.
  37. // NOLINTBEGIN(misc-no-recursion)
  38. namespace Carbon::Check {
  39. // Marks the initializer `init_id` as initializing `target.storage_id`.
  40. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  41. ConversionTarget& target) -> void {
  42. if (!target.storage_id.has_value()) {
  43. return;
  44. }
  45. CARBON_CHECK(target.is_initializer());
  46. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  47. if (return_slot_arg_id.has_value()) {
  48. // Replace the temporary in the return slot with a reference to our target.
  49. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  50. SemIR::TemporaryStorage::Kind,
  51. "Return slot for initializer does not contain a temporary; "
  52. "initialized multiple times? Have {0}",
  53. sem_ir.insts().Get(return_slot_arg_id));
  54. target.storage_id = target.storage_access_block->MergeReplacing(
  55. return_slot_arg_id, target.storage_id);
  56. }
  57. }
  58. // For a value or initializing expression using a copy value representation,
  59. // copy the value into a temporary object.
  60. static auto CopyValueToTemporary(Context& context, SemIR::InstId init_id)
  61. -> SemIR::InstId {
  62. // TODO: Consider using `None` to mean that we immediately materialize and
  63. // initialize a temporary, rather than two separate instructions.
  64. auto init = context.insts().Get(init_id);
  65. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  66. context, SemIR::LocId(init_id), {.type_id = init.type_id()});
  67. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(init_id),
  68. {.type_id = init.type_id(),
  69. .storage_id = temporary_id,
  70. .init_id = init_id});
  71. }
  72. // Commits to using a temporary to store the result of the initializing
  73. // expression described by `init_id`, and returns the location of the
  74. // temporary. If `discarded` is `true`, the result is discarded, and no
  75. // temporary will be created if possible; if no temporary is created, the
  76. // return value will be `SemIR::InstId::None`.
  77. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  78. bool discarded) -> SemIR::InstId {
  79. auto& sem_ir = context.sem_ir();
  80. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  81. if (return_slot_arg_id.has_value()) {
  82. // The return slot should already have a materialized temporary in it.
  83. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  84. SemIR::TemporaryStorage::Kind,
  85. "Return slot for initializer does not contain a temporary; "
  86. "initialized multiple times? Have {0}",
  87. sem_ir.insts().Get(return_slot_arg_id));
  88. auto init = sem_ir.insts().Get(init_id);
  89. return AddInstWithCleanup<SemIR::Temporary>(
  90. context, SemIR::LocId(init_id),
  91. {.type_id = init.type_id(),
  92. .storage_id = return_slot_arg_id,
  93. .init_id = init_id});
  94. }
  95. if (discarded) {
  96. // Don't invent a temporary that we're going to discard.
  97. return SemIR::InstId::None;
  98. }
  99. // The initializer has no return slot, but we want to produce a temporary
  100. // object. Materialize one now.
  101. return CopyValueToTemporary(context, init_id);
  102. }
  103. // Materialize a temporary to hold the result of the given expression if it is
  104. // an initializing expression.
  105. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  106. -> SemIR::InstId {
  107. if (GetExprCategory(context.sem_ir(), expr_id) ==
  108. SemIR::ExprCategory::Initializing) {
  109. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  110. }
  111. return expr_id;
  112. }
  113. // Helper to allow `MakeElementAccessInst` to call `AddInst` with either a
  114. // `PendingBlock` or `Context` (defined in `inst.h`).
  115. template <typename AccessInstT>
  116. static auto AddInst(PendingBlock& block, SemIR::LocId loc_id, AccessInstT inst)
  117. -> SemIR::InstId {
  118. return block.AddInst<AccessInstT>(loc_id, inst);
  119. }
  120. // Creates and adds an instruction to perform element access into an aggregate.
  121. template <typename AccessInstT, typename InstBlockT>
  122. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  123. SemIR::InstId aggregate_id,
  124. SemIR::TypeId elem_type_id, InstBlockT& block,
  125. size_t i) -> SemIR::InstId {
  126. if (!aggregate_id.has_value()) {
  127. return SemIR::InstId::None;
  128. }
  129. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  130. // TODO: Add a new instruction kind for indexing an array at a constant
  131. // index so that we don't need an integer literal instruction here, and
  132. // remove this special case.
  133. auto index_id = block.template AddInst<SemIR::IntValue>(
  134. loc_id, {.type_id = GetSingletonType(context,
  135. SemIR::IntLiteralType::TypeInstId),
  136. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  137. return AddInst<AccessInstT>(block, loc_id,
  138. {elem_type_id, aggregate_id, index_id});
  139. } else {
  140. return AddInst<AccessInstT>(
  141. block, loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  142. }
  143. }
  144. // Get the conversion target kind to use when initializing an element of an
  145. // aggregate.
  146. static auto GetAggregateElementConversionTargetKind(SemIR::File& sem_ir,
  147. ConversionTarget target)
  148. -> ConversionTarget::Kind {
  149. // If we're forming an initializer, then we want an initializer for each
  150. // element.
  151. if (target.is_initializer()) {
  152. // Perform a final destination store if we're performing an in-place
  153. // initialization.
  154. auto init_repr = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  155. CARBON_CHECK(init_repr.kind != SemIR::InitRepr::Dependent,
  156. "Aggregate should not have dependent init kind");
  157. if (init_repr.kind == SemIR::InitRepr::InPlace) {
  158. return ConversionTarget::FullInitializer;
  159. }
  160. return ConversionTarget::Initializer;
  161. }
  162. // Otherwise, we want a value representation for each element.
  163. return ConversionTarget::Value;
  164. }
  165. // Converts an element of one aggregate so that it can be used as an element of
  166. // another aggregate.
  167. //
  168. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  169. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  170. // kind of instruction used to access the source element.
  171. //
  172. // For the target: `kind` is the kind of conversion or initialization,
  173. // `target_elem_type` is the element type. For initialization, `target_id` is
  174. // the destination, `target_block` is a pending block for target location
  175. // calculations that will be spliced as the return slot of the initializer if
  176. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  177. // kind of instruction used to access the destination element.
  178. template <typename SourceAccessInstT, typename TargetAccessInstT>
  179. static auto ConvertAggregateElement(
  180. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  181. SemIR::TypeInstId src_elem_type_inst,
  182. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  183. ConversionTarget::Kind kind, SemIR::InstId target_id,
  184. SemIR::TypeInstId target_elem_type_inst, PendingBlock* target_block,
  185. size_t src_field_index, size_t target_field_index,
  186. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  187. auto src_elem_type =
  188. context.types().GetTypeIdForTypeInstId(src_elem_type_inst);
  189. auto target_elem_type =
  190. context.types().GetTypeIdForTypeInstId(target_elem_type_inst);
  191. // Compute the location of the source element. This goes into the current code
  192. // block, not into the target block.
  193. // TODO: Ideally we would discard this instruction if it's unused.
  194. auto src_elem_id = !src_literal_elems.empty()
  195. ? src_literal_elems[src_field_index]
  196. : MakeElementAccessInst<SourceAccessInstT>(
  197. context, loc_id, src_id, src_elem_type, context,
  198. src_field_index);
  199. // If we're performing a conversion rather than an initialization, we won't
  200. // have or need a target.
  201. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  202. if (!target.is_initializer()) {
  203. return Convert(context, loc_id, src_elem_id, target);
  204. }
  205. // Compute the location of the target element and initialize it.
  206. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  207. target.storage_access_block = target_block;
  208. target.storage_id = MakeElementAccessInst<TargetAccessInstT>(
  209. context, loc_id, target_id, target_elem_type, *target_block,
  210. target_field_index);
  211. return Convert(context, loc_id, src_elem_id, target, vtable_class_type);
  212. }
  213. // Performs a conversion from a tuple to an array type. This function only
  214. // converts the type, and does not perform a final conversion to the requested
  215. // expression category.
  216. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  217. SemIR::ArrayType array_type,
  218. SemIR::InstId value_id, ConversionTarget target)
  219. -> SemIR::InstId {
  220. auto& sem_ir = context.sem_ir();
  221. auto tuple_elem_types = sem_ir.inst_blocks().Get(tuple_type.type_elements_id);
  222. auto value = sem_ir.insts().Get(value_id);
  223. SemIR::LocId value_loc_id(value_id);
  224. // If we're initializing from a tuple literal, we will use its elements
  225. // directly. Otherwise, materialize a temporary if needed and index into the
  226. // result.
  227. llvm::ArrayRef<SemIR::InstId> literal_elems;
  228. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  229. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  230. } else {
  231. value_id = MaterializeIfInitializing(context, value_id);
  232. }
  233. // Check that the tuple is the right size.
  234. std::optional<uint64_t> array_bound =
  235. sem_ir.GetArrayBoundValue(array_type.bound_id);
  236. if (!array_bound) {
  237. // TODO: Should this fall back to using `ImplicitAs`?
  238. if (target.diagnose) {
  239. CARBON_DIAGNOSTIC(ArrayInitDependentBound, Error,
  240. "cannot initialize array with dependent bound from a "
  241. "list of initializers");
  242. context.emitter().Emit(value_loc_id, ArrayInitDependentBound);
  243. }
  244. return SemIR::ErrorInst::InstId;
  245. }
  246. if (tuple_elem_types.size() != array_bound) {
  247. if (target.diagnose) {
  248. CARBON_DIAGNOSTIC(ArrayInitFromLiteralArgCountMismatch, Error,
  249. "cannot initialize array of {0} element{0:s} from {1} "
  250. "initializer{1:s}",
  251. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  252. CARBON_DIAGNOSTIC(
  253. ArrayInitFromExprArgCountMismatch, Error,
  254. "cannot initialize array of {0} element{0:s} from tuple "
  255. "with {1} element{1:s}",
  256. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  257. context.emitter().Emit(value_loc_id,
  258. literal_elems.empty()
  259. ? ArrayInitFromExprArgCountMismatch
  260. : ArrayInitFromLiteralArgCountMismatch,
  261. *array_bound, tuple_elem_types.size());
  262. }
  263. return SemIR::ErrorInst::InstId;
  264. }
  265. PendingBlock target_block_storage(&context);
  266. PendingBlock* target_block = target.storage_access_block
  267. ? target.storage_access_block
  268. : &target_block_storage;
  269. // Arrays are always initialized in-place. Allocate a temporary as the
  270. // destination for the array initialization if we weren't given one.
  271. SemIR::InstId return_slot_arg_id = target.storage_id;
  272. if (!target.storage_id.has_value()) {
  273. return_slot_arg_id = target_block->AddInst<SemIR::TemporaryStorage>(
  274. value_loc_id, {.type_id = target.type_id});
  275. }
  276. // Initialize each element of the array from the corresponding element of the
  277. // tuple.
  278. // TODO: Annotate diagnostics coming from here with the array element index,
  279. // if initializing from a tuple literal.
  280. llvm::SmallVector<SemIR::InstId> inits;
  281. inits.reserve(*array_bound + 1);
  282. for (auto [i, src_type_inst_id] : llvm::enumerate(
  283. context.types().GetBlockAsTypeInstIds(tuple_elem_types))) {
  284. // TODO: This call recurses back into conversion. Switch to an iterative
  285. // approach.
  286. auto init_id =
  287. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  288. context, value_loc_id, value_id, src_type_inst_id, literal_elems,
  289. ConversionTarget::FullInitializer, return_slot_arg_id,
  290. array_type.element_type_inst_id, target_block, i, i);
  291. if (init_id == SemIR::ErrorInst::InstId) {
  292. return SemIR::ErrorInst::InstId;
  293. }
  294. inits.push_back(init_id);
  295. }
  296. // Flush the temporary here if we didn't insert it earlier, so we can add a
  297. // reference to the return slot.
  298. target_block->InsertHere();
  299. return AddInst<SemIR::ArrayInit>(context, value_loc_id,
  300. {.type_id = target.type_id,
  301. .inits_id = sem_ir.inst_blocks().Add(inits),
  302. .dest_id = return_slot_arg_id});
  303. }
  304. // Performs a conversion from a tuple to a tuple type. This function only
  305. // converts the type, and does not perform a final conversion to the requested
  306. // expression category.
  307. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  308. SemIR::TupleType dest_type,
  309. SemIR::InstId value_id, ConversionTarget target)
  310. -> SemIR::InstId {
  311. auto& sem_ir = context.sem_ir();
  312. auto src_elem_types = sem_ir.inst_blocks().Get(src_type.type_elements_id);
  313. auto dest_elem_types = sem_ir.inst_blocks().Get(dest_type.type_elements_id);
  314. auto value = sem_ir.insts().Get(value_id);
  315. SemIR::LocId value_loc_id(value_id);
  316. // If we're initializing from a tuple literal, we will use its elements
  317. // directly. Otherwise, materialize a temporary if needed and index into the
  318. // result.
  319. llvm::ArrayRef<SemIR::InstId> literal_elems;
  320. auto literal_elems_id = SemIR::InstBlockId::None;
  321. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  322. literal_elems_id = tuple_literal->elements_id;
  323. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  324. } else {
  325. value_id = MaterializeIfInitializing(context, value_id);
  326. }
  327. // Check that the tuples are the same size.
  328. if (src_elem_types.size() != dest_elem_types.size()) {
  329. if (target.diagnose) {
  330. CARBON_DIAGNOSTIC(
  331. TupleInitElementCountMismatch, Error,
  332. "cannot initialize tuple of {0} element{0:s} from tuple "
  333. "with {1} element{1:s}",
  334. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  335. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  336. dest_elem_types.size(), src_elem_types.size());
  337. }
  338. return SemIR::ErrorInst::InstId;
  339. }
  340. ConversionTarget::Kind inner_kind =
  341. GetAggregateElementConversionTargetKind(sem_ir, target);
  342. // Initialize each element of the destination from the corresponding element
  343. // of the source.
  344. // TODO: Annotate diagnostics coming from here with the element index.
  345. auto new_block =
  346. literal_elems_id.has_value()
  347. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  348. : SemIR::CopyOnWriteInstBlock(
  349. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  350. src_elem_types.size()});
  351. for (auto [i, src_type_inst_id, dest_type_inst_id] : llvm::enumerate(
  352. context.types().GetBlockAsTypeInstIds(src_elem_types),
  353. context.types().GetBlockAsTypeInstIds(dest_elem_types))) {
  354. // TODO: This call recurses back into conversion. Switch to an iterative
  355. // approach.
  356. auto init_id =
  357. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  358. context, value_loc_id, value_id, src_type_inst_id, literal_elems,
  359. inner_kind, target.storage_id, dest_type_inst_id,
  360. target.storage_access_block, i, i);
  361. if (init_id == SemIR::ErrorInst::InstId) {
  362. return SemIR::ErrorInst::InstId;
  363. }
  364. new_block.Set(i, init_id);
  365. }
  366. if (target.is_initializer()) {
  367. target.storage_access_block->InsertHere();
  368. return AddInst<SemIR::TupleInit>(context, value_loc_id,
  369. {.type_id = target.type_id,
  370. .elements_id = new_block.id(),
  371. .dest_id = target.storage_id});
  372. } else {
  373. return AddInst<SemIR::TupleValue>(
  374. context, value_loc_id,
  375. {.type_id = target.type_id, .elements_id = new_block.id()});
  376. }
  377. }
  378. // Converts a tuple of elements that are convertible to `type` into a `type`
  379. // that is a tuple of types.
  380. static auto ConvertTupleToType(Context& context, SemIR::LocId loc_id,
  381. SemIR::InstId value_id,
  382. SemIR::TypeId value_type_id,
  383. ConversionTarget target) -> SemIR::TypeInstId {
  384. auto value_const_id = context.constant_values().Get(value_id);
  385. if (!value_const_id.is_constant()) {
  386. // Types are constants. The input value must have a constant value to
  387. // convert.
  388. return SemIR::TypeInstId::None;
  389. }
  390. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  391. auto value_const_inst_id =
  392. context.constant_values().GetInstId(value_const_id);
  393. if (auto tuple_value =
  394. context.insts().TryGetAs<SemIR::TupleValue>(value_const_inst_id)) {
  395. for (auto tuple_inst_id :
  396. context.inst_blocks().Get(tuple_value->elements_id)) {
  397. // TODO: This call recurses back into conversion. Switch to an
  398. // iterative approach.
  399. type_inst_ids.push_back(
  400. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose).inst_id);
  401. }
  402. } else {
  403. // A value of type TupleType that isn't a TupleValue must be a symbolic
  404. // binding.
  405. CARBON_CHECK(
  406. context.insts().Is<SemIR::SymbolicBinding>(value_const_inst_id));
  407. // Form a TupleAccess for each element in the symbolic value, which is then
  408. // converted to a `type` or diagnosed as an error.
  409. auto tuple_type = context.types().GetAs<SemIR::TupleType>(value_type_id);
  410. auto type_elements = context.types().GetBlockAsTypeIds(
  411. context.inst_blocks().Get(tuple_type.type_elements_id));
  412. for (auto [i, type_id] : llvm::enumerate(type_elements)) {
  413. auto access_inst_id =
  414. GetOrAddInst<SemIR::TupleAccess>(context, loc_id,
  415. {.type_id = type_id,
  416. .tuple_id = value_id,
  417. .index = SemIR::ElementIndex(i)});
  418. // TODO: This call recurses back into conversion. Switch to an
  419. // iterative approach.
  420. type_inst_ids.push_back(
  421. ExprAsType(context, loc_id, access_inst_id, target.diagnose).inst_id);
  422. }
  423. }
  424. // TODO: Should we add this as an instruction? It will contain
  425. // references to local InstIds.
  426. auto tuple_type_id = GetTupleType(context, type_inst_ids);
  427. return context.types().GetInstId(tuple_type_id);
  428. }
  429. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  430. template <typename TargetAccessInstT>
  431. static auto ConvertStructToStructOrClass(
  432. Context& context, SemIR::StructType src_type, SemIR::StructType dest_type,
  433. SemIR::InstId value_id, ConversionTarget target,
  434. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  435. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  436. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  437. constexpr bool ToClass =
  438. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  439. auto& sem_ir = context.sem_ir();
  440. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  441. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  442. bool dest_has_vptr = !dest_elem_fields.empty() &&
  443. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  444. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  445. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  446. auto value = sem_ir.insts().Get(value_id);
  447. SemIR::LocId value_loc_id(value_id);
  448. // If we're initializing from a struct literal, we will use its elements
  449. // directly. Otherwise, materialize a temporary if needed and index into the
  450. // result.
  451. llvm::ArrayRef<SemIR::InstId> literal_elems;
  452. auto literal_elems_id = SemIR::InstBlockId::None;
  453. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  454. literal_elems_id = struct_literal->elements_id;
  455. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  456. } else {
  457. value_id = MaterializeIfInitializing(context, value_id);
  458. }
  459. // Check that the structs are the same size.
  460. // TODO: If not, include the name of the first source field that doesn't
  461. // exist in the destination or vice versa in the diagnostic.
  462. if (src_elem_fields.size() != dest_elem_fields_size) {
  463. if (target.diagnose) {
  464. CARBON_DIAGNOSTIC(
  465. StructInitElementCountMismatch, Error,
  466. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  467. "with {2} field{2:s}",
  468. Diagnostics::BoolAsSelect, Diagnostics::IntAsSelect,
  469. Diagnostics::IntAsSelect);
  470. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  471. ToClass, dest_elem_fields_size,
  472. src_elem_fields.size());
  473. }
  474. return SemIR::ErrorInst::InstId;
  475. }
  476. // Prepare to look up fields in the source by index.
  477. Map<SemIR::NameId, int32_t> src_field_indexes;
  478. if (src_type.fields_id != dest_type.fields_id) {
  479. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  480. auto result = src_field_indexes.Insert(field.name_id, i);
  481. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  482. }
  483. }
  484. ConversionTarget::Kind inner_kind =
  485. GetAggregateElementConversionTargetKind(sem_ir, target);
  486. // Initialize each element of the destination from the corresponding element
  487. // of the source.
  488. // TODO: Annotate diagnostics coming from here with the element index.
  489. auto new_block =
  490. literal_elems_id.has_value() && !dest_has_vptr
  491. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  492. : SemIR::CopyOnWriteInstBlock(
  493. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  494. dest_elem_fields.size()});
  495. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  496. if (dest_field.name_id == SemIR::NameId::Vptr) {
  497. if constexpr (!ToClass) {
  498. CARBON_FATAL("Only classes should have vptrs.");
  499. }
  500. target.storage_access_block->InsertHere();
  501. auto vptr_type_id =
  502. context.types().GetTypeIdForTypeInstId(dest_field.type_inst_id);
  503. auto dest_id =
  504. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  505. {.type_id = vptr_type_id,
  506. .base_id = target.storage_id,
  507. .index = SemIR::ElementIndex(i)});
  508. auto vtable_decl_id =
  509. context.classes().Get(vtable_class_type->class_id).vtable_decl_id;
  510. LoadImportRef(context, vtable_decl_id);
  511. auto canonical_vtable_decl_id =
  512. context.constant_values().GetConstantInstId(vtable_decl_id);
  513. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  514. context, value_loc_id,
  515. {.type_id = GetPointerType(context, SemIR::VtableType::TypeInstId),
  516. .vtable_id = context.insts()
  517. .GetAs<SemIR::VtableDecl>(canonical_vtable_decl_id)
  518. .vtable_id,
  519. .specific_id = vtable_class_type->specific_id});
  520. auto init_id = AddInst<SemIR::InitializeFrom>(context, value_loc_id,
  521. {.type_id = vptr_type_id,
  522. .src_id = vtable_ptr_id,
  523. .dest_id = dest_id});
  524. new_block.Set(i, init_id);
  525. continue;
  526. }
  527. // Find the matching source field.
  528. auto src_field_index = i;
  529. if (src_type.fields_id != dest_type.fields_id) {
  530. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  531. src_field_index = lookup.value();
  532. } else {
  533. if (target.diagnose) {
  534. if (literal_elems_id.has_value()) {
  535. CARBON_DIAGNOSTIC(
  536. StructInitMissingFieldInLiteral, Error,
  537. "missing value for field `{0}` in struct initialization",
  538. SemIR::NameId);
  539. context.emitter().Emit(value_loc_id,
  540. StructInitMissingFieldInLiteral,
  541. dest_field.name_id);
  542. } else {
  543. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  544. "cannot convert from struct type {0} to {1}: "
  545. "missing field `{2}` in source type",
  546. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  547. context.emitter().Emit(value_loc_id,
  548. StructInitMissingFieldInConversion, value_id,
  549. target.type_id, dest_field.name_id);
  550. }
  551. }
  552. return SemIR::ErrorInst::InstId;
  553. }
  554. }
  555. auto src_field = src_elem_fields[src_field_index];
  556. // TODO: This call recurses back into conversion. Switch to an iterative
  557. // approach.
  558. auto init_id =
  559. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  560. context, value_loc_id, value_id, src_field.type_inst_id,
  561. literal_elems, inner_kind, target.storage_id,
  562. dest_field.type_inst_id, target.storage_access_block,
  563. src_field_index, src_field_index + dest_vptr_offset,
  564. vtable_class_type);
  565. if (init_id == SemIR::ErrorInst::InstId) {
  566. return SemIR::ErrorInst::InstId;
  567. }
  568. new_block.Set(i, init_id);
  569. }
  570. bool is_init = target.is_initializer();
  571. if (ToClass) {
  572. target.storage_access_block->InsertHere();
  573. CARBON_CHECK(is_init,
  574. "Converting directly to a class value is not supported");
  575. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  576. {.type_id = target.type_id,
  577. .elements_id = new_block.id(),
  578. .dest_id = target.storage_id});
  579. } else if (is_init) {
  580. target.storage_access_block->InsertHere();
  581. return AddInst<SemIR::StructInit>(context, value_loc_id,
  582. {.type_id = target.type_id,
  583. .elements_id = new_block.id(),
  584. .dest_id = target.storage_id});
  585. } else {
  586. return AddInst<SemIR::StructValue>(
  587. context, value_loc_id,
  588. {.type_id = target.type_id, .elements_id = new_block.id()});
  589. }
  590. }
  591. // Performs a conversion from a struct to a struct type. This function only
  592. // converts the type, and does not perform a final conversion to the requested
  593. // expression category.
  594. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  595. SemIR::StructType dest_type,
  596. SemIR::InstId value_id,
  597. ConversionTarget target) -> SemIR::InstId {
  598. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  599. context, src_type, dest_type, value_id, target);
  600. }
  601. // Performs a conversion from a struct to a class type. This function only
  602. // converts the type, and does not perform a final conversion to the requested
  603. // expression category.
  604. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  605. SemIR::ClassType dest_type,
  606. SemIR::InstId value_id,
  607. ConversionTarget target,
  608. SemIR::ClassType* vtable_class_type)
  609. -> SemIR::InstId {
  610. PendingBlock target_block(&context);
  611. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  612. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  613. auto object_repr_id =
  614. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  615. if (object_repr_id == SemIR::ErrorInst::TypeId) {
  616. return SemIR::ErrorInst::InstId;
  617. }
  618. if (context.types().Is<SemIR::CustomLayoutType>(object_repr_id)) {
  619. // Builtin conversion does not apply.
  620. return value_id;
  621. }
  622. auto dest_struct_type =
  623. context.types().GetAs<SemIR::StructType>(object_repr_id);
  624. // If we're trying to create a class value, form a temporary for the value to
  625. // point to.
  626. bool need_temporary = !target.is_initializer();
  627. if (need_temporary) {
  628. target.kind = ConversionTarget::Initializer;
  629. target.storage_access_block = &target_block;
  630. target.storage_id = target_block.AddInst<SemIR::TemporaryStorage>(
  631. SemIR::LocId(value_id), {.type_id = target.type_id});
  632. }
  633. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  634. context, src_type, dest_struct_type, value_id, target,
  635. vtable_class_type ? vtable_class_type : &dest_type);
  636. if (need_temporary) {
  637. target_block.InsertHere();
  638. result_id =
  639. AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(value_id),
  640. {.type_id = target.type_id,
  641. .storage_id = target.storage_id,
  642. .init_id = result_id});
  643. }
  644. return result_id;
  645. }
  646. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  647. // in order from derived to base.
  648. using InheritancePath =
  649. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  650. // Computes the inheritance path from class `derived_id` to class `base_id`.
  651. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  652. static auto ComputeInheritancePath(Context& context, SemIR::LocId loc_id,
  653. SemIR::TypeId derived_id,
  654. SemIR::TypeId base_id)
  655. -> std::optional<InheritancePath> {
  656. // We intend for NRVO to be applied to `result`. All `return` statements in
  657. // this function should `return result;`.
  658. std::optional<InheritancePath> result(std::in_place);
  659. if (!TryToCompleteType(context, derived_id, loc_id)) {
  660. // TODO: Should we give an error here? If we don't, and there is an
  661. // inheritance path when the class is defined, we may have a coherence
  662. // problem.
  663. result = std::nullopt;
  664. return result;
  665. }
  666. while (derived_id != base_id) {
  667. auto derived_class_type =
  668. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  669. if (!derived_class_type) {
  670. result = std::nullopt;
  671. break;
  672. }
  673. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  674. auto base_type_id = derived_class.GetBaseType(
  675. context.sem_ir(), derived_class_type->specific_id);
  676. if (!base_type_id.has_value()) {
  677. result = std::nullopt;
  678. break;
  679. }
  680. result->push_back({derived_class.base_id, base_type_id});
  681. derived_id = base_type_id;
  682. }
  683. return result;
  684. }
  685. // Performs a conversion from a derived class value or reference to a base class
  686. // value or reference.
  687. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  688. SemIR::InstId value_id,
  689. const InheritancePath& path) -> SemIR::InstId {
  690. // Materialize a temporary if necessary.
  691. value_id = ConvertToValueOrRefExpr(context, value_id);
  692. // Preserve type qualifiers.
  693. auto quals = context.types()
  694. .GetUnqualifiedTypeAndQualifiers(
  695. context.insts().Get(value_id).type_id())
  696. .second;
  697. // Add a series of `.base` accesses.
  698. for (auto [base_id, base_type_id] : path) {
  699. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  700. value_id = AddInst<SemIR::ClassElementAccess>(
  701. context, loc_id,
  702. {.type_id = GetQualifiedType(context, base_type_id, quals),
  703. .base_id = value_id,
  704. .index = base_decl.index});
  705. }
  706. return value_id;
  707. }
  708. // Performs a conversion from a derived class pointer to a base class pointer.
  709. static auto ConvertDerivedPointerToBasePointer(
  710. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  711. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  712. const InheritancePath& path) -> SemIR::InstId {
  713. auto pointee_type_id =
  714. context.types().GetTypeIdForTypeInstId(src_ptr_type.pointee_id);
  715. // Form `*p`.
  716. ptr_id = ConvertToValueExpr(context, ptr_id);
  717. auto ref_id = AddInst<SemIR::Deref>(
  718. context, loc_id, {.type_id = pointee_type_id, .pointer_id = ptr_id});
  719. // Convert as a reference expression.
  720. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  721. // Take the address.
  722. return AddInst<SemIR::AddrOf>(
  723. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  724. }
  725. // Returns whether `category` is a valid expression category to produce as a
  726. // result of a conversion with kind `target_kind`.
  727. static auto IsValidExprCategoryForConversionTarget(
  728. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  729. switch (target_kind) {
  730. case ConversionTarget::Value:
  731. return category == SemIR::ExprCategory::Value;
  732. case ConversionTarget::ValueOrRef:
  733. return category == SemIR::ExprCategory::Value ||
  734. category == SemIR::ExprCategory::DurableRef ||
  735. category == SemIR::ExprCategory::EphemeralRef;
  736. case ConversionTarget::Discarded:
  737. return category == SemIR::ExprCategory::Value ||
  738. category == SemIR::ExprCategory::DurableRef ||
  739. category == SemIR::ExprCategory::EphemeralRef ||
  740. category == SemIR::ExprCategory::Initializing;
  741. case ConversionTarget::RefParam:
  742. case ConversionTarget::UnmarkedRefParam:
  743. return category == SemIR::ExprCategory::DurableRef ||
  744. category == SemIR::ExprCategory::EphemeralRef ||
  745. category == SemIR::ExprCategory::Initializing;
  746. case ConversionTarget::DurableRef:
  747. return category == SemIR::ExprCategory::DurableRef;
  748. case ConversionTarget::CppThunkRef:
  749. return category == SemIR::ExprCategory::EphemeralRef;
  750. case ConversionTarget::ExplicitAs:
  751. case ConversionTarget::ExplicitUnsafeAs:
  752. return true;
  753. case ConversionTarget::Initializer:
  754. case ConversionTarget::FullInitializer:
  755. return category == SemIR::ExprCategory::Initializing;
  756. }
  757. }
  758. // Determines whether the initialization representation of the type is a copy of
  759. // the value representation.
  760. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  761. SemIR::TypeId type_id) -> bool {
  762. // The initializing representation is a copy of the value representation if
  763. // they're both copies of the object representation.
  764. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  765. SemIR::ValueRepr::ForType(sem_ir, type_id)
  766. .IsCopyOfObjectRepr(sem_ir, type_id);
  767. }
  768. // Determines whether we can pull a value directly out of an initializing
  769. // expression of type `type_id` to initialize a target of type `type_id` and
  770. // kind `target_kind`.
  771. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  772. SemIR::TypeId type_id,
  773. ConversionTarget::Kind target_kind)
  774. -> bool {
  775. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  776. target_kind)) {
  777. // We don't want a value expression.
  778. return false;
  779. }
  780. // We can pull a value out of an initializing expression if it holds one.
  781. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  782. }
  783. // Determine whether the given set of qualifiers can be added by a conversion
  784. // of an expression of the given category.
  785. static auto CanAddQualifiers(SemIR::TypeQualifiers quals,
  786. SemIR::ExprCategory cat) -> bool {
  787. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  788. !SemIR::IsRefCategory(cat)) {
  789. // `MaybeUnformed(T)` may have a different value representation or
  790. // initializing representation from `T`, so only allow it to be added for a
  791. // reference expression.
  792. // TODO: We should allow converting an initializing expression of type `T`
  793. // to `MaybeUnformed(T)`. `PerformBuiltinConversion` will need to generate
  794. // an `InPlaceInit` instruction when needed.
  795. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  796. return false;
  797. }
  798. // `const` and `partial` can always be added.
  799. return true;
  800. }
  801. // Determine whether the given set of qualifiers can be removed by a conversion
  802. // of an expression of the given category.
  803. static auto CanRemoveQualifiers(SemIR::TypeQualifiers quals,
  804. SemIR::ExprCategory cat,
  805. ConversionTarget::Kind kind) -> bool {
  806. bool allow_unsafe = kind == ConversionTarget::ExplicitUnsafeAs;
  807. if (quals.HasAnyOf(SemIR::TypeQualifiers::Const) && !allow_unsafe &&
  808. SemIR::IsRefCategory(cat) &&
  809. IsValidExprCategoryForConversionTarget(cat, kind)) {
  810. // Removing `const` is an unsafe conversion for a reference expression. But
  811. // it's OK if we will be converting to a different category as part of this
  812. // overall conversion anyway.
  813. return false;
  814. }
  815. if (quals.HasAnyOf(SemIR::TypeQualifiers::Partial) &&
  816. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  817. // TODO: Allow removing `partial` for initializing expressions as a safe
  818. // conversion. `PerformBuiltinConversion` will need to initialize the vptr
  819. // as part of the conversion.
  820. return false;
  821. }
  822. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  823. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  824. // As an unsafe conversion, `MaybeUnformed` can be removed from a value or
  825. // reference expression.
  826. return false;
  827. }
  828. return true;
  829. }
  830. static auto DiagnoseConversionFailureToConstraintValue(
  831. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  832. SemIR::TypeId target_type_id) -> void {
  833. CARBON_CHECK(context.types().IsFacetType(target_type_id));
  834. // If the source type is/has a facet value (converted with `as type` or
  835. // otherwise), then we can include its `FacetType` in the diagnostic to help
  836. // explain what interfaces the source type implements.
  837. auto const_expr_id = GetCanonicalFacetOrTypeValue(context, expr_id);
  838. auto const_expr_type_id = context.insts().Get(const_expr_id).type_id();
  839. if (context.types().Is<SemIR::FacetType>(const_expr_type_id)) {
  840. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  841. "cannot convert type {0} that implements {1} into type "
  842. "implementing {2}",
  843. InstIdAsType, SemIR::TypeId, SemIR::TypeId);
  844. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  845. const_expr_type_id, target_type_id);
  846. } else {
  847. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  848. "cannot convert type {0} into type implementing {1}",
  849. InstIdAsType, SemIR::TypeId);
  850. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  851. target_type_id);
  852. }
  853. }
  854. static auto PerformBuiltinConversion(
  855. Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  856. ConversionTarget target, SemIR::ClassType* vtable_class_type = nullptr)
  857. -> SemIR::InstId {
  858. auto& sem_ir = context.sem_ir();
  859. auto value = sem_ir.insts().Get(value_id);
  860. auto value_type_id = value.type_id();
  861. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  862. // Various forms of implicit conversion are supported as builtin conversions,
  863. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  864. // prelude. There are a few reasons we need to perform some of these
  865. // conversions as builtins:
  866. //
  867. // 1) Conversions from struct and tuple *literals* have special rules that
  868. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  869. // recurse into the elements of the literal before performing
  870. // initialization in order to avoid unnecessary conversions between
  871. // expression categories that would be performed by `ImplicitAs.Convert`.
  872. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  873. // the value of the facet, not only its type, and therefore cannot be
  874. // modeled by `ImplicitAs`.
  875. // 3) Some of these conversions are used while checking the library
  876. // definition of `ImplicitAs` itself or implementations of it.
  877. //
  878. // We also expect to see better performance by avoiding an `impl` lookup for
  879. // common conversions.
  880. //
  881. // TODO: We should provide a debugging flag to turn off as many of these
  882. // builtin conversions as we can so that we can test that they do the same
  883. // thing as the library implementations.
  884. //
  885. // The builtin conversions that correspond to `impl`s in the library all
  886. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  887. // being specialized in any of these cases.
  888. // If the value is already of the right kind and expression category, there's
  889. // nothing to do. Performing a conversion would decompose and rebuild tuples
  890. // and structs, so it's important that we bail out early in this case.
  891. if (value_type_id == target.type_id) {
  892. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  893. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  894. return value_id;
  895. }
  896. // If the source is an initializing expression, we may be able to pull a
  897. // value right out of it.
  898. if (value_cat == SemIR::ExprCategory::Initializing &&
  899. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  900. return AddInst<SemIR::ValueOfInitializer>(
  901. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  902. }
  903. // Materialization is handled as part of the enclosing conversion.
  904. if (value_cat == SemIR::ExprCategory::Initializing &&
  905. target.kind == ConversionTarget::ValueOrRef) {
  906. return value_id;
  907. }
  908. // PerformBuiltinConversion converts each part of a tuple or struct, even
  909. // when the types are the same. This is not done for classes since they have
  910. // to define their conversions as part of their api.
  911. //
  912. // If a class adapts a tuple or struct, we convert each of its parts when
  913. // there's no other conversion going on (the source and target types are the
  914. // same). To do so, we have to insert a conversion of the value up to the
  915. // foundation and back down, and a conversion of the initializing object if
  916. // there is one.
  917. //
  918. // Implementation note: We do the conversion through a call to
  919. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  920. // extraneous `converted` semir instructions on the adapted types, and as a
  921. // shortcut to doing the explicit calls to walk the parts of the
  922. // tuple/struct which happens inside PerformBuiltinConversion().
  923. if (auto foundation_type_id =
  924. context.types().GetTransitiveAdaptedType(value_type_id);
  925. foundation_type_id != value_type_id &&
  926. context.types().IsOneOf<SemIR::StructType, SemIR::TupleType>(
  927. foundation_type_id)) {
  928. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  929. context, loc_id,
  930. {.type_id = foundation_type_id, .source_id = value_id});
  931. auto foundation_init_id = target.storage_id;
  932. if (foundation_init_id != SemIR::InstId::None) {
  933. foundation_init_id =
  934. target.storage_access_block->AddInst<SemIR::AsCompatible>(
  935. loc_id, {.type_id = foundation_type_id,
  936. .source_id = target.storage_id});
  937. }
  938. {
  939. // While the types are the same, the conversion can still fail if it
  940. // performs a copy while converting the value to another category, and
  941. // the type (or some part of it) is not copyable.
  942. Diagnostics::AnnotationScope annotate_diagnostics(
  943. &context.emitter(), [&](auto& builder) {
  944. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  945. builder.Note(value_id, InCopy, value_id);
  946. });
  947. foundation_value_id = PerformBuiltinConversion(
  948. context, loc_id, foundation_value_id,
  949. {.kind = target.kind,
  950. .type_id = foundation_type_id,
  951. .storage_id = foundation_init_id,
  952. .storage_access_block = target.storage_access_block,
  953. .diagnose = target.diagnose});
  954. if (foundation_value_id == SemIR::ErrorInst::InstId) {
  955. return SemIR::ErrorInst::InstId;
  956. }
  957. }
  958. return AddInst<SemIR::AsCompatible>(
  959. context, loc_id,
  960. {.type_id = target.type_id, .source_id = foundation_value_id});
  961. }
  962. }
  963. // T implicitly converts to U if T and U are the same ignoring qualifiers, and
  964. // we're allowed to remove / add any qualifiers that differ. Similarly, T
  965. // explicitly converts to U if T is compatible with U, and we're allowed to
  966. // remove / add any qualifiers that differ.
  967. if (target.type_id != value_type_id) {
  968. auto [target_foundation_id, target_quals] =
  969. target.is_explicit_as()
  970. ? context.types().GetTransitiveUnqualifiedAdaptedType(
  971. target.type_id)
  972. : context.types().GetUnqualifiedTypeAndQualifiers(target.type_id);
  973. auto [value_foundation_id, value_quals] =
  974. target.is_explicit_as()
  975. ? context.types().GetTransitiveUnqualifiedAdaptedType(value_type_id)
  976. : context.types().GetUnqualifiedTypeAndQualifiers(value_type_id);
  977. if (target_foundation_id == value_foundation_id) {
  978. auto category = SemIR::GetExprCategory(context.sem_ir(), value_id);
  979. auto added_quals = target_quals & ~value_quals;
  980. auto removed_quals = value_quals & ~target_quals;
  981. if (CanAddQualifiers(added_quals, category) &&
  982. CanRemoveQualifiers(removed_quals, category, target.kind)) {
  983. // For a struct or tuple literal, perform a category conversion if
  984. // necessary.
  985. if (category == SemIR::ExprCategory::Mixed) {
  986. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  987. {.kind = ConversionTarget::Value,
  988. .type_id = value_type_id,
  989. .diagnose = target.diagnose});
  990. }
  991. // `MaybeUnformed(T)` might have a pointer value representation when `T`
  992. // does not, so convert as needed when removing `MaybeUnformed`.
  993. bool need_value_binding = false;
  994. if ((removed_quals & SemIR::TypeQualifiers::MaybeUnformed) !=
  995. SemIR::TypeQualifiers::None &&
  996. category == SemIR::ExprCategory::Value) {
  997. auto value_rep =
  998. SemIR::ValueRepr::ForType(context.sem_ir(), value_type_id);
  999. auto unformed_value_rep =
  1000. SemIR::ValueRepr::ForType(context.sem_ir(), target.type_id);
  1001. if (value_rep.kind != unformed_value_rep.kind) {
  1002. CARBON_CHECK(unformed_value_rep.kind == SemIR::ValueRepr::Pointer);
  1003. value_id = AddInst<SemIR::ValueAsRef>(
  1004. context, loc_id,
  1005. {.type_id = value_type_id, .value_id = value_id});
  1006. need_value_binding = true;
  1007. }
  1008. }
  1009. value_id = AddInst<SemIR::AsCompatible>(
  1010. context, loc_id,
  1011. {.type_id = target.type_id, .source_id = value_id});
  1012. if (need_value_binding) {
  1013. value_id = AddInst<SemIR::AcquireValue>(
  1014. context, loc_id,
  1015. {.type_id = target.type_id, .value_id = value_id});
  1016. }
  1017. return value_id;
  1018. } else {
  1019. // TODO: Produce a custom diagnostic explaining that we can't perform
  1020. // this conversion due to the change in qualifiers and/or the expression
  1021. // category.
  1022. }
  1023. }
  1024. }
  1025. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  1026. // converts to Ui.
  1027. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  1028. if (auto src_tuple_type =
  1029. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1030. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  1031. value_id, target);
  1032. }
  1033. }
  1034. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  1035. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  1036. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  1037. // to Ui.
  1038. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  1039. if (auto src_struct_type =
  1040. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1041. return ConvertStructToStruct(context, *src_struct_type,
  1042. *target_struct_type, value_id, target);
  1043. }
  1044. }
  1045. // No other conversions apply when the source and destination types are the
  1046. // same.
  1047. if (value_type_id == target.type_id) {
  1048. return value_id;
  1049. }
  1050. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  1051. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  1052. if (auto src_tuple_type =
  1053. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1054. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  1055. value_id, target);
  1056. }
  1057. }
  1058. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  1059. // if it converts to the struct type that is the class's representation type
  1060. // (a struct with the same fields as the class, plus a base field where
  1061. // relevant).
  1062. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  1063. if (auto src_struct_type =
  1064. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1065. if (!context.classes()
  1066. .Get(target_class_type->class_id)
  1067. .adapt_id.has_value()) {
  1068. return ConvertStructToClass(context, *src_struct_type,
  1069. *target_class_type, value_id, target,
  1070. vtable_class_type);
  1071. }
  1072. }
  1073. // An expression of type T converts to U if T is a class derived from U.
  1074. //
  1075. // TODO: Combine this with the qualifiers and adapter conversion logic above
  1076. // to allow qualifiers and inheritance conversions to be performed together.
  1077. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  1078. target.type_id);
  1079. path && !path->empty()) {
  1080. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  1081. }
  1082. }
  1083. // A pointer T* converts to [qualified] U* if T is the same as U, or is a
  1084. // class derived from U.
  1085. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  1086. if (auto src_pointer_type =
  1087. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  1088. auto target_pointee_id = context.types().GetTypeIdForTypeInstId(
  1089. target_pointer_type->pointee_id);
  1090. auto src_pointee_id =
  1091. context.types().GetTypeIdForTypeInstId(src_pointer_type->pointee_id);
  1092. // Try to complete the pointee types so that we can walk through adapters
  1093. // to their adapted types.
  1094. TryToCompleteType(context, target_pointee_id, loc_id);
  1095. TryToCompleteType(context, src_pointee_id, loc_id);
  1096. auto [unqual_target_pointee_type_id, target_quals] =
  1097. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(target_pointee_id);
  1098. auto [unqual_src_pointee_type_id, src_quals] =
  1099. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(src_pointee_id);
  1100. // If the qualifiers are incompatible, we can't perform a conversion,
  1101. // except with `unsafe as`.
  1102. if ((src_quals & ~target_quals) != SemIR::TypeQualifiers::None &&
  1103. target.kind != ConversionTarget::ExplicitUnsafeAs) {
  1104. // TODO: Consider producing a custom diagnostic here for a cast that
  1105. // discards constness.
  1106. return value_id;
  1107. }
  1108. if (unqual_target_pointee_type_id != unqual_src_pointee_type_id) {
  1109. // If there's an inheritance path from target to source, this is a
  1110. // derived to base conversion.
  1111. if (auto path = ComputeInheritancePath(context, loc_id,
  1112. unqual_src_pointee_type_id,
  1113. unqual_target_pointee_type_id);
  1114. path && !path->empty()) {
  1115. value_id = ConvertDerivedPointerToBasePointer(
  1116. context, loc_id, *src_pointer_type, target.type_id, value_id,
  1117. *path);
  1118. } else {
  1119. // No conversion was possible.
  1120. return value_id;
  1121. }
  1122. }
  1123. // Perform a compatible conversion to add any new qualifiers.
  1124. if (src_quals != target_quals) {
  1125. return AddInst<SemIR::AsCompatible>(
  1126. context, loc_id,
  1127. {.type_id = target.type_id, .source_id = value_id});
  1128. }
  1129. return value_id;
  1130. }
  1131. }
  1132. if (sem_ir.types().IsFacetType(target.type_id)) {
  1133. auto type_value_id = SemIR::TypeInstId::None;
  1134. // A tuple of types converts to type `type`.
  1135. if (sem_ir.types().Is<SemIR::TupleType>(value_type_id)) {
  1136. type_value_id =
  1137. ConvertTupleToType(context, loc_id, value_id, value_type_id, target);
  1138. }
  1139. // `{}` converts to `{} as type`.
  1140. if (auto struct_type =
  1141. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1142. if (struct_type->fields_id == SemIR::StructTypeFieldsId::Empty) {
  1143. type_value_id = sem_ir.types().GetInstId(value_type_id);
  1144. }
  1145. }
  1146. if (type_value_id != SemIR::InstId::None) {
  1147. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1148. // Use the converted `TypeType` value for converting to a facet.
  1149. value_id = type_value_id;
  1150. value_type_id = SemIR::TypeType::TypeId;
  1151. } else {
  1152. // We wanted a `TypeType`, and we've done that.
  1153. return type_value_id;
  1154. }
  1155. }
  1156. }
  1157. // FacetType converts to Type by wrapping the facet value in
  1158. // FacetAccessType.
  1159. if (target.type_id == SemIR::TypeType::TypeId &&
  1160. sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1161. return AddInst<SemIR::FacetAccessType>(
  1162. context, loc_id,
  1163. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  1164. }
  1165. // Type values can convert to facet values, and facet values can convert to
  1166. // other facet values, as long as they satisfy the required interfaces of the
  1167. // target `FacetType`.
  1168. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  1169. sem_ir.types().IsOneOf<SemIR::TypeType, SemIR::FacetType>(
  1170. value_type_id)) {
  1171. // TODO: Runtime facet values should be allowed to convert based on their
  1172. // FacetTypes, but we assume constant values for impl lookup at the moment.
  1173. if (!context.constant_values().Get(value_id).is_constant()) {
  1174. context.TODO(loc_id, "conversion of runtime facet value");
  1175. return SemIR::ErrorInst::InstId;
  1176. }
  1177. // Get the canonical type for which we want to attach a new set of witnesses
  1178. // to match the requirements of the target FacetType.
  1179. auto type_inst_id = SemIR::TypeInstId::None;
  1180. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1181. type_inst_id = AddTypeInst<SemIR::FacetAccessType>(
  1182. context, loc_id,
  1183. {.type_id = SemIR::TypeType::TypeId,
  1184. .facet_value_inst_id = value_id});
  1185. } else {
  1186. type_inst_id = context.types().GetAsTypeInstId(value_id);
  1187. // Shortcut for lossless round trips through a FacetAccessType (which
  1188. // evaluates to SymbolicBindingType when wrapping a symbolic binding) when
  1189. // converting back to the type of the original symbolic binding facet
  1190. // value.
  1191. //
  1192. // In the case where the FacetAccessType wraps a SymbolicBinding with the
  1193. // exact facet type that we are converting to, the resulting FacetValue
  1194. // would evaluate back to the original SymbolicBinding as its canonical
  1195. // form. We can skip past the whole impl lookup step then and do that
  1196. // here.
  1197. //
  1198. // TODO: This instruction is going to become a `SymbolicBindingType`, so
  1199. // we'll need to handle that instead.
  1200. auto facet_value_inst_id =
  1201. GetCanonicalFacetOrTypeValue(context, type_inst_id);
  1202. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  1203. return facet_value_inst_id;
  1204. }
  1205. }
  1206. // Conversion from a facet value (which has type `FacetType`) or a type
  1207. // value (which has type `TypeType`) to a facet value. We can do this if the
  1208. // type satisfies the requirements of the target `FacetType`, as determined
  1209. // by finding impl witnesses for the target FacetType.
  1210. auto lookup_result = LookupImplWitness(
  1211. context, loc_id, sem_ir.constant_values().Get(type_inst_id),
  1212. sem_ir.types().GetConstantId(target.type_id));
  1213. if (lookup_result.has_value()) {
  1214. if (lookup_result.has_error_value()) {
  1215. return SemIR::ErrorInst::InstId;
  1216. } else {
  1217. // Note that `FacetValue`'s type is the same `FacetType` that was used
  1218. // to construct the set of witnesses, ie. the query to
  1219. // `LookupImplWitness()`. This ensures that the witnesses are in the
  1220. // same order as the `required_interfaces()` in the `FacetValue`'s type.
  1221. return AddInst<SemIR::FacetValue>(
  1222. context, loc_id,
  1223. {.type_id = target.type_id,
  1224. .type_inst_id = type_inst_id,
  1225. .witnesses_block_id = lookup_result.inst_block_id()});
  1226. }
  1227. } else {
  1228. // If impl lookup fails, don't keep looking for another way to convert.
  1229. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1230. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1231. // the error add notes explaining failure.
  1232. if (target.diagnose) {
  1233. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1234. target.type_id);
  1235. }
  1236. return SemIR::ErrorInst::InstId;
  1237. }
  1238. }
  1239. // No builtin conversion applies.
  1240. return value_id;
  1241. }
  1242. // Determine whether this is a C++ enum type.
  1243. // TODO: This should be removed once we can properly add a `Copy` impl for C++
  1244. // enum types.
  1245. static auto IsCppEnum(Context& context, SemIR::TypeId type_id) -> bool {
  1246. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  1247. if (!class_type) {
  1248. return false;
  1249. }
  1250. // A C++-imported class type that is an adapter is an enum.
  1251. auto& class_info = context.classes().Get(class_type->class_id);
  1252. return class_info.adapt_id.has_value() &&
  1253. context.name_scopes().Get(class_info.scope_id).is_cpp_scope();
  1254. }
  1255. // Given a value expression, form a corresponding initializer that copies from
  1256. // that value to the specified target, if it is possible to do so.
  1257. static auto PerformCopy(Context& context, SemIR::InstId expr_id,
  1258. ConversionTarget& target) -> SemIR::InstId {
  1259. // TODO: We don't have a mechanism yet to generate `Copy` impls for each enum
  1260. // type imported from C++. For now we fake it by providing a direct copy.
  1261. auto type_id = context.insts().Get(expr_id).type_id();
  1262. if (IsCppEnum(context, type_id)) {
  1263. return expr_id;
  1264. }
  1265. auto copy_id = BuildUnaryOperator(
  1266. context, SemIR::LocId(expr_id), {.interface_name = CoreIdentifier::Copy},
  1267. expr_id, [&] {
  1268. if (!target.diagnose) {
  1269. return context.emitter().BuildSuppressed();
  1270. }
  1271. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1272. "cannot copy value of type {0}", TypeOfInstId);
  1273. return context.emitter().Build(expr_id, CopyOfUncopyableType, expr_id);
  1274. });
  1275. MarkInitializerFor(context.sem_ir(), copy_id, target);
  1276. return copy_id;
  1277. }
  1278. // Convert a value expression so that it can be used to initialize a C++ thunk
  1279. // parameter.
  1280. static auto ConvertValueForCppThunkRef(Context& context, SemIR::InstId expr_id)
  1281. -> SemIR::InstId {
  1282. auto expr = context.insts().Get(expr_id);
  1283. // If the expression has a pointer value representation, extract that and use
  1284. // it directly.
  1285. if (SemIR::ValueRepr::ForType(context.sem_ir(), expr.type_id()).kind ==
  1286. SemIR::ValueRepr::Pointer) {
  1287. return AddInst<SemIR::ValueAsRef>(
  1288. context, SemIR::LocId(expr_id),
  1289. {.type_id = expr.type_id(), .value_id = expr_id});
  1290. }
  1291. // Otherwise, we need a temporary to pass as the thunk argument. Create a copy
  1292. // and initialize a temporary from it.
  1293. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  1294. context, SemIR::LocId(expr_id), {.type_id = expr.type_id()});
  1295. expr_id = Initialize(context, SemIR::LocId(expr_id), temporary_id, expr_id);
  1296. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(expr_id),
  1297. {.type_id = expr.type_id(),
  1298. .storage_id = temporary_id,
  1299. .init_id = expr_id});
  1300. }
  1301. // Returns the Core interface name to use for a given kind of conversion.
  1302. static auto GetConversionInterfaceName(ConversionTarget::Kind kind)
  1303. -> CoreIdentifier {
  1304. switch (kind) {
  1305. case ConversionTarget::ExplicitAs:
  1306. return CoreIdentifier::As;
  1307. case ConversionTarget::ExplicitUnsafeAs:
  1308. return CoreIdentifier::UnsafeAs;
  1309. default:
  1310. return CoreIdentifier::ImplicitAs;
  1311. }
  1312. }
  1313. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1314. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1315. return Convert(context, loc_id, action.inst_id,
  1316. {.kind = ConversionTarget::Value,
  1317. .type_id = context.types().GetTypeIdForTypeInstId(
  1318. action.target_type_inst_id)});
  1319. }
  1320. // State machine for performing category conversions.
  1321. class CategoryConverter {
  1322. public:
  1323. // Constructs a converter which converts an expression at the given location
  1324. // to the given conversion target. performed_builtin_conversion indicates
  1325. // whether builtin conversions were performed prior to this.
  1326. CategoryConverter(Context& context, SemIR::LocId loc_id,
  1327. ConversionTarget& target, bool performed_builtin_conversion)
  1328. : context_(context),
  1329. sem_ir_(context.sem_ir()),
  1330. loc_id_(loc_id),
  1331. target_(target),
  1332. performed_builtin_conversion_(performed_builtin_conversion) {}
  1333. // Converts expr_id to the target specified in the constructor, and returns
  1334. // the converted inst.
  1335. auto Convert(SemIR::InstId expr_id) && -> SemIR::InstId {
  1336. auto category = SemIR::GetExprCategory(sem_ir_, expr_id);
  1337. while (true) {
  1338. if (expr_id == SemIR::ErrorInst::InstId) {
  1339. return expr_id;
  1340. }
  1341. CARBON_KIND_SWITCH(DoStep(expr_id, category)) {
  1342. case CARBON_KIND(NextStep next_step): {
  1343. CARBON_CHECK(next_step.expr_id != SemIR::InstId::None);
  1344. expr_id = next_step.expr_id;
  1345. category = next_step.category;
  1346. break;
  1347. }
  1348. case CARBON_KIND(Done done): {
  1349. return done.expr_id;
  1350. }
  1351. }
  1352. }
  1353. }
  1354. private:
  1355. // State that indicates there's more work to be done. As a convenience,
  1356. // if expr_id is SemIR::ErrorInst::InstId, this is equivalent to
  1357. // Done{SemIR::ErrorInst::InstId}.
  1358. struct NextStep {
  1359. // The inst to convert.
  1360. SemIR::InstId expr_id;
  1361. // The category of expr_id.
  1362. SemIR::ExprCategory category;
  1363. };
  1364. // State that indicates we've finished category conversion.
  1365. struct Done {
  1366. // The result of the conversion.
  1367. SemIR::InstId expr_id;
  1368. };
  1369. using State = std::variant<NextStep, Done>;
  1370. // Performs the first step of converting `expr_id` with category `category`
  1371. // to the target specified in the constructor, and returns the state after
  1372. // that step.
  1373. auto DoStep(SemIR::InstId expr_id, SemIR::ExprCategory category) const
  1374. -> State;
  1375. Context& context_;
  1376. SemIR::File& sem_ir_;
  1377. SemIR::LocId loc_id_;
  1378. ConversionTarget& target_;
  1379. bool performed_builtin_conversion_;
  1380. };
  1381. auto CategoryConverter::DoStep(const SemIR::InstId expr_id,
  1382. const SemIR::ExprCategory category) const
  1383. -> State {
  1384. CARBON_DCHECK(SemIR::GetExprCategory(sem_ir_, expr_id) == category);
  1385. switch (category) {
  1386. case SemIR::ExprCategory::NotExpr:
  1387. case SemIR::ExprCategory::Mixed:
  1388. case SemIR::ExprCategory::Pattern:
  1389. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1390. sem_ir_.insts().Get(expr_id));
  1391. case SemIR::ExprCategory::Error:
  1392. return Done{SemIR::ErrorInst::InstId};
  1393. case SemIR::ExprCategory::Initializing:
  1394. if (target_.is_initializer()) {
  1395. if (!performed_builtin_conversion_) {
  1396. // Don't fill in the return slot if we created the expression through
  1397. // a builtin conversion. In that case, we will have created it with
  1398. // the target already set.
  1399. // TODO: Find a better way to track whether we need to do this,
  1400. // and then make target_ immutable if possible.
  1401. MarkInitializerFor(sem_ir_, expr_id, target_);
  1402. }
  1403. return Done{expr_id};
  1404. }
  1405. // Commit to using a temporary for this initializing expression.
  1406. // TODO: Don't create a temporary if the initializing representation
  1407. // is already a value representation.
  1408. // TODO: If the target is DurableRef, materialize a VarStorage instead of
  1409. // a TemporaryStorage to lifetime-extend.
  1410. if (target_.kind == ConversionTarget::Discarded) {
  1411. return Done{FinalizeTemporary(context_, expr_id, /*discarded=*/true)};
  1412. } else {
  1413. return NextStep{.expr_id = FinalizeTemporary(context_, expr_id,
  1414. /*discarded=*/false),
  1415. .category = SemIR::ExprCategory::EphemeralRef};
  1416. }
  1417. case SemIR::ExprCategory::RefTagged: {
  1418. auto tagged_expr_id =
  1419. sem_ir_.insts().GetAs<SemIR::RefTagExpr>(expr_id).expr_id;
  1420. auto tagged_expr_category =
  1421. SemIR::GetExprCategory(sem_ir_, tagged_expr_id);
  1422. if (target_.diagnose &&
  1423. tagged_expr_category != SemIR::ExprCategory::DurableRef) {
  1424. CARBON_DIAGNOSTIC(
  1425. RefTagNotDurableRef, Error,
  1426. "expression tagged with `ref` is not a durable reference");
  1427. context_.emitter().Emit(tagged_expr_id, RefTagNotDurableRef);
  1428. }
  1429. if (target_.kind == ConversionTarget::RefParam) {
  1430. return Done{expr_id};
  1431. }
  1432. // If the target isn't a reference parameter, ignore the `ref` tag.
  1433. // Unnecessary `ref` tags are diagnosed earlier.
  1434. return NextStep{.expr_id = tagged_expr_id,
  1435. .category = tagged_expr_category};
  1436. }
  1437. case SemIR::ExprCategory::DurableRef:
  1438. if (target_.kind == ConversionTarget::DurableRef ||
  1439. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1440. return Done{expr_id};
  1441. }
  1442. if (target_.kind == ConversionTarget::RefParam) {
  1443. if (target_.diagnose) {
  1444. CARBON_DIAGNOSTIC(
  1445. RefParamNoRefTag, Error,
  1446. "argument to `ref` parameter not marked with `ref`");
  1447. context_.emitter().Emit(expr_id, RefParamNoRefTag);
  1448. }
  1449. return Done{expr_id};
  1450. }
  1451. [[fallthrough]];
  1452. case SemIR::ExprCategory::EphemeralRef:
  1453. // If a reference expression is an acceptable result, we're done.
  1454. if (target_.kind == ConversionTarget::ValueOrRef ||
  1455. target_.kind == ConversionTarget::Discarded ||
  1456. target_.kind == ConversionTarget::CppThunkRef ||
  1457. target_.kind == ConversionTarget::RefParam ||
  1458. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1459. return Done{expr_id};
  1460. }
  1461. // If we have a reference and don't want one, form a value binding.
  1462. // TODO: Support types with custom value representations.
  1463. return NextStep{.expr_id = AddInst<SemIR::AcquireValue>(
  1464. context_, SemIR::LocId(expr_id),
  1465. {.type_id = target_.type_id, .value_id = expr_id}),
  1466. .category = SemIR::ExprCategory::Value};
  1467. case SemIR::ExprCategory::Value:
  1468. if (target_.kind == ConversionTarget::DurableRef) {
  1469. if (target_.diagnose) {
  1470. CARBON_DIAGNOSTIC(ConversionFailureNonRefToRef, Error,
  1471. "cannot bind durable reference to non-reference "
  1472. "value of type {0}",
  1473. SemIR::TypeId);
  1474. context_.emitter().Emit(loc_id_, ConversionFailureNonRefToRef,
  1475. target_.type_id);
  1476. }
  1477. return Done{SemIR::ErrorInst::InstId};
  1478. }
  1479. if (target_.kind == ConversionTarget::RefParam ||
  1480. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1481. if (target_.diagnose) {
  1482. CARBON_DIAGNOSTIC(ValueForRefParam, Error,
  1483. "value expression passed to reference parameter");
  1484. context_.emitter().Emit(loc_id_, ValueForRefParam);
  1485. }
  1486. return Done{SemIR::ErrorInst::InstId};
  1487. }
  1488. // When initializing from a value, perform a copy.
  1489. if (target_.is_initializer()) {
  1490. return Done{PerformCopy(context_, expr_id, target_)};
  1491. }
  1492. // When initializing a C++ thunk parameter, form a reference, creating a
  1493. // temporary if needed.
  1494. if (target_.kind == ConversionTarget::CppThunkRef) {
  1495. return Done{ConvertValueForCppThunkRef(context_, expr_id)};
  1496. }
  1497. return Done{expr_id};
  1498. }
  1499. }
  1500. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1501. ConversionTarget target, SemIR::ClassType* vtable_class_type)
  1502. -> SemIR::InstId {
  1503. auto& sem_ir = context.sem_ir();
  1504. auto orig_expr_id = expr_id;
  1505. // Start by making sure both sides are non-errors. If any part is an error,
  1506. // the result is an error and we shouldn't diagnose.
  1507. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::ErrorInst::TypeId ||
  1508. target.type_id == SemIR::ErrorInst::TypeId) {
  1509. return SemIR::ErrorInst::InstId;
  1510. }
  1511. auto starting_category = SemIR::GetExprCategory(sem_ir, expr_id);
  1512. if (starting_category == SemIR::ExprCategory::NotExpr) {
  1513. // TODO: We currently encounter this for use of namespaces and functions.
  1514. // We should provide a better diagnostic for inappropriate use of
  1515. // namespace names, and allow use of functions as values.
  1516. if (target.diagnose) {
  1517. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1518. "expression cannot be used as a value");
  1519. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1520. }
  1521. return SemIR::ErrorInst::InstId;
  1522. }
  1523. // Diagnose unnecessary `ref` tags early, so that they're not obscured by
  1524. // conversions.
  1525. if (starting_category == SemIR::ExprCategory::RefTagged &&
  1526. target.kind != ConversionTarget::RefParam && target.diagnose) {
  1527. CARBON_DIAGNOSTIC(RefTagNoRefParam, Error,
  1528. "`ref` tag is not an argument to a `ref` parameter");
  1529. context.emitter().Emit(expr_id, RefTagNoRefParam);
  1530. }
  1531. // We can only perform initialization for complete, non-abstract types. Note
  1532. // that `RequireConcreteType` returns true for facet types, since their
  1533. // representation is fixed. This allows us to support using the `Self` of an
  1534. // interface inside its definition.
  1535. if (!RequireConcreteType(
  1536. context, target.type_id, loc_id,
  1537. [&] {
  1538. CARBON_CHECK(!target.is_initializer(),
  1539. "Initialization of incomplete types is expected to be "
  1540. "caught elsewhere.");
  1541. if (!target.diagnose) {
  1542. return context.emitter().BuildSuppressed();
  1543. }
  1544. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1545. "forming value of incomplete type {0}",
  1546. SemIR::TypeId);
  1547. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1548. "invalid use of incomplete type {0}",
  1549. SemIR::TypeId);
  1550. return context.emitter().Build(
  1551. loc_id,
  1552. target.kind == ConversionTarget::Value
  1553. ? IncompleteTypeInValueConversion
  1554. : IncompleteTypeInConversion,
  1555. target.type_id);
  1556. },
  1557. [&] {
  1558. if (!target.diagnose || !target.is_initializer()) {
  1559. return context.emitter().BuildSuppressed();
  1560. }
  1561. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1562. "initialization of abstract type {0}",
  1563. SemIR::TypeId);
  1564. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1565. target.type_id);
  1566. })) {
  1567. return SemIR::ErrorInst::InstId;
  1568. }
  1569. if (target.kind != ConversionTarget::FullInitializer &&
  1570. (target.kind != ConversionTarget::Initializer ||
  1571. !SemIR::InitRepr::ForType(context.sem_ir(), target.type_id)
  1572. .MightBeInPlace())) {
  1573. // storage_id should only be used for a FullInitializer, or an Initializer
  1574. // if the type has an in-place init representation. This ensures we don't
  1575. // accidentally use it for anything else.
  1576. target.storage_id = SemIR::InstId::None;
  1577. }
  1578. // The source type doesn't need to be complete, but its completeness can
  1579. // affect the result. For example, we don't know what type it adapts or
  1580. // derives from unless it's complete.
  1581. // TODO: Is there a risk of coherence problems if the source type is
  1582. // incomplete, but a conversion would have been possible or would have behaved
  1583. // differently if it were complete?
  1584. TryToCompleteType(context, context.insts().Get(expr_id).type_id(), loc_id);
  1585. // Check whether any builtin conversion applies.
  1586. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target,
  1587. vtable_class_type);
  1588. if (expr_id == SemIR::ErrorInst::InstId) {
  1589. return expr_id;
  1590. }
  1591. bool performed_builtin_conversion = expr_id != orig_expr_id;
  1592. // Defer the action if it's dependent. We do this now rather than before
  1593. // attempting any conversion so that we can still perform builtin conversions
  1594. // on dependent arguments. This matters for things like converting a
  1595. // `template T:! SomeInterface` to `type`, where it's important to form a
  1596. // `FacetAccessType` when checking the template. But when running the action
  1597. // later, we need to try builtin conversions again, because one may apply that
  1598. // didn't apply in the template definition.
  1599. // TODO: Support this for targets other than `Value`.
  1600. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1601. target.kind == ConversionTarget::Value &&
  1602. (OperandIsDependent(context, expr_id) ||
  1603. OperandIsDependent(context, target.type_id))) {
  1604. auto target_type_inst_id = context.types().GetInstId(target.type_id);
  1605. return AddDependentActionSplice(
  1606. context, loc_id,
  1607. SemIR::ConvertToValueAction{
  1608. .type_id = GetSingletonType(context, SemIR::InstType::TypeInstId),
  1609. .inst_id = expr_id,
  1610. .target_type_inst_id = target_type_inst_id},
  1611. target_type_inst_id);
  1612. }
  1613. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1614. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1615. SemIR::InstId interface_args[] = {
  1616. context.types().GetInstId(target.type_id)};
  1617. Operator op = {
  1618. .interface_name = GetConversionInterfaceName(target.kind),
  1619. .interface_args_ref = interface_args,
  1620. .op_name = CoreIdentifier::Convert,
  1621. };
  1622. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1623. if (!target.diagnose) {
  1624. return context.emitter().BuildSuppressed();
  1625. }
  1626. int target_kind_for_diag =
  1627. target.kind == ConversionTarget::ExplicitAs ? 1
  1628. : target.kind == ConversionTarget::ExplicitUnsafeAs ? 2
  1629. : 0;
  1630. if (target.type_id == SemIR::TypeType::TypeId ||
  1631. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1632. CARBON_DIAGNOSTIC(
  1633. ConversionFailureNonTypeToFacet, Error,
  1634. "cannot{0:=0: implicitly|:} convert non-type value of type {1} "
  1635. "{2:to|into type implementing} {3}"
  1636. "{0:=1: with `as`|=2: with `unsafe as`|:}",
  1637. Diagnostics::IntAsSelect, TypeOfInstId, Diagnostics::BoolAsSelect,
  1638. SemIR::TypeId);
  1639. return context.emitter().Build(
  1640. loc_id, ConversionFailureNonTypeToFacet, target_kind_for_diag,
  1641. expr_id, target.type_id == SemIR::TypeType::TypeId, target.type_id);
  1642. } else {
  1643. CARBON_DIAGNOSTIC(
  1644. ConversionFailure, Error,
  1645. "cannot{0:=0: implicitly|:} convert expression of type "
  1646. "{1} to {2}{0:=1: with `as`|=2: with `unsafe as`|:}",
  1647. Diagnostics::IntAsSelect, TypeOfInstId, SemIR::TypeId);
  1648. return context.emitter().Build(loc_id, ConversionFailure,
  1649. target_kind_for_diag, expr_id,
  1650. target.type_id);
  1651. }
  1652. });
  1653. // Pull a value directly out of the initializer if possible and wanted.
  1654. if (expr_id != SemIR::ErrorInst::InstId &&
  1655. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1656. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1657. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1658. }
  1659. }
  1660. // Track that we performed a type conversion, if we did so.
  1661. if (orig_expr_id != expr_id) {
  1662. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1663. {.type_id = target.type_id,
  1664. .original_id = orig_expr_id,
  1665. .result_id = expr_id});
  1666. }
  1667. // For `as`, don't perform any value category conversions. In particular, an
  1668. // identity conversion shouldn't change the expression category.
  1669. if (target.is_explicit_as()) {
  1670. return expr_id;
  1671. }
  1672. // Now perform any necessary value category conversions.
  1673. expr_id =
  1674. CategoryConverter(context, loc_id, target, performed_builtin_conversion)
  1675. .Convert(expr_id);
  1676. // Perform a final destination store, if necessary.
  1677. if (target.kind == ConversionTarget::FullInitializer) {
  1678. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1679. init_rep.MightBeByCopy()) {
  1680. target.storage_access_block->InsertHere();
  1681. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1682. {.type_id = target.type_id,
  1683. .src_id = expr_id,
  1684. .dest_id = target.storage_id});
  1685. }
  1686. }
  1687. return expr_id;
  1688. }
  1689. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId storage_id,
  1690. SemIR::InstId value_id) -> SemIR::InstId {
  1691. PendingBlock target_block(&context);
  1692. return Convert(context, loc_id, value_id,
  1693. {.kind = ConversionTarget::Initializer,
  1694. .type_id = context.insts().Get(storage_id).type_id(),
  1695. .storage_id = storage_id,
  1696. .storage_access_block = &target_block});
  1697. }
  1698. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1699. -> SemIR::InstId {
  1700. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1701. {.kind = ConversionTarget::Value,
  1702. .type_id = context.insts().Get(expr_id).type_id()});
  1703. }
  1704. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1705. -> SemIR::InstId {
  1706. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1707. {.kind = ConversionTarget::ValueOrRef,
  1708. .type_id = context.insts().Get(expr_id).type_id()});
  1709. }
  1710. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1711. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1712. -> SemIR::InstId {
  1713. return Convert(context, loc_id, expr_id,
  1714. {.kind = ConversionTarget::Value, .type_id = type_id});
  1715. }
  1716. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1717. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1718. -> SemIR::InstId {
  1719. return Convert(context, loc_id, expr_id,
  1720. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1721. }
  1722. // Like ConvertToValueOfType but failure to convert does not result in
  1723. // diagnostics. An ErrorInst instruction is still returned on failure.
  1724. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1725. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1726. -> SemIR::InstId {
  1727. return Convert(
  1728. context, loc_id, expr_id,
  1729. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1730. }
  1731. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1732. SemIR::InstId value_id) -> SemIR::InstId {
  1733. return ConvertToValueOfType(
  1734. context, loc_id, value_id,
  1735. GetSingletonType(context, SemIR::BoolType::TypeInstId));
  1736. }
  1737. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1738. SemIR::InstId value_id, SemIR::TypeId type_id,
  1739. bool unsafe) -> SemIR::InstId {
  1740. return Convert(context, as_node, value_id,
  1741. {.kind = unsafe ? ConversionTarget::ExplicitUnsafeAs
  1742. : ConversionTarget::ExplicitAs,
  1743. .type_id = type_id});
  1744. }
  1745. // TODO: Consider moving this to pattern_match.h.
  1746. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1747. SemIR::InstId self_id,
  1748. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1749. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  1750. const SemIR::Function& callee,
  1751. SemIR::SpecificId callee_specific_id,
  1752. bool is_operator_syntax) -> SemIR::InstBlockId {
  1753. auto param_patterns =
  1754. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1755. auto return_patterns_id = callee.return_patterns_id;
  1756. // The caller should have ensured this callee has the right arity.
  1757. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1758. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1759. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1760. "missing object argument in method call");
  1761. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1762. context.emitter()
  1763. .Build(call_loc_id, MissingObjectInMethodCall)
  1764. .Note(callee.latest_decl_id(), InCallToFunction)
  1765. .Emit();
  1766. self_id = SemIR::ErrorInst::InstId;
  1767. }
  1768. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1769. callee.param_patterns_id, return_patterns_id,
  1770. self_id, arg_refs, return_arg_ids,
  1771. is_operator_syntax);
  1772. }
  1773. auto TypeExpr::ForUnsugared(Context& context, SemIR::TypeId type_id)
  1774. -> TypeExpr {
  1775. return {.inst_id = context.types().GetInstId(type_id), .type_id = type_id};
  1776. }
  1777. static auto DiagnoseTypeExprEvaluationFailure(Context& context,
  1778. SemIR::LocId loc_id) -> void {
  1779. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1780. "cannot evaluate type expression");
  1781. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1782. }
  1783. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1784. bool diagnose) -> TypeExpr {
  1785. auto type_inst_id =
  1786. ConvertToValueOfType(context, loc_id, value_id, SemIR::TypeType::TypeId);
  1787. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1788. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1789. .type_id = SemIR::ErrorInst::TypeId};
  1790. }
  1791. auto type_const_id = context.constant_values().Get(type_inst_id);
  1792. if (!type_const_id.is_constant()) {
  1793. if (diagnose) {
  1794. DiagnoseTypeExprEvaluationFailure(context, loc_id);
  1795. }
  1796. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1797. .type_id = SemIR::ErrorInst::TypeId};
  1798. }
  1799. return {.inst_id = context.types().GetAsTypeInstId(type_inst_id),
  1800. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1801. }
  1802. auto ExprAsReturnForm(Context& context, SemIR::LocId loc_id,
  1803. SemIR::InstId value_id) -> Context::FormExpr {
  1804. constexpr Context::FormExpr ErrorFormExpr = {
  1805. .form_inst_id = SemIR::ErrorInst::InstId,
  1806. .type_component_id = SemIR::ErrorInst::TypeInstId,
  1807. .type_id = SemIR::ErrorInst::TypeId};
  1808. auto form_inst_id = SemIR::InstId::None;
  1809. auto type_inst_id = SemIR::InstId::None;
  1810. if (auto ref_tag = context.insts().TryGetAs<SemIR::RefTagExpr>(value_id)) {
  1811. type_inst_id = ConvertToValueOfType(context, loc_id, ref_tag->expr_id,
  1812. SemIR::TypeType::TypeId);
  1813. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1814. return ErrorFormExpr;
  1815. }
  1816. if (!context.constant_values().Get(type_inst_id).is_constant()) {
  1817. DiagnoseTypeExprEvaluationFailure(context,
  1818. SemIR::LocId(ref_tag->expr_id));
  1819. return ErrorFormExpr;
  1820. }
  1821. form_inst_id = AddInst(
  1822. context,
  1823. SemIR::LocIdAndInst::UncheckedLoc(
  1824. loc_id,
  1825. SemIR::RefForm{.type_id = SemIR::FormType::TypeId,
  1826. .type_component_inst_id =
  1827. context.types().GetAsTypeInstId(type_inst_id)}));
  1828. } else {
  1829. type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1830. SemIR::TypeType::TypeId);
  1831. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1832. return ErrorFormExpr;
  1833. }
  1834. if (!context.constant_values().Get(type_inst_id).is_constant()) {
  1835. DiagnoseTypeExprEvaluationFailure(context, loc_id);
  1836. return ErrorFormExpr;
  1837. }
  1838. form_inst_id = AddInst(
  1839. context,
  1840. SemIR::LocIdAndInst::UncheckedLoc(
  1841. loc_id,
  1842. SemIR::InitForm{
  1843. .type_id = SemIR::FormType::TypeId,
  1844. .type_component_inst_id =
  1845. context.types().GetAsTypeInstId(type_inst_id),
  1846. .index = context.full_pattern_stack().NextCallParamIndex()}));
  1847. }
  1848. auto type_const_id = context.constant_values().Get(type_inst_id);
  1849. CARBON_CHECK(type_const_id.is_constant());
  1850. return {.form_inst_id = form_inst_id,
  1851. .type_component_id = context.types().GetAsTypeInstId(type_inst_id),
  1852. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1853. }
  1854. auto DiscardExpr(Context& context, SemIR::InstId expr_id) -> void {
  1855. // If we discard an initializing expression, convert it to a value or
  1856. // reference so that it has something to initialize.
  1857. auto expr = context.insts().Get(expr_id);
  1858. Convert(context, SemIR::LocId(expr_id), expr_id,
  1859. {.kind = ConversionTarget::Discarded, .type_id = expr.type_id()});
  1860. // TODO: This will eventually need to do some "do not discard" analysis.
  1861. }
  1862. } // namespace Carbon::Check
  1863. // NOLINTEND(misc-no-recursion)