convert.cpp 51 KB

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