convert.cpp 76 KB

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