convert.cpp 91 KB

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