convert.cpp 48 KB

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