convert.cpp 52 KB

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