convert.cpp 84 KB

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