convert.cpp 54 KB

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