convert.cpp 82 KB

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