convert.cpp 99 KB

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