convert.cpp 90 KB

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