convert.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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.GetBuiltinType(
  146. SemIR::BuiltinInstKind::IntLiteralType),
  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. // TODO: Initialize the vptr to point to a vtable.
  428. new_block.Set(i, SemIR::ErrorInst::SingletonInstId);
  429. continue;
  430. }
  431. // Find the matching source field.
  432. auto src_field_index = i;
  433. if (src_type.fields_id != dest_type.fields_id) {
  434. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  435. src_field_index = lookup.value();
  436. } else {
  437. if (literal_elems_id.is_valid()) {
  438. CARBON_DIAGNOSTIC(
  439. StructInitMissingFieldInLiteral, Error,
  440. "missing value for field `{0}` in struct initialization",
  441. SemIR::NameId);
  442. context.emitter().Emit(value_loc_id, StructInitMissingFieldInLiteral,
  443. dest_field.name_id);
  444. } else {
  445. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  446. "cannot convert from struct type {0} to {1}: "
  447. "missing field `{2}` in source type",
  448. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  449. context.emitter().Emit(value_loc_id,
  450. StructInitMissingFieldInConversion, value_id,
  451. target.type_id, dest_field.name_id);
  452. }
  453. return SemIR::ErrorInst::SingletonInstId;
  454. }
  455. }
  456. auto src_field = src_elem_fields[src_field_index];
  457. // TODO: This call recurses back into conversion. Switch to an iterative
  458. // approach.
  459. auto init_id =
  460. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  461. context, value_loc_id, value_id, src_field.type_id, literal_elems,
  462. inner_kind, target.init_id, dest_field.type_id, target.init_block,
  463. src_field_index, src_field_index + dest_vptr_offset);
  464. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  465. return SemIR::ErrorInst::SingletonInstId;
  466. }
  467. new_block.Set(i, init_id);
  468. }
  469. if (ToClass) {
  470. target.init_block->InsertHere();
  471. CARBON_CHECK(is_init,
  472. "Converting directly to a class value is not supported");
  473. return context.AddInst<SemIR::ClassInit>(value_loc_id,
  474. {.type_id = target.type_id,
  475. .elements_id = new_block.id(),
  476. .dest_id = target.init_id});
  477. } else if (is_init) {
  478. target.init_block->InsertHere();
  479. return context.AddInst<SemIR::StructInit>(value_loc_id,
  480. {.type_id = target.type_id,
  481. .elements_id = new_block.id(),
  482. .dest_id = target.init_id});
  483. } else {
  484. return context.AddInst<SemIR::StructValue>(
  485. value_loc_id,
  486. {.type_id = target.type_id, .elements_id = new_block.id()});
  487. }
  488. }
  489. // Performs a conversion from a struct to a struct type. This function only
  490. // converts the type, and does not perform a final conversion to the requested
  491. // expression category.
  492. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  493. SemIR::StructType dest_type,
  494. SemIR::InstId value_id,
  495. ConversionTarget target) -> SemIR::InstId {
  496. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  497. context, src_type, dest_type, value_id, target);
  498. }
  499. // Performs a conversion from a struct to a class type. This function only
  500. // converts the type, and does not perform a final conversion to the requested
  501. // expression category.
  502. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  503. SemIR::ClassType dest_type,
  504. SemIR::InstId value_id,
  505. ConversionTarget target) -> SemIR::InstId {
  506. PendingBlock target_block(context);
  507. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  508. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  509. auto object_repr_id =
  510. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  511. if (object_repr_id == SemIR::ErrorInst::SingletonTypeId) {
  512. return SemIR::ErrorInst::SingletonInstId;
  513. }
  514. auto dest_struct_type =
  515. context.types().GetAs<SemIR::StructType>(object_repr_id);
  516. // If we're trying to create a class value, form a temporary for the value to
  517. // point to.
  518. bool need_temporary = !target.is_initializer();
  519. if (need_temporary) {
  520. target.kind = ConversionTarget::Initializer;
  521. target.init_block = &target_block;
  522. target.init_id = target_block.AddInst<SemIR::TemporaryStorage>(
  523. context.insts().GetLocId(value_id), {.type_id = target.type_id});
  524. }
  525. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  526. context, src_type, dest_struct_type, value_id, target);
  527. if (need_temporary) {
  528. target_block.InsertHere();
  529. result_id = context.AddInst<SemIR::Temporary>(
  530. context.insts().GetLocId(value_id), {.type_id = target.type_id,
  531. .storage_id = target.init_id,
  532. .init_id = result_id});
  533. }
  534. return result_id;
  535. }
  536. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  537. // in order from derived to base.
  538. using InheritancePath =
  539. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  540. // Computes the inheritance path from class `derived_id` to class `base_id`.
  541. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  542. static auto ComputeInheritancePath(Context& context, SemIR::TypeId derived_id,
  543. SemIR::TypeId base_id)
  544. -> std::optional<InheritancePath> {
  545. // We intend for NRVO to be applied to `result`. All `return` statements in
  546. // this function should `return result;`.
  547. std::optional<InheritancePath> result(std::in_place);
  548. if (!context.TryToCompleteType(derived_id)) {
  549. // TODO: Should we give an error here? If we don't, and there is an
  550. // inheritance path when the class is defined, we may have a coherence
  551. // problem.
  552. result = std::nullopt;
  553. return result;
  554. }
  555. while (derived_id != base_id) {
  556. auto derived_class_type =
  557. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  558. if (!derived_class_type) {
  559. result = std::nullopt;
  560. break;
  561. }
  562. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  563. auto base_type_id = derived_class.GetBaseType(
  564. context.sem_ir(), derived_class_type->specific_id);
  565. if (!base_type_id.is_valid()) {
  566. result = std::nullopt;
  567. break;
  568. }
  569. result->push_back({derived_class.base_id, base_type_id});
  570. derived_id = base_type_id;
  571. }
  572. return result;
  573. }
  574. // Performs a conversion from a derived class value or reference to a base class
  575. // value or reference.
  576. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  577. SemIR::InstId value_id,
  578. const InheritancePath& path) -> SemIR::InstId {
  579. // Materialize a temporary if necessary.
  580. value_id = ConvertToValueOrRefExpr(context, value_id);
  581. // Add a series of `.base` accesses.
  582. for (auto [base_id, base_type_id] : path) {
  583. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  584. value_id = context.AddInst<SemIR::ClassElementAccess>(
  585. loc_id, {.type_id = base_type_id,
  586. .base_id = value_id,
  587. .index = base_decl.index});
  588. }
  589. return value_id;
  590. }
  591. // Performs a conversion from a derived class pointer to a base class pointer.
  592. static auto ConvertDerivedPointerToBasePointer(
  593. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  594. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  595. const InheritancePath& path) -> SemIR::InstId {
  596. // Form `*p`.
  597. ptr_id = ConvertToValueExpr(context, ptr_id);
  598. auto ref_id = context.AddInst<SemIR::Deref>(
  599. loc_id, {.type_id = src_ptr_type.pointee_id, .pointer_id = ptr_id});
  600. // Convert as a reference expression.
  601. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  602. // Take the address.
  603. return context.AddInst<SemIR::AddrOf>(
  604. loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  605. }
  606. // Returns whether `category` is a valid expression category to produce as a
  607. // result of a conversion with kind `target_kind`, or at most needs a temporary
  608. // to be materialized.
  609. static auto IsValidExprCategoryForConversionTarget(
  610. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  611. switch (target_kind) {
  612. case ConversionTarget::Value:
  613. return category == SemIR::ExprCategory::Value;
  614. case ConversionTarget::ValueOrRef:
  615. case ConversionTarget::Discarded:
  616. return category == SemIR::ExprCategory::Value ||
  617. category == SemIR::ExprCategory::DurableRef ||
  618. category == SemIR::ExprCategory::EphemeralRef ||
  619. category == SemIR::ExprCategory::Initializing;
  620. case ConversionTarget::ExplicitAs:
  621. return true;
  622. case ConversionTarget::Initializer:
  623. case ConversionTarget::FullInitializer:
  624. return category == SemIR::ExprCategory::Initializing;
  625. }
  626. }
  627. // Determines whether we can pull a value directly out of an initializing
  628. // expression of type `type_id` to initialize a target of type `type_id` and
  629. // kind `target_kind`.
  630. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  631. SemIR::TypeId type_id,
  632. ConversionTarget::Kind target_kind)
  633. -> bool {
  634. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  635. target_kind)) {
  636. // We don't want a value expression.
  637. return false;
  638. }
  639. if (SemIR::InitRepr::ForType(sem_ir, type_id).kind !=
  640. SemIR::InitRepr::ByCopy) {
  641. // The initializing expression doesn't contain a copy of a value.
  642. return false;
  643. }
  644. // If the value representation is a copy of the object representation, we
  645. // already have a value of the right form and can use that value directly.
  646. auto value_rep = SemIR::ValueRepr::ForType(sem_ir, type_id);
  647. return value_rep.kind == SemIR::ValueRepr::Copy &&
  648. value_rep.type_id == type_id;
  649. }
  650. // Returns the non-adapter type that is compatible with the specified type.
  651. static auto GetCompatibleBaseType(Context& context, SemIR::TypeId type_id)
  652. -> SemIR::TypeId {
  653. // If the type is an adapter, its object representation type is its compatible
  654. // non-adapter type.
  655. while (auto class_type =
  656. context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  657. auto& class_info = context.classes().Get(class_type->class_id);
  658. auto adapted_type_id =
  659. class_info.GetAdaptedType(context.sem_ir(), class_type->specific_id);
  660. if (!adapted_type_id.is_valid()) {
  661. break;
  662. }
  663. type_id = adapted_type_id;
  664. }
  665. // Otherwise, the type itself is a non-adapter type.
  666. return type_id;
  667. }
  668. static auto PerformBuiltinConversion(Context& context, SemIR::LocId loc_id,
  669. SemIR::InstId value_id,
  670. ConversionTarget target) -> SemIR::InstId {
  671. auto& sem_ir = context.sem_ir();
  672. auto value = sem_ir.insts().Get(value_id);
  673. auto value_type_id = value.type_id();
  674. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  675. // Various forms of implicit conversion are supported as builtin conversions,
  676. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  677. // prelude. There are a few reasons we need to perform some of these
  678. // conversions as builtins:
  679. //
  680. // 1) Conversions from struct and tuple *literals* have special rules that
  681. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  682. // recurse into the elements of the literal before performing
  683. // initialization in order to avoid unnecessary conversions between
  684. // expression categories that would be performed by `ImplicitAs.Convert`.
  685. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  686. // the value of the facet, not only its type, and therefore cannot be
  687. // modeled by `ImplicitAs`.
  688. // 3) Some of these conversions are used while checking the library
  689. // definition of `ImplicitAs` itself or implementations of it.
  690. //
  691. // We also expect to see better performance by avoiding an `impl` lookup for
  692. // common conversions.
  693. //
  694. // TODO: We should provide a debugging flag to turn off as many of these
  695. // builtin conversions as we can so that we can test that they do the same
  696. // thing as the library implementations.
  697. //
  698. // The builtin conversions that correspond to `impl`s in the library all
  699. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  700. // being specialized in any of these cases.
  701. // If the value is already of the right kind and expression category, there's
  702. // nothing to do. Performing a conversion would decompose and rebuild tuples
  703. // and structs, so it's important that we bail out early in this case.
  704. if (value_type_id == target.type_id) {
  705. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  706. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  707. return value_id;
  708. }
  709. // If the source is an initializing expression, we may be able to pull a
  710. // value right out of it.
  711. if (value_cat == SemIR::ExprCategory::Initializing &&
  712. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  713. return context.AddInst<SemIR::ValueOfInitializer>(
  714. loc_id, {.type_id = value_type_id, .init_id = value_id});
  715. }
  716. }
  717. // T explicitly converts to U if T is compatible with U.
  718. if (target.kind == ConversionTarget::Kind::ExplicitAs &&
  719. target.type_id != value_type_id) {
  720. auto target_base_id = GetCompatibleBaseType(context, target.type_id);
  721. auto value_base_id = GetCompatibleBaseType(context, value_type_id);
  722. if (target_base_id == value_base_id) {
  723. // For a struct or tuple literal, perform a category conversion if
  724. // necessary.
  725. if (SemIR::GetExprCategory(context.sem_ir(), value_id) ==
  726. SemIR::ExprCategory::Mixed) {
  727. value_id = PerformBuiltinConversion(
  728. context, loc_id, value_id,
  729. ConversionTarget{.kind = ConversionTarget::Value,
  730. .type_id = value_type_id});
  731. }
  732. return context.AddInst<SemIR::AsCompatible>(
  733. loc_id, {.type_id = target.type_id, .source_id = value_id});
  734. }
  735. }
  736. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  737. // converts to Ui.
  738. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  739. if (auto src_tuple_type =
  740. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  741. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  742. value_id, target);
  743. }
  744. }
  745. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  746. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  747. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  748. // to Ui.
  749. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  750. if (auto src_struct_type =
  751. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  752. return ConvertStructToStruct(context, *src_struct_type,
  753. *target_struct_type, value_id, target);
  754. }
  755. }
  756. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  757. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  758. if (auto src_tuple_type =
  759. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  760. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  761. value_id, target);
  762. }
  763. }
  764. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  765. // if it converts to the struct type that is the class's representation type
  766. // (a struct with the same fields as the class, plus a base field where
  767. // relevant).
  768. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  769. if (auto src_struct_type =
  770. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  771. if (!context.classes()
  772. .Get(target_class_type->class_id)
  773. .adapt_id.is_valid()) {
  774. return ConvertStructToClass(context, *src_struct_type,
  775. *target_class_type, value_id, target);
  776. }
  777. }
  778. // An expression of type T converts to U if T is a class derived from U.
  779. if (auto path =
  780. ComputeInheritancePath(context, value_type_id, target.type_id);
  781. path && !path->empty()) {
  782. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  783. }
  784. }
  785. // A pointer T* converts to U* if T is a class derived from U.
  786. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  787. if (auto src_pointer_type =
  788. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  789. if (auto path =
  790. ComputeInheritancePath(context, src_pointer_type->pointee_id,
  791. target_pointer_type->pointee_id);
  792. path && !path->empty()) {
  793. return ConvertDerivedPointerToBasePointer(
  794. context, loc_id, *src_pointer_type, target.type_id, value_id,
  795. *path);
  796. }
  797. }
  798. }
  799. if (target.type_id == SemIR::TypeType::SingletonTypeId) {
  800. // A tuple of types converts to type `type`.
  801. // TODO: This should apply even for non-literal tuples.
  802. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  803. llvm::SmallVector<SemIR::TypeId> type_ids;
  804. for (auto tuple_inst_id :
  805. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  806. // TODO: This call recurses back into conversion. Switch to an
  807. // iterative approach.
  808. type_ids.push_back(ExprAsType(context, loc_id, tuple_inst_id).type_id);
  809. }
  810. auto tuple_type_id = context.GetTupleType(type_ids);
  811. return sem_ir.types().GetInstId(tuple_type_id);
  812. }
  813. // `{}` converts to `{} as type`.
  814. // TODO: This conversion should also be performed for a non-literal value
  815. // of type `{}`.
  816. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  817. struct_literal &&
  818. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  819. value_id = sem_ir.types().GetInstId(value_type_id);
  820. }
  821. // Facet type conversions: a value T of facet type F1 can be implicitly
  822. // converted to facet type F2 if T satisfies the requirements of F2.
  823. //
  824. // TODO: Support this conversion in general. For now we only support it in
  825. // the case where F1 is a facet type and F2 is `type`.
  826. // TODO: Support converting tuple and struct values to facet types,
  827. // combining the above conversions and this one in a single conversion.
  828. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  829. return context.AddInst<SemIR::FacetAccessType>(
  830. loc_id, {.type_id = target.type_id, .facet_value_inst_id = value_id});
  831. }
  832. }
  833. // No builtin conversion applies.
  834. return value_id;
  835. }
  836. // Given a value expression, form a corresponding initializer that copies from
  837. // that value, if it is possible to do so.
  838. static auto PerformCopy(Context& context, SemIR::InstId expr_id)
  839. -> SemIR::InstId {
  840. auto expr = context.insts().Get(expr_id);
  841. auto type_id = expr.type_id();
  842. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  843. return SemIR::ErrorInst::SingletonInstId;
  844. }
  845. // TODO: Directly track on the value representation whether it's a copy of
  846. // the object representation.
  847. auto value_rep = SemIR::ValueRepr::ForType(context.sem_ir(), type_id);
  848. if (value_rep.kind == SemIR::ValueRepr::Copy &&
  849. value_rep.aggregate_kind == SemIR::ValueRepr::NotAggregate &&
  850. value_rep.type_id == type_id) {
  851. // For by-value scalar types, no explicit action is required. Initializing
  852. // from a value expression is treated as copying the value.
  853. return expr_id;
  854. }
  855. // TODO: We don't yet have rules for whether and when a class type is
  856. // copyable, or how to perform the copy.
  857. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  858. "cannot copy value of type {0}", TypeOfInstId);
  859. context.emitter().Emit(expr_id, CopyOfUncopyableType, expr_id);
  860. return SemIR::ErrorInst::SingletonInstId;
  861. }
  862. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  863. ConversionTarget target) -> SemIR::InstId {
  864. auto& sem_ir = context.sem_ir();
  865. auto orig_expr_id = expr_id;
  866. // Start by making sure both sides are valid. If any part is invalid, the
  867. // result is invalid and we shouldn't error.
  868. if (sem_ir.insts().Get(expr_id).type_id() ==
  869. SemIR::ErrorInst::SingletonTypeId ||
  870. target.type_id == SemIR::ErrorInst::SingletonTypeId) {
  871. return SemIR::ErrorInst::SingletonInstId;
  872. }
  873. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  874. // TODO: We currently encounter this for use of namespaces and functions.
  875. // We should provide a better diagnostic for inappropriate use of
  876. // namespace names, and allow use of functions as values.
  877. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  878. "expression cannot be used as a value");
  879. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  880. return SemIR::ErrorInst::SingletonInstId;
  881. }
  882. // We can only perform initialization for complete types.
  883. if (!context.TryToCompleteType(
  884. target.type_id,
  885. [&] {
  886. CARBON_CHECK(!target.is_initializer(),
  887. "Initialization of incomplete types is expected to be "
  888. "caught elsewhere.");
  889. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  890. "forming value of incomplete type {0}",
  891. SemIR::TypeId);
  892. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  893. "invalid use of incomplete type {0}",
  894. SemIR::TypeId);
  895. return context.emitter().Build(
  896. loc_id,
  897. target.kind == ConversionTarget::Value
  898. ? IncompleteTypeInValueConversion
  899. : IncompleteTypeInConversion,
  900. target.type_id);
  901. },
  902. [&] {
  903. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  904. "initialization of abstract type {0}",
  905. SemIR::TypeId);
  906. if (!target.is_initializer()) {
  907. return context.emitter().BuildSuppressed();
  908. }
  909. return context.emitter().Build(loc_id, AbstractTypeInInit,
  910. target.type_id);
  911. })) {
  912. return SemIR::ErrorInst::SingletonInstId;
  913. }
  914. // Check whether any builtin conversion applies.
  915. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target);
  916. if (expr_id == SemIR::ErrorInst::SingletonInstId) {
  917. return expr_id;
  918. }
  919. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  920. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  921. SemIR::InstId interface_args[] = {
  922. context.types().GetInstId(target.type_id)};
  923. Operator op = {
  924. .interface_name = target.kind == ConversionTarget::ExplicitAs
  925. ? llvm::StringLiteral("As")
  926. : llvm::StringLiteral("ImplicitAs"),
  927. .interface_args_ref = interface_args,
  928. .op_name = "Convert",
  929. };
  930. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  931. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  932. "cannot implicitly convert from {0} to {1}",
  933. TypeOfInstId, SemIR::TypeId);
  934. CARBON_DIAGNOSTIC(ExplicitAsConversionFailure, Error,
  935. "cannot convert from {0} to {1} with `as`",
  936. TypeOfInstId, SemIR::TypeId);
  937. return context.emitter().Build(loc_id,
  938. target.kind == ConversionTarget::ExplicitAs
  939. ? ExplicitAsConversionFailure
  940. : ImplicitAsConversionFailure,
  941. expr_id, target.type_id);
  942. });
  943. // Pull a value directly out of the initializer if possible and wanted.
  944. if (expr_id != SemIR::ErrorInst::SingletonInstId &&
  945. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  946. expr_id = context.AddInst<SemIR::ValueOfInitializer>(
  947. loc_id, {.type_id = target.type_id, .init_id = expr_id});
  948. }
  949. }
  950. // Track that we performed a type conversion, if we did so.
  951. if (orig_expr_id != expr_id) {
  952. expr_id =
  953. context.AddInst<SemIR::Converted>(loc_id, {.type_id = target.type_id,
  954. .original_id = orig_expr_id,
  955. .result_id = expr_id});
  956. }
  957. // For `as`, don't perform any value category conversions. In particular, an
  958. // identity conversion shouldn't change the expression category.
  959. if (target.kind == ConversionTarget::ExplicitAs) {
  960. return expr_id;
  961. }
  962. // Now perform any necessary value category conversions.
  963. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  964. case SemIR::ExprCategory::NotExpr:
  965. case SemIR::ExprCategory::Mixed:
  966. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  967. sem_ir.insts().Get(expr_id));
  968. case SemIR::ExprCategory::Error:
  969. return SemIR::ErrorInst::SingletonInstId;
  970. case SemIR::ExprCategory::Initializing:
  971. if (target.is_initializer()) {
  972. if (orig_expr_id == expr_id) {
  973. // Don't fill in the return slot if we created the expression through
  974. // a conversion. In that case, we will have created it with the
  975. // target already set.
  976. // TODO: Find a better way to track whether we need to do this.
  977. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  978. *target.init_block);
  979. }
  980. break;
  981. }
  982. // Commit to using a temporary for this initializing expression.
  983. // TODO: Don't create a temporary if the initializing representation
  984. // is already a value representation.
  985. expr_id = FinalizeTemporary(context, expr_id,
  986. target.kind == ConversionTarget::Discarded);
  987. // We now have an ephemeral reference.
  988. [[fallthrough]];
  989. case SemIR::ExprCategory::DurableRef:
  990. case SemIR::ExprCategory::EphemeralRef:
  991. // If a reference expression is an acceptable result, we're done.
  992. if (target.kind == ConversionTarget::ValueOrRef ||
  993. target.kind == ConversionTarget::Discarded) {
  994. break;
  995. }
  996. // If we have a reference and don't want one, form a value binding.
  997. // TODO: Support types with custom value representations.
  998. expr_id = context.AddInst<SemIR::BindValue>(
  999. context.insts().GetLocId(expr_id),
  1000. {.type_id = target.type_id, .value_id = expr_id});
  1001. // We now have a value expression.
  1002. [[fallthrough]];
  1003. case SemIR::ExprCategory::Value:
  1004. // When initializing from a value, perform a copy.
  1005. if (target.is_initializer()) {
  1006. expr_id = PerformCopy(context, expr_id);
  1007. }
  1008. break;
  1009. }
  1010. // Perform a final destination store, if necessary.
  1011. if (target.kind == ConversionTarget::FullInitializer) {
  1012. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1013. init_rep.kind == SemIR::InitRepr::ByCopy) {
  1014. target.init_block->InsertHere();
  1015. expr_id = context.AddInst<SemIR::InitializeFrom>(
  1016. loc_id, {.type_id = target.type_id,
  1017. .src_id = expr_id,
  1018. .dest_id = target.init_id});
  1019. }
  1020. }
  1021. return expr_id;
  1022. }
  1023. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1024. SemIR::InstId value_id) -> SemIR::InstId {
  1025. PendingBlock target_block(context);
  1026. return Convert(context, loc_id, value_id,
  1027. {.kind = ConversionTarget::Initializer,
  1028. .type_id = context.insts().Get(target_id).type_id(),
  1029. .init_id = target_id,
  1030. .init_block = &target_block});
  1031. }
  1032. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1033. -> SemIR::InstId {
  1034. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1035. {.kind = ConversionTarget::Value,
  1036. .type_id = context.insts().Get(expr_id).type_id()});
  1037. }
  1038. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1039. -> SemIR::InstId {
  1040. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1041. {.kind = ConversionTarget::ValueOrRef,
  1042. .type_id = context.insts().Get(expr_id).type_id()});
  1043. }
  1044. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1045. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1046. -> SemIR::InstId {
  1047. return Convert(context, loc_id, expr_id,
  1048. {.kind = ConversionTarget::Value, .type_id = type_id});
  1049. }
  1050. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1051. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1052. -> SemIR::InstId {
  1053. return Convert(context, loc_id, expr_id,
  1054. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1055. }
  1056. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1057. SemIR::InstId value_id) -> SemIR::InstId {
  1058. return ConvertToValueOfType(
  1059. context, loc_id, value_id,
  1060. context.GetBuiltinType(SemIR::BuiltinInstKind::BoolType));
  1061. }
  1062. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1063. SemIR::InstId value_id, SemIR::TypeId type_id)
  1064. -> SemIR::InstId {
  1065. return Convert(context, as_node, value_id,
  1066. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  1067. }
  1068. // TODO: Consider moving this to pattern_match.h.
  1069. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1070. SemIR::InstId self_id,
  1071. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1072. SemIR::InstId return_slot_arg_id,
  1073. const SemIR::Function& callee,
  1074. SemIR::SpecificId callee_specific_id)
  1075. -> SemIR::InstBlockId {
  1076. // The callee reference can be invalidated by conversions, so ensure all reads
  1077. // from it are done before conversion calls.
  1078. auto callee_decl_id = callee.latest_decl_id();
  1079. auto implicit_param_patterns =
  1080. context.inst_blocks().GetOrEmpty(callee.implicit_param_patterns_id);
  1081. auto param_patterns =
  1082. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1083. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1084. // The caller should have ensured this callee has the right arity.
  1085. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1086. // Find self parameter pattern.
  1087. // TODO: Do this during initial traversal of implicit params.
  1088. auto self_param_id = SemIR::InstId::Invalid;
  1089. for (auto implicit_param_id : implicit_param_patterns) {
  1090. if (SemIR::Function::GetNameFromPatternId(
  1091. context.sem_ir(), implicit_param_id) == SemIR::NameId::SelfValue) {
  1092. CARBON_CHECK(!self_param_id.is_valid());
  1093. self_param_id = implicit_param_id;
  1094. }
  1095. }
  1096. if (self_param_id.is_valid() && !self_id.is_valid()) {
  1097. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1098. "missing object argument in method call");
  1099. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1100. context.emitter()
  1101. .Build(call_loc_id, MissingObjectInMethodCall)
  1102. .Note(callee_decl_id, InCallToFunction)
  1103. .Emit();
  1104. self_id = SemIR::ErrorInst::SingletonInstId;
  1105. }
  1106. return CallerPatternMatch(context, callee_specific_id, self_param_id,
  1107. callee.param_patterns_id, return_slot_pattern_id,
  1108. self_id, arg_refs, return_slot_arg_id);
  1109. }
  1110. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id)
  1111. -> TypeExpr {
  1112. auto type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1113. SemIR::TypeType::SingletonTypeId);
  1114. if (type_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1115. return {.inst_id = type_inst_id,
  1116. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1117. }
  1118. auto type_const_id = context.constant_values().Get(type_inst_id);
  1119. if (!type_const_id.is_constant()) {
  1120. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1121. "cannot evaluate type expression");
  1122. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1123. return {.inst_id = SemIR::ErrorInst::SingletonInstId,
  1124. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1125. }
  1126. return {.inst_id = type_inst_id,
  1127. .type_id = context.GetTypeIdForTypeConstant(type_const_id)};
  1128. }
  1129. } // namespace Carbon::Check