convert.cpp 99 KB

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