convert.cpp 47 KB

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