convert.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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 <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "common/map.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/context.h"
  12. #include "toolchain/check/operator.h"
  13. #include "toolchain/check/pattern_match.h"
  14. #include "toolchain/diagnostics/format_providers.h"
  15. #include "toolchain/sem_ir/copy_on_write_block.h"
  16. #include "toolchain/sem_ir/file.h"
  17. #include "toolchain/sem_ir/generic.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/inst.h"
  20. #include "toolchain/sem_ir/typed_insts.h"
  21. namespace Carbon::Check {
  22. // Given an initializing expression, find its return slot argument. Returns
  23. // `Invalid` if there is no return slot, because the initialization is not
  24. // performed in place.
  25. static auto FindReturnSlotArgForInitializer(SemIR::File& sem_ir,
  26. SemIR::InstId init_id)
  27. -> SemIR::InstId {
  28. while (true) {
  29. SemIR::Inst init_untyped = sem_ir.insts().Get(init_id);
  30. CARBON_KIND_SWITCH(init_untyped) {
  31. case CARBON_KIND(SemIR::AsCompatible init): {
  32. init_id = init.source_id;
  33. continue;
  34. }
  35. case CARBON_KIND(SemIR::Converted init): {
  36. init_id = init.result_id;
  37. continue;
  38. }
  39. case CARBON_KIND(SemIR::ArrayInit init): {
  40. return init.dest_id;
  41. }
  42. case CARBON_KIND(SemIR::ClassInit init): {
  43. return init.dest_id;
  44. }
  45. case CARBON_KIND(SemIR::StructInit init): {
  46. return init.dest_id;
  47. }
  48. case CARBON_KIND(SemIR::TupleInit init): {
  49. return init.dest_id;
  50. }
  51. case CARBON_KIND(SemIR::InitializeFrom init): {
  52. return init.dest_id;
  53. }
  54. case CARBON_KIND(SemIR::Call call): {
  55. if (!SemIR::ReturnTypeInfo::ForType(sem_ir, call.type_id)
  56. .has_return_slot()) {
  57. return SemIR::InstId::Invalid;
  58. }
  59. if (!call.args_id.is_valid()) {
  60. // Argument initialization failed, so we have no return slot.
  61. return SemIR::InstId::Invalid;
  62. }
  63. return sem_ir.inst_blocks().Get(call.args_id).back();
  64. }
  65. default:
  66. CARBON_FATAL("Initialization from unexpected inst {0}", init_untyped);
  67. }
  68. }
  69. }
  70. // Marks the initializer `init_id` as initializing `target_id`.
  71. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  72. SemIR::InstId target_id,
  73. PendingBlock& target_block) -> void {
  74. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  75. if (return_slot_arg_id.is_valid()) {
  76. // Replace the temporary in the return slot with a reference to our target.
  77. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  78. SemIR::TemporaryStorage::Kind,
  79. "Return slot for initializer does not contain a temporary; "
  80. "initialized multiple times? Have {0}",
  81. sem_ir.insts().Get(return_slot_arg_id));
  82. target_block.MergeReplacing(return_slot_arg_id, target_id);
  83. }
  84. }
  85. // Commits to using a temporary to store the result of the initializing
  86. // expression described by `init_id`, and returns the location of the
  87. // temporary. If `discarded` is `true`, the result is discarded, and no
  88. // temporary will be created if possible; if no temporary is created, the
  89. // return value will be `SemIR::InstId::Invalid`.
  90. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  91. bool discarded) -> SemIR::InstId {
  92. auto& sem_ir = context.sem_ir();
  93. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  94. if (return_slot_arg_id.is_valid()) {
  95. // The return slot should already have a materialized temporary in it.
  96. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  97. SemIR::TemporaryStorage::Kind,
  98. "Return slot for initializer does not contain a temporary; "
  99. "initialized multiple times? Have {0}",
  100. sem_ir.insts().Get(return_slot_arg_id));
  101. auto init = sem_ir.insts().Get(init_id);
  102. return context.AddInst<SemIR::Temporary>(sem_ir.insts().GetLocId(init_id),
  103. {.type_id = init.type_id(),
  104. .storage_id = return_slot_arg_id,
  105. .init_id = init_id});
  106. }
  107. if (discarded) {
  108. // Don't invent a temporary that we're going to discard.
  109. return SemIR::InstId::Invalid;
  110. }
  111. // The initializer has no return slot, but we want to produce a temporary
  112. // object. Materialize one now.
  113. // TODO: Consider using an invalid ID to mean that we immediately
  114. // materialize and initialize a temporary, rather than two separate
  115. // instructions.
  116. auto init = sem_ir.insts().Get(init_id);
  117. auto loc_id = sem_ir.insts().GetLocId(init_id);
  118. auto temporary_id = context.AddInst<SemIR::TemporaryStorage>(
  119. loc_id, {.type_id = init.type_id()});
  120. return context.AddInst<SemIR::Temporary>(loc_id, {.type_id = init.type_id(),
  121. .storage_id = temporary_id,
  122. .init_id = init_id});
  123. }
  124. // Materialize a temporary to hold the result of the given expression if it is
  125. // an initializing expression.
  126. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  127. -> SemIR::InstId {
  128. if (GetExprCategory(context.sem_ir(), expr_id) ==
  129. SemIR::ExprCategory::Initializing) {
  130. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  131. }
  132. return expr_id;
  133. }
  134. // Creates and adds an instruction to perform element access into an aggregate.
  135. template <typename AccessInstT, typename InstBlockT>
  136. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  137. SemIR::InstId aggregate_id,
  138. SemIR::TypeId elem_type_id, InstBlockT& block,
  139. size_t i) {
  140. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  141. // TODO: Add a new instruction kind for indexing an array at a constant
  142. // index so that we don't need an integer literal instruction here, and
  143. // remove this special case.
  144. auto index_id = block.template AddInst<SemIR::IntValue>(
  145. loc_id, {.type_id = context.GetSingletonType(
  146. SemIR::IntLiteralType::SingletonInstId),
  147. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  148. return block.template AddInst<AccessInstT>(
  149. loc_id, {elem_type_id, aggregate_id, index_id});
  150. } else {
  151. return block.template AddInst<AccessInstT>(
  152. loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  153. }
  154. }
  155. // Converts an element of one aggregate so that it can be used as an element of
  156. // another aggregate.
  157. //
  158. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  159. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  160. // kind of instruction used to access the source element.
  161. //
  162. // For the target: `kind` is the kind of conversion or initialization,
  163. // `target_elem_type` is the element type. For initialization, `target_id` is
  164. // the destination, `target_block` is a pending block for target location
  165. // calculations that will be spliced as the return slot of the initializer if
  166. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  167. // kind of instruction used to access the destination element.
  168. template <typename SourceAccessInstT, typename TargetAccessInstT>
  169. static auto ConvertAggregateElement(
  170. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  171. SemIR::TypeId src_elem_type,
  172. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  173. ConversionTarget::Kind kind, SemIR::InstId target_id,
  174. SemIR::TypeId target_elem_type, PendingBlock* target_block,
  175. size_t src_field_index, size_t target_field_index) {
  176. // Compute the location of the source element. This goes into the current code
  177. // block, not into the target block.
  178. // TODO: Ideally we would discard this instruction if it's unused.
  179. auto src_elem_id = !src_literal_elems.empty()
  180. ? src_literal_elems[src_field_index]
  181. : MakeElementAccessInst<SourceAccessInstT>(
  182. context, loc_id, src_id, src_elem_type, context,
  183. src_field_index);
  184. // If we're performing a conversion rather than an initialization, we won't
  185. // have or need a target.
  186. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  187. if (!target.is_initializer()) {
  188. return Convert(context, loc_id, src_elem_id, target);
  189. }
  190. // Compute the location of the target element and initialize it.
  191. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  192. target.init_block = target_block;
  193. target.init_id = MakeElementAccessInst<TargetAccessInstT>(
  194. context, loc_id, target_id, target_elem_type, *target_block,
  195. target_field_index);
  196. return Convert(context, loc_id, src_elem_id, target);
  197. }
  198. // Performs a conversion from a tuple to an array type. This function only
  199. // converts the type, and does not perform a final conversion to the requested
  200. // expression category.
  201. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  202. SemIR::ArrayType array_type,
  203. SemIR::InstId value_id, ConversionTarget target)
  204. -> SemIR::InstId {
  205. auto& sem_ir = context.sem_ir();
  206. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  207. auto value = sem_ir.insts().Get(value_id);
  208. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  209. // If we're initializing from a tuple literal, we will use its elements
  210. // directly. Otherwise, materialize a temporary if needed and index into the
  211. // result.
  212. llvm::ArrayRef<SemIR::InstId> literal_elems;
  213. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  214. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  215. } else {
  216. value_id = MaterializeIfInitializing(context, value_id);
  217. }
  218. // Check that the tuple is the right size.
  219. uint64_t array_bound = sem_ir.GetArrayBoundValue(array_type.bound_id);
  220. if (tuple_elem_types.size() != array_bound) {
  221. CARBON_DIAGNOSTIC(
  222. ArrayInitFromLiteralArgCountMismatch, Error,
  223. "cannot initialize array of {0} element{0:s} from {1} initializer{1:s}",
  224. IntAsSelect, IntAsSelect);
  225. CARBON_DIAGNOSTIC(ArrayInitFromExprArgCountMismatch, Error,
  226. "cannot initialize array of {0} element{0:s} from tuple "
  227. "with {1} element{1:s}",
  228. IntAsSelect, IntAsSelect);
  229. context.emitter().Emit(value_loc_id,
  230. literal_elems.empty()
  231. ? ArrayInitFromExprArgCountMismatch
  232. : ArrayInitFromLiteralArgCountMismatch,
  233. array_bound, tuple_elem_types.size());
  234. return SemIR::ErrorInst::SingletonInstId;
  235. }
  236. PendingBlock target_block_storage(context);
  237. PendingBlock* target_block =
  238. target.init_block ? target.init_block : &target_block_storage;
  239. // Arrays are always initialized in-place. Allocate a temporary as the
  240. // destination for the array initialization if we weren't given one.
  241. SemIR::InstId return_slot_arg_id = target.init_id;
  242. if (!target.init_id.is_valid()) {
  243. return_slot_arg_id = target_block->AddInst<SemIR::TemporaryStorage>(
  244. value_loc_id, {.type_id = target.type_id});
  245. }
  246. // Initialize each element of the array from the corresponding element of the
  247. // tuple.
  248. // TODO: Annotate diagnostics coming from here with the array element index,
  249. // if initializing from a tuple literal.
  250. llvm::SmallVector<SemIR::InstId> inits;
  251. inits.reserve(array_bound + 1);
  252. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  253. // TODO: This call recurses back into conversion. Switch to an iterative
  254. // approach.
  255. auto init_id =
  256. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  257. context, value_loc_id, value_id, src_type_id, literal_elems,
  258. ConversionTarget::FullInitializer, return_slot_arg_id,
  259. array_type.element_type_id, target_block, i, i);
  260. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  261. return SemIR::ErrorInst::SingletonInstId;
  262. }
  263. inits.push_back(init_id);
  264. }
  265. // Flush the temporary here if we didn't insert it earlier, so we can add a
  266. // reference to the return slot.
  267. target_block->InsertHere();
  268. return context.AddInst<SemIR::ArrayInit>(
  269. value_loc_id, {.type_id = target.type_id,
  270. .inits_id = sem_ir.inst_blocks().Add(inits),
  271. .dest_id = return_slot_arg_id});
  272. }
  273. // Performs a conversion from a tuple to a tuple type. This function only
  274. // converts the type, and does not perform a final conversion to the requested
  275. // expression category.
  276. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  277. SemIR::TupleType dest_type,
  278. SemIR::InstId value_id, ConversionTarget target)
  279. -> SemIR::InstId {
  280. auto& sem_ir = context.sem_ir();
  281. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  282. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  283. auto value = sem_ir.insts().Get(value_id);
  284. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  285. // If we're initializing from a tuple literal, we will use its elements
  286. // directly. Otherwise, materialize a temporary if needed and index into the
  287. // result.
  288. llvm::ArrayRef<SemIR::InstId> literal_elems;
  289. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  290. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  291. literal_elems_id = tuple_literal->elements_id;
  292. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  293. } else {
  294. value_id = MaterializeIfInitializing(context, value_id);
  295. }
  296. // Check that the tuples are the same size.
  297. if (src_elem_types.size() != dest_elem_types.size()) {
  298. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  299. "cannot initialize tuple of {0} element{0:s} from tuple "
  300. "with {1} element{1:s}",
  301. IntAsSelect, IntAsSelect);
  302. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  303. dest_elem_types.size(), src_elem_types.size());
  304. return SemIR::ErrorInst::SingletonInstId;
  305. }
  306. // If we're forming an initializer, then we want an initializer for each
  307. // element. Otherwise, we want a value representation for each element.
  308. // Perform a final destination store if we're performing an in-place
  309. // initialization.
  310. bool is_init = target.is_initializer();
  311. ConversionTarget::Kind inner_kind =
  312. !is_init ? ConversionTarget::Value
  313. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  314. SemIR::InitRepr::InPlace
  315. ? ConversionTarget::FullInitializer
  316. : ConversionTarget::Initializer;
  317. // Initialize each element of the destination from the corresponding element
  318. // of the source.
  319. // TODO: Annotate diagnostics coming from here with the element index.
  320. auto new_block =
  321. literal_elems_id.is_valid()
  322. ? SemIR::CopyOnWriteInstBlock(sem_ir, literal_elems_id)
  323. : SemIR::CopyOnWriteInstBlock(
  324. sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  325. src_elem_types.size()});
  326. for (auto [i, src_type_id, dest_type_id] :
  327. llvm::enumerate(src_elem_types, dest_elem_types)) {
  328. // TODO: This call recurses back into conversion. Switch to an iterative
  329. // approach.
  330. auto init_id =
  331. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  332. context, value_loc_id, value_id, src_type_id, literal_elems,
  333. inner_kind, target.init_id, dest_type_id, target.init_block, i, i);
  334. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  335. return SemIR::ErrorInst::SingletonInstId;
  336. }
  337. new_block.Set(i, init_id);
  338. }
  339. if (is_init) {
  340. target.init_block->InsertHere();
  341. return context.AddInst<SemIR::TupleInit>(value_loc_id,
  342. {.type_id = target.type_id,
  343. .elements_id = new_block.id(),
  344. .dest_id = target.init_id});
  345. } else {
  346. return context.AddInst<SemIR::TupleValue>(
  347. value_loc_id,
  348. {.type_id = target.type_id, .elements_id = new_block.id()});
  349. }
  350. }
  351. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  352. template <typename TargetAccessInstT>
  353. static auto ConvertStructToStructOrClass(Context& context,
  354. SemIR::StructType src_type,
  355. SemIR::StructType dest_type,
  356. SemIR::InstId value_id,
  357. ConversionTarget target)
  358. -> SemIR::InstId {
  359. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  360. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  361. constexpr bool ToClass =
  362. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  363. auto& sem_ir = context.sem_ir();
  364. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  365. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  366. bool dest_has_vptr = !dest_elem_fields.empty() &&
  367. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  368. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  369. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  370. auto value = sem_ir.insts().Get(value_id);
  371. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  372. // If we're initializing from a struct literal, we will use its elements
  373. // directly. Otherwise, materialize a temporary if needed and index into the
  374. // result.
  375. llvm::ArrayRef<SemIR::InstId> literal_elems;
  376. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  377. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  378. literal_elems_id = struct_literal->elements_id;
  379. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  380. } else {
  381. value_id = MaterializeIfInitializing(context, value_id);
  382. }
  383. // Check that the structs are the same size.
  384. // TODO: If not, include the name of the first source field that doesn't
  385. // exist in the destination or vice versa in the diagnostic.
  386. if (src_elem_fields.size() != dest_elem_fields_size) {
  387. CARBON_DIAGNOSTIC(
  388. StructInitElementCountMismatch, Error,
  389. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  390. "with {2} field{2:s}",
  391. BoolAsSelect, IntAsSelect, IntAsSelect);
  392. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  393. ToClass, dest_elem_fields_size,
  394. src_elem_fields.size());
  395. return SemIR::ErrorInst::SingletonInstId;
  396. }
  397. // Prepare to look up fields in the source by index.
  398. Map<SemIR::NameId, int32_t> src_field_indexes;
  399. if (src_type.fields_id != dest_type.fields_id) {
  400. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  401. auto result = src_field_indexes.Insert(field.name_id, i);
  402. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  403. }
  404. }
  405. // If we're forming an initializer, then we want an initializer for each
  406. // element. Otherwise, we want a value representation for each element.
  407. // Perform a final destination store if we're performing an in-place
  408. // initialization.
  409. bool is_init = target.is_initializer();
  410. ConversionTarget::Kind inner_kind =
  411. !is_init ? ConversionTarget::Value
  412. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  413. SemIR::InitRepr::InPlace
  414. ? ConversionTarget::FullInitializer
  415. : ConversionTarget::Initializer;
  416. // Initialize each element of the destination from the corresponding element
  417. // of the source.
  418. // TODO: Annotate diagnostics coming from here with the element index.
  419. auto new_block =
  420. literal_elems_id.is_valid() && !dest_has_vptr
  421. ? SemIR::CopyOnWriteInstBlock(sem_ir, literal_elems_id)
  422. : SemIR::CopyOnWriteInstBlock(
  423. sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  424. dest_elem_fields.size()});
  425. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  426. if (dest_field.name_id == SemIR::NameId::Vptr) {
  427. // CARBON_CHECK(ToClass, "Only classes should have vptrs.");
  428. auto dest_id = context.AddInst<SemIR::ClassElementAccess>(
  429. value_loc_id, {.type_id = dest_field.type_id,
  430. .base_id = target.init_id,
  431. .index = SemIR::ElementIndex(i)});
  432. auto vtable_ptr_id = context.AddInst<SemIR::VtablePtr>(
  433. value_loc_id, {.type_id = dest_field.type_id});
  434. auto init_id = context.AddInst<SemIR::InitializeFrom>(
  435. value_loc_id, {.type_id = dest_field.type_id,
  436. .src_id = vtable_ptr_id,
  437. .dest_id = dest_id});
  438. new_block.Set(i, init_id);
  439. continue;
  440. }
  441. // Find the matching source field.
  442. auto src_field_index = i;
  443. if (src_type.fields_id != dest_type.fields_id) {
  444. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  445. src_field_index = lookup.value();
  446. } else {
  447. if (literal_elems_id.is_valid()) {
  448. CARBON_DIAGNOSTIC(
  449. StructInitMissingFieldInLiteral, Error,
  450. "missing value for field `{0}` in struct initialization",
  451. SemIR::NameId);
  452. context.emitter().Emit(value_loc_id, StructInitMissingFieldInLiteral,
  453. dest_field.name_id);
  454. } else {
  455. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  456. "cannot convert from struct type {0} to {1}: "
  457. "missing field `{2}` in source type",
  458. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  459. context.emitter().Emit(value_loc_id,
  460. StructInitMissingFieldInConversion, value_id,
  461. target.type_id, dest_field.name_id);
  462. }
  463. return SemIR::ErrorInst::SingletonInstId;
  464. }
  465. }
  466. auto src_field = src_elem_fields[src_field_index];
  467. // TODO: This call recurses back into conversion. Switch to an iterative
  468. // approach.
  469. auto init_id =
  470. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  471. context, value_loc_id, value_id, src_field.type_id, literal_elems,
  472. inner_kind, target.init_id, dest_field.type_id, target.init_block,
  473. src_field_index, src_field_index + dest_vptr_offset);
  474. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  475. return SemIR::ErrorInst::SingletonInstId;
  476. }
  477. new_block.Set(i, init_id);
  478. }
  479. if (ToClass) {
  480. target.init_block->InsertHere();
  481. CARBON_CHECK(is_init,
  482. "Converting directly to a class value is not supported");
  483. return context.AddInst<SemIR::ClassInit>(value_loc_id,
  484. {.type_id = target.type_id,
  485. .elements_id = new_block.id(),
  486. .dest_id = target.init_id});
  487. } else if (is_init) {
  488. target.init_block->InsertHere();
  489. return context.AddInst<SemIR::StructInit>(value_loc_id,
  490. {.type_id = target.type_id,
  491. .elements_id = new_block.id(),
  492. .dest_id = target.init_id});
  493. } else {
  494. return context.AddInst<SemIR::StructValue>(
  495. value_loc_id,
  496. {.type_id = target.type_id, .elements_id = new_block.id()});
  497. }
  498. }
  499. // Performs a conversion from a struct to a struct type. This function only
  500. // converts the type, and does not perform a final conversion to the requested
  501. // expression category.
  502. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  503. SemIR::StructType dest_type,
  504. SemIR::InstId value_id,
  505. ConversionTarget target) -> SemIR::InstId {
  506. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  507. context, src_type, dest_type, value_id, target);
  508. }
  509. // Performs a conversion from a struct to a class type. This function only
  510. // converts the type, and does not perform a final conversion to the requested
  511. // expression category.
  512. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  513. SemIR::ClassType dest_type,
  514. SemIR::InstId value_id,
  515. ConversionTarget target) -> SemIR::InstId {
  516. PendingBlock target_block(context);
  517. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  518. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  519. auto object_repr_id =
  520. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  521. if (object_repr_id == SemIR::ErrorInst::SingletonTypeId) {
  522. return SemIR::ErrorInst::SingletonInstId;
  523. }
  524. auto dest_struct_type =
  525. context.types().GetAs<SemIR::StructType>(object_repr_id);
  526. // If we're trying to create a class value, form a temporary for the value to
  527. // point to.
  528. bool need_temporary = !target.is_initializer();
  529. if (need_temporary) {
  530. target.kind = ConversionTarget::Initializer;
  531. target.init_block = &target_block;
  532. target.init_id = target_block.AddInst<SemIR::TemporaryStorage>(
  533. context.insts().GetLocId(value_id), {.type_id = target.type_id});
  534. }
  535. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  536. context, src_type, dest_struct_type, value_id, target);
  537. if (need_temporary) {
  538. target_block.InsertHere();
  539. result_id = context.AddInst<SemIR::Temporary>(
  540. context.insts().GetLocId(value_id), {.type_id = target.type_id,
  541. .storage_id = target.init_id,
  542. .init_id = result_id});
  543. }
  544. return result_id;
  545. }
  546. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  547. // in order from derived to base.
  548. using InheritancePath =
  549. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  550. // Computes the inheritance path from class `derived_id` to class `base_id`.
  551. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  552. static auto ComputeInheritancePath(Context& context, SemIR::TypeId derived_id,
  553. SemIR::TypeId base_id)
  554. -> std::optional<InheritancePath> {
  555. // We intend for NRVO to be applied to `result`. All `return` statements in
  556. // this function should `return result;`.
  557. std::optional<InheritancePath> result(std::in_place);
  558. if (!context.TryToCompleteType(derived_id)) {
  559. // TODO: Should we give an error here? If we don't, and there is an
  560. // inheritance path when the class is defined, we may have a coherence
  561. // problem.
  562. result = std::nullopt;
  563. return result;
  564. }
  565. while (derived_id != base_id) {
  566. auto derived_class_type =
  567. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  568. if (!derived_class_type) {
  569. result = std::nullopt;
  570. break;
  571. }
  572. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  573. auto base_type_id = derived_class.GetBaseType(
  574. context.sem_ir(), derived_class_type->specific_id);
  575. if (!base_type_id.is_valid()) {
  576. result = std::nullopt;
  577. break;
  578. }
  579. result->push_back({derived_class.base_id, base_type_id});
  580. derived_id = base_type_id;
  581. }
  582. return result;
  583. }
  584. // Performs a conversion from a derived class value or reference to a base class
  585. // value or reference.
  586. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  587. SemIR::InstId value_id,
  588. const InheritancePath& path) -> SemIR::InstId {
  589. // Materialize a temporary if necessary.
  590. value_id = ConvertToValueOrRefExpr(context, value_id);
  591. // Add a series of `.base` accesses.
  592. for (auto [base_id, base_type_id] : path) {
  593. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  594. value_id = context.AddInst<SemIR::ClassElementAccess>(
  595. loc_id, {.type_id = base_type_id,
  596. .base_id = value_id,
  597. .index = base_decl.index});
  598. }
  599. return value_id;
  600. }
  601. // Performs a conversion from a derived class pointer to a base class pointer.
  602. static auto ConvertDerivedPointerToBasePointer(
  603. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  604. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  605. const InheritancePath& path) -> SemIR::InstId {
  606. // Form `*p`.
  607. ptr_id = ConvertToValueExpr(context, ptr_id);
  608. auto ref_id = context.AddInst<SemIR::Deref>(
  609. loc_id, {.type_id = src_ptr_type.pointee_id, .pointer_id = ptr_id});
  610. // Convert as a reference expression.
  611. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  612. // Take the address.
  613. return context.AddInst<SemIR::AddrOf>(
  614. loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  615. }
  616. // Returns whether `category` is a valid expression category to produce as a
  617. // result of a conversion with kind `target_kind`, or at most needs a temporary
  618. // to be materialized.
  619. static auto IsValidExprCategoryForConversionTarget(
  620. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  621. switch (target_kind) {
  622. case ConversionTarget::Value:
  623. return category == SemIR::ExprCategory::Value;
  624. case ConversionTarget::ValueOrRef:
  625. case ConversionTarget::Discarded:
  626. return category == SemIR::ExprCategory::Value ||
  627. category == SemIR::ExprCategory::DurableRef ||
  628. category == SemIR::ExprCategory::EphemeralRef ||
  629. category == SemIR::ExprCategory::Initializing;
  630. case ConversionTarget::ExplicitAs:
  631. return true;
  632. case ConversionTarget::Initializer:
  633. case ConversionTarget::FullInitializer:
  634. return category == SemIR::ExprCategory::Initializing;
  635. }
  636. }
  637. // Determines whether the initialization representation of the type is a copy of
  638. // the value representation.
  639. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  640. SemIR::TypeId type_id) -> bool {
  641. // The initializing representation is a copy of the value representation if
  642. // they're both copies of the object representation.
  643. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  644. SemIR::ValueRepr::ForType(sem_ir, type_id)
  645. .IsCopyOfObjectRepr(sem_ir, type_id);
  646. }
  647. // Determines whether we can pull a value directly out of an initializing
  648. // expression of type `type_id` to initialize a target of type `type_id` and
  649. // kind `target_kind`.
  650. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  651. SemIR::TypeId type_id,
  652. ConversionTarget::Kind target_kind)
  653. -> bool {
  654. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  655. target_kind)) {
  656. // We don't want a value expression.
  657. return false;
  658. }
  659. // We can pull a value out of an initializing expression if it holds one.
  660. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  661. }
  662. // Returns the non-adapter type that is compatible with the specified type.
  663. static auto GetCompatibleBaseType(Context& context, SemIR::TypeId type_id)
  664. -> SemIR::TypeId {
  665. // If the type is an adapter, its object representation type is its compatible
  666. // non-adapter type.
  667. while (auto class_type =
  668. context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  669. auto& class_info = context.classes().Get(class_type->class_id);
  670. auto adapted_type_id =
  671. class_info.GetAdaptedType(context.sem_ir(), class_type->specific_id);
  672. if (!adapted_type_id.is_valid()) {
  673. break;
  674. }
  675. type_id = adapted_type_id;
  676. }
  677. // Otherwise, the type itself is a non-adapter type.
  678. return type_id;
  679. }
  680. static auto PerformBuiltinConversion(Context& context, SemIR::LocId loc_id,
  681. SemIR::InstId value_id,
  682. ConversionTarget target) -> SemIR::InstId {
  683. auto& sem_ir = context.sem_ir();
  684. auto value = sem_ir.insts().Get(value_id);
  685. auto value_type_id = value.type_id();
  686. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  687. // Various forms of implicit conversion are supported as builtin conversions,
  688. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  689. // prelude. There are a few reasons we need to perform some of these
  690. // conversions as builtins:
  691. //
  692. // 1) Conversions from struct and tuple *literals* have special rules that
  693. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  694. // recurse into the elements of the literal before performing
  695. // initialization in order to avoid unnecessary conversions between
  696. // expression categories that would be performed by `ImplicitAs.Convert`.
  697. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  698. // the value of the facet, not only its type, and therefore cannot be
  699. // modeled by `ImplicitAs`.
  700. // 3) Some of these conversions are used while checking the library
  701. // definition of `ImplicitAs` itself or implementations of it.
  702. //
  703. // We also expect to see better performance by avoiding an `impl` lookup for
  704. // common conversions.
  705. //
  706. // TODO: We should provide a debugging flag to turn off as many of these
  707. // builtin conversions as we can so that we can test that they do the same
  708. // thing as the library implementations.
  709. //
  710. // The builtin conversions that correspond to `impl`s in the library all
  711. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  712. // being specialized in any of these cases.
  713. // If the value is already of the right kind and expression category, there's
  714. // nothing to do. Performing a conversion would decompose and rebuild tuples
  715. // and structs, so it's important that we bail out early in this case.
  716. if (value_type_id == target.type_id) {
  717. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  718. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  719. return value_id;
  720. }
  721. // If the source is an initializing expression, we may be able to pull a
  722. // value right out of it.
  723. if (value_cat == SemIR::ExprCategory::Initializing &&
  724. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  725. return context.AddInst<SemIR::ValueOfInitializer>(
  726. loc_id, {.type_id = value_type_id, .init_id = value_id});
  727. }
  728. }
  729. // T explicitly converts to U if T is compatible with U.
  730. if (target.kind == ConversionTarget::Kind::ExplicitAs &&
  731. target.type_id != value_type_id) {
  732. auto target_base_id = GetCompatibleBaseType(context, target.type_id);
  733. auto value_base_id = GetCompatibleBaseType(context, value_type_id);
  734. if (target_base_id == value_base_id) {
  735. // For a struct or tuple literal, perform a category conversion if
  736. // necessary.
  737. if (SemIR::GetExprCategory(context.sem_ir(), value_id) ==
  738. SemIR::ExprCategory::Mixed) {
  739. value_id = PerformBuiltinConversion(
  740. context, loc_id, value_id,
  741. ConversionTarget{.kind = ConversionTarget::Value,
  742. .type_id = value_type_id});
  743. }
  744. return context.AddInst<SemIR::AsCompatible>(
  745. loc_id, {.type_id = target.type_id, .source_id = value_id});
  746. }
  747. }
  748. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  749. // converts to Ui.
  750. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  751. if (auto src_tuple_type =
  752. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  753. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  754. value_id, target);
  755. }
  756. }
  757. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  758. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  759. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  760. // to Ui.
  761. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  762. if (auto src_struct_type =
  763. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  764. return ConvertStructToStruct(context, *src_struct_type,
  765. *target_struct_type, value_id, target);
  766. }
  767. }
  768. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  769. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  770. if (auto src_tuple_type =
  771. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  772. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  773. value_id, target);
  774. }
  775. }
  776. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  777. // if it converts to the struct type that is the class's representation type
  778. // (a struct with the same fields as the class, plus a base field where
  779. // relevant).
  780. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  781. if (auto src_struct_type =
  782. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  783. if (!context.classes()
  784. .Get(target_class_type->class_id)
  785. .adapt_id.is_valid()) {
  786. return ConvertStructToClass(context, *src_struct_type,
  787. *target_class_type, value_id, target);
  788. }
  789. }
  790. // An expression of type T converts to U if T is a class derived from U.
  791. if (auto path =
  792. ComputeInheritancePath(context, value_type_id, target.type_id);
  793. path && !path->empty()) {
  794. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  795. }
  796. }
  797. // A pointer T* converts to U* if T is a class derived from U.
  798. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  799. if (auto src_pointer_type =
  800. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  801. if (auto path =
  802. ComputeInheritancePath(context, src_pointer_type->pointee_id,
  803. target_pointer_type->pointee_id);
  804. path && !path->empty()) {
  805. return ConvertDerivedPointerToBasePointer(
  806. context, loc_id, *src_pointer_type, target.type_id, value_id,
  807. *path);
  808. }
  809. }
  810. }
  811. if (target.type_id == SemIR::TypeType::SingletonTypeId) {
  812. // A tuple of types converts to type `type`.
  813. // TODO: This should apply even for non-literal tuples.
  814. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  815. llvm::SmallVector<SemIR::TypeId> type_ids;
  816. for (auto tuple_inst_id :
  817. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  818. // TODO: This call recurses back into conversion. Switch to an
  819. // iterative approach.
  820. type_ids.push_back(ExprAsType(context, loc_id, tuple_inst_id).type_id);
  821. }
  822. auto tuple_type_id = context.GetTupleType(type_ids);
  823. return sem_ir.types().GetInstId(tuple_type_id);
  824. }
  825. // `{}` converts to `{} as type`.
  826. // TODO: This conversion should also be performed for a non-literal value
  827. // of type `{}`.
  828. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  829. struct_literal &&
  830. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  831. value_id = sem_ir.types().GetInstId(value_type_id);
  832. }
  833. // Facet type conversions: a value T of facet type F1 can be implicitly
  834. // converted to facet type F2 if T satisfies the requirements of F2.
  835. //
  836. // TODO: Support this conversion in general. For now we only support it in
  837. // the case where F1 is a facet type and F2 is `type`.
  838. // TODO: Support converting tuple and struct values to facet types,
  839. // combining the above conversions and this one in a single conversion.
  840. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  841. return context.AddInst<SemIR::FacetAccessType>(
  842. loc_id, {.type_id = target.type_id, .facet_value_inst_id = value_id});
  843. }
  844. }
  845. // No builtin conversion applies.
  846. return value_id;
  847. }
  848. // Given a value expression, form a corresponding initializer that copies from
  849. // that value, if it is possible to do so.
  850. static auto PerformCopy(Context& context, SemIR::InstId expr_id)
  851. -> SemIR::InstId {
  852. auto expr = context.insts().Get(expr_id);
  853. auto type_id = expr.type_id();
  854. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  855. return SemIR::ErrorInst::SingletonInstId;
  856. }
  857. if (InitReprIsCopyOfValueRepr(context.sem_ir(), type_id)) {
  858. // For simple by-value types, no explicit action is required. Initializing
  859. // from a value expression is treated as copying the value.
  860. return expr_id;
  861. }
  862. // TODO: We don't yet have rules for whether and when a class type is
  863. // copyable, or how to perform the copy.
  864. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  865. "cannot copy value of type {0}", TypeOfInstId);
  866. context.emitter().Emit(expr_id, CopyOfUncopyableType, expr_id);
  867. return SemIR::ErrorInst::SingletonInstId;
  868. }
  869. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  870. ConversionTarget target) -> SemIR::InstId {
  871. auto& sem_ir = context.sem_ir();
  872. auto orig_expr_id = expr_id;
  873. // Start by making sure both sides are valid. If any part is invalid, the
  874. // result is invalid and we shouldn't error.
  875. if (sem_ir.insts().Get(expr_id).type_id() ==
  876. SemIR::ErrorInst::SingletonTypeId ||
  877. target.type_id == SemIR::ErrorInst::SingletonTypeId) {
  878. return SemIR::ErrorInst::SingletonInstId;
  879. }
  880. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  881. // TODO: We currently encounter this for use of namespaces and functions.
  882. // We should provide a better diagnostic for inappropriate use of
  883. // namespace names, and allow use of functions as values.
  884. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  885. "expression cannot be used as a value");
  886. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  887. return SemIR::ErrorInst::SingletonInstId;
  888. }
  889. // We can only perform initialization for complete types.
  890. if (!context.TryToCompleteType(
  891. target.type_id, loc_id,
  892. [&] {
  893. CARBON_CHECK(!target.is_initializer(),
  894. "Initialization of incomplete types is expected to be "
  895. "caught elsewhere.");
  896. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  897. "forming value of incomplete type {0}",
  898. SemIR::TypeId);
  899. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  900. "invalid use of incomplete type {0}",
  901. SemIR::TypeId);
  902. return context.emitter().Build(
  903. loc_id,
  904. target.kind == ConversionTarget::Value
  905. ? IncompleteTypeInValueConversion
  906. : IncompleteTypeInConversion,
  907. target.type_id);
  908. },
  909. [&] {
  910. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  911. "initialization of abstract type {0}",
  912. SemIR::TypeId);
  913. if (!target.is_initializer()) {
  914. return context.emitter().BuildSuppressed();
  915. }
  916. return context.emitter().Build(loc_id, AbstractTypeInInit,
  917. target.type_id);
  918. })) {
  919. return SemIR::ErrorInst::SingletonInstId;
  920. }
  921. // Check whether any builtin conversion applies.
  922. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target);
  923. if (expr_id == SemIR::ErrorInst::SingletonInstId) {
  924. return expr_id;
  925. }
  926. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  927. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  928. SemIR::InstId interface_args[] = {
  929. context.types().GetInstId(target.type_id)};
  930. Operator op = {
  931. .interface_name = target.kind == ConversionTarget::ExplicitAs
  932. ? llvm::StringLiteral("As")
  933. : llvm::StringLiteral("ImplicitAs"),
  934. .interface_args_ref = interface_args,
  935. .op_name = "Convert",
  936. };
  937. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  938. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  939. "cannot implicitly convert from {0} to {1}",
  940. TypeOfInstId, SemIR::TypeId);
  941. CARBON_DIAGNOSTIC(ExplicitAsConversionFailure, Error,
  942. "cannot convert from {0} to {1} with `as`",
  943. TypeOfInstId, SemIR::TypeId);
  944. return context.emitter().Build(loc_id,
  945. target.kind == ConversionTarget::ExplicitAs
  946. ? ExplicitAsConversionFailure
  947. : ImplicitAsConversionFailure,
  948. expr_id, target.type_id);
  949. });
  950. // Pull a value directly out of the initializer if possible and wanted.
  951. if (expr_id != SemIR::ErrorInst::SingletonInstId &&
  952. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  953. expr_id = context.AddInst<SemIR::ValueOfInitializer>(
  954. loc_id, {.type_id = target.type_id, .init_id = expr_id});
  955. }
  956. }
  957. // Track that we performed a type conversion, if we did so.
  958. if (orig_expr_id != expr_id) {
  959. expr_id =
  960. context.AddInst<SemIR::Converted>(loc_id, {.type_id = target.type_id,
  961. .original_id = orig_expr_id,
  962. .result_id = expr_id});
  963. }
  964. // For `as`, don't perform any value category conversions. In particular, an
  965. // identity conversion shouldn't change the expression category.
  966. if (target.kind == ConversionTarget::ExplicitAs) {
  967. return expr_id;
  968. }
  969. // Now perform any necessary value category conversions.
  970. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  971. case SemIR::ExprCategory::NotExpr:
  972. case SemIR::ExprCategory::Mixed:
  973. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  974. sem_ir.insts().Get(expr_id));
  975. case SemIR::ExprCategory::Error:
  976. return SemIR::ErrorInst::SingletonInstId;
  977. case SemIR::ExprCategory::Initializing:
  978. if (target.is_initializer()) {
  979. if (orig_expr_id == expr_id) {
  980. // Don't fill in the return slot if we created the expression through
  981. // a conversion. In that case, we will have created it with the
  982. // target already set.
  983. // TODO: Find a better way to track whether we need to do this.
  984. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  985. *target.init_block);
  986. }
  987. break;
  988. }
  989. // Commit to using a temporary for this initializing expression.
  990. // TODO: Don't create a temporary if the initializing representation
  991. // is already a value representation.
  992. expr_id = FinalizeTemporary(context, expr_id,
  993. target.kind == ConversionTarget::Discarded);
  994. // We now have an ephemeral reference.
  995. [[fallthrough]];
  996. case SemIR::ExprCategory::DurableRef:
  997. case SemIR::ExprCategory::EphemeralRef:
  998. // If a reference expression is an acceptable result, we're done.
  999. if (target.kind == ConversionTarget::ValueOrRef ||
  1000. target.kind == ConversionTarget::Discarded) {
  1001. break;
  1002. }
  1003. // If we have a reference and don't want one, form a value binding.
  1004. // TODO: Support types with custom value representations.
  1005. expr_id = context.AddInst<SemIR::BindValue>(
  1006. context.insts().GetLocId(expr_id),
  1007. {.type_id = target.type_id, .value_id = expr_id});
  1008. // We now have a value expression.
  1009. [[fallthrough]];
  1010. case SemIR::ExprCategory::Value:
  1011. // When initializing from a value, perform a copy.
  1012. if (target.is_initializer()) {
  1013. expr_id = PerformCopy(context, expr_id);
  1014. }
  1015. break;
  1016. }
  1017. // Perform a final destination store, if necessary.
  1018. if (target.kind == ConversionTarget::FullInitializer) {
  1019. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1020. init_rep.kind == SemIR::InitRepr::ByCopy) {
  1021. target.init_block->InsertHere();
  1022. expr_id = context.AddInst<SemIR::InitializeFrom>(
  1023. loc_id, {.type_id = target.type_id,
  1024. .src_id = expr_id,
  1025. .dest_id = target.init_id});
  1026. }
  1027. }
  1028. return expr_id;
  1029. }
  1030. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1031. SemIR::InstId value_id) -> SemIR::InstId {
  1032. PendingBlock target_block(context);
  1033. return Convert(context, loc_id, value_id,
  1034. {.kind = ConversionTarget::Initializer,
  1035. .type_id = context.insts().Get(target_id).type_id(),
  1036. .init_id = target_id,
  1037. .init_block = &target_block});
  1038. }
  1039. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1040. -> SemIR::InstId {
  1041. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1042. {.kind = ConversionTarget::Value,
  1043. .type_id = context.insts().Get(expr_id).type_id()});
  1044. }
  1045. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1046. -> SemIR::InstId {
  1047. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1048. {.kind = ConversionTarget::ValueOrRef,
  1049. .type_id = context.insts().Get(expr_id).type_id()});
  1050. }
  1051. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1052. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1053. -> SemIR::InstId {
  1054. return Convert(context, loc_id, expr_id,
  1055. {.kind = ConversionTarget::Value, .type_id = type_id});
  1056. }
  1057. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1058. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1059. -> SemIR::InstId {
  1060. return Convert(context, loc_id, expr_id,
  1061. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1062. }
  1063. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1064. SemIR::InstId value_id) -> SemIR::InstId {
  1065. return ConvertToValueOfType(
  1066. context, loc_id, value_id,
  1067. context.GetSingletonType(SemIR::BoolType::SingletonInstId));
  1068. }
  1069. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1070. SemIR::InstId value_id, SemIR::TypeId type_id)
  1071. -> SemIR::InstId {
  1072. return Convert(context, as_node, value_id,
  1073. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  1074. }
  1075. // TODO: Consider moving this to pattern_match.h.
  1076. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1077. SemIR::InstId self_id,
  1078. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1079. SemIR::InstId return_slot_arg_id,
  1080. const SemIR::Function& callee,
  1081. SemIR::SpecificId callee_specific_id)
  1082. -> SemIR::InstBlockId {
  1083. // The callee reference can be invalidated by conversions, so ensure all reads
  1084. // from it are done before conversion calls.
  1085. auto callee_decl_id = callee.latest_decl_id();
  1086. auto implicit_param_patterns =
  1087. context.inst_blocks().GetOrEmpty(callee.implicit_param_patterns_id);
  1088. auto param_patterns =
  1089. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1090. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1091. // The caller should have ensured this callee has the right arity.
  1092. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1093. // Find self parameter pattern.
  1094. // TODO: Do this during initial traversal of implicit params.
  1095. auto self_param_id = SemIR::InstId::Invalid;
  1096. for (auto implicit_param_id : implicit_param_patterns) {
  1097. if (SemIR::Function::GetNameFromPatternId(
  1098. context.sem_ir(), implicit_param_id) == SemIR::NameId::SelfValue) {
  1099. CARBON_CHECK(!self_param_id.is_valid());
  1100. self_param_id = implicit_param_id;
  1101. }
  1102. }
  1103. if (self_param_id.is_valid() && !self_id.is_valid()) {
  1104. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1105. "missing object argument in method call");
  1106. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1107. context.emitter()
  1108. .Build(call_loc_id, MissingObjectInMethodCall)
  1109. .Note(callee_decl_id, InCallToFunction)
  1110. .Emit();
  1111. self_id = SemIR::ErrorInst::SingletonInstId;
  1112. }
  1113. return CallerPatternMatch(context, callee_specific_id, self_param_id,
  1114. callee.param_patterns_id, return_slot_pattern_id,
  1115. self_id, arg_refs, return_slot_arg_id);
  1116. }
  1117. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id)
  1118. -> TypeExpr {
  1119. auto type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1120. SemIR::TypeType::SingletonTypeId);
  1121. if (type_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1122. return {.inst_id = type_inst_id,
  1123. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1124. }
  1125. auto type_const_id = context.constant_values().Get(type_inst_id);
  1126. if (!type_const_id.is_constant()) {
  1127. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1128. "cannot evaluate type expression");
  1129. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1130. return {.inst_id = SemIR::ErrorInst::SingletonInstId,
  1131. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1132. }
  1133. return {.inst_id = type_inst_id,
  1134. .type_id = context.GetTypeIdForTypeConstant(type_const_id)};
  1135. }
  1136. } // namespace Carbon::Check