convert.cpp 100 KB

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