convert.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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 "common/map.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/context.h"
  12. #include "toolchain/check/diagnostic_helpers.h"
  13. #include "toolchain/check/eval.h"
  14. #include "toolchain/check/impl_lookup.h"
  15. #include "toolchain/check/inst.h"
  16. #include "toolchain/check/operator.h"
  17. #include "toolchain/check/pattern_match.h"
  18. #include "toolchain/check/type.h"
  19. #include "toolchain/check/type_completion.h"
  20. #include "toolchain/diagnostics/format_providers.h"
  21. #include "toolchain/sem_ir/copy_on_write_block.h"
  22. #include "toolchain/sem_ir/file.h"
  23. #include "toolchain/sem_ir/generic.h"
  24. #include "toolchain/sem_ir/ids.h"
  25. #include "toolchain/sem_ir/inst.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. // TODO: This contains a lot of recursion. Consider removing it in order to
  28. // prevent accidents.
  29. // NOLINTBEGIN(misc-no-recursion)
  30. namespace Carbon::Check {
  31. // Given an initializing expression, find its return slot argument. Returns
  32. // `None` if there is no return slot, because the initialization is not
  33. // performed in place.
  34. static auto FindReturnSlotArgForInitializer(SemIR::File& sem_ir,
  35. SemIR::InstId init_id)
  36. -> SemIR::InstId {
  37. while (true) {
  38. SemIR::Inst init_untyped = sem_ir.insts().Get(init_id);
  39. CARBON_KIND_SWITCH(init_untyped) {
  40. case CARBON_KIND(SemIR::AsCompatible init): {
  41. init_id = init.source_id;
  42. continue;
  43. }
  44. case CARBON_KIND(SemIR::Converted init): {
  45. init_id = init.result_id;
  46. continue;
  47. }
  48. case CARBON_KIND(SemIR::ArrayInit init): {
  49. return init.dest_id;
  50. }
  51. case CARBON_KIND(SemIR::ClassInit init): {
  52. return init.dest_id;
  53. }
  54. case CARBON_KIND(SemIR::StructInit init): {
  55. return init.dest_id;
  56. }
  57. case CARBON_KIND(SemIR::TupleInit init): {
  58. return init.dest_id;
  59. }
  60. case CARBON_KIND(SemIR::InitializeFrom init): {
  61. return init.dest_id;
  62. }
  63. case CARBON_KIND(SemIR::Call call): {
  64. if (!SemIR::ReturnTypeInfo::ForType(sem_ir, call.type_id)
  65. .has_return_slot()) {
  66. return SemIR::InstId::None;
  67. }
  68. if (!call.args_id.has_value()) {
  69. // Argument initialization failed, so we have no return slot.
  70. return SemIR::InstId::None;
  71. }
  72. return sem_ir.inst_blocks().Get(call.args_id).back();
  73. }
  74. default:
  75. CARBON_FATAL("Initialization from unexpected inst {0}", init_untyped);
  76. }
  77. }
  78. }
  79. // Marks the initializer `init_id` as initializing `target_id`.
  80. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  81. SemIR::InstId target_id,
  82. PendingBlock& target_block) -> void {
  83. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  84. if (return_slot_arg_id.has_value()) {
  85. // Replace the temporary in the return slot with a reference to our target.
  86. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  87. SemIR::TemporaryStorage::Kind,
  88. "Return slot for initializer does not contain a temporary; "
  89. "initialized multiple times? Have {0}",
  90. sem_ir.insts().Get(return_slot_arg_id));
  91. target_block.MergeReplacing(return_slot_arg_id, target_id);
  92. }
  93. }
  94. // Commits to using a temporary to store the result of the initializing
  95. // expression described by `init_id`, and returns the location of the
  96. // temporary. If `discarded` is `true`, the result is discarded, and no
  97. // temporary will be created if possible; if no temporary is created, the
  98. // return value will be `SemIR::InstId::None`.
  99. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  100. bool discarded) -> SemIR::InstId {
  101. auto& sem_ir = context.sem_ir();
  102. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  103. if (return_slot_arg_id.has_value()) {
  104. // The return slot should already have a materialized temporary in it.
  105. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  106. SemIR::TemporaryStorage::Kind,
  107. "Return slot for initializer does not contain a temporary; "
  108. "initialized multiple times? Have {0}",
  109. sem_ir.insts().Get(return_slot_arg_id));
  110. auto init = sem_ir.insts().Get(init_id);
  111. return AddInst<SemIR::Temporary>(context, sem_ir.insts().GetLocId(init_id),
  112. {.type_id = init.type_id(),
  113. .storage_id = return_slot_arg_id,
  114. .init_id = init_id});
  115. }
  116. if (discarded) {
  117. // Don't invent a temporary that we're going to discard.
  118. return SemIR::InstId::None;
  119. }
  120. // The initializer has no return slot, but we want to produce a temporary
  121. // object. Materialize one now.
  122. // TODO: Consider using `None` to mean that we immediately materialize and
  123. // initialize a temporary, rather than two separate instructions.
  124. auto init = sem_ir.insts().Get(init_id);
  125. auto loc_id = sem_ir.insts().GetLocId(init_id);
  126. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  127. context, loc_id, {.type_id = init.type_id()});
  128. return AddInst<SemIR::Temporary>(context, loc_id,
  129. {.type_id = init.type_id(),
  130. .storage_id = temporary_id,
  131. .init_id = init_id});
  132. }
  133. // Materialize a temporary to hold the result of the given expression if it is
  134. // an initializing expression.
  135. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  136. -> SemIR::InstId {
  137. if (GetExprCategory(context.sem_ir(), expr_id) ==
  138. SemIR::ExprCategory::Initializing) {
  139. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  140. }
  141. return expr_id;
  142. }
  143. // Helper to allow `MakeElementAccessInst` to call `AddInst` with either a
  144. // `PendingBlock` or `Context` (defined in `inst.h`).
  145. template <typename AccessInstT>
  146. static auto AddInst(PendingBlock& block, SemIR::LocId loc_id, AccessInstT inst)
  147. -> SemIR::InstId {
  148. return block.AddInst<AccessInstT>(loc_id, inst);
  149. }
  150. // Creates and adds an instruction to perform element access into an aggregate.
  151. template <typename AccessInstT, typename InstBlockT>
  152. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  153. SemIR::InstId aggregate_id,
  154. SemIR::TypeId elem_type_id, InstBlockT& block,
  155. size_t i) -> SemIR::InstId {
  156. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  157. // TODO: Add a new instruction kind for indexing an array at a constant
  158. // index so that we don't need an integer literal instruction here, and
  159. // remove this special case.
  160. auto index_id = block.template AddInst<SemIR::IntValue>(
  161. loc_id, {.type_id = GetSingletonType(
  162. context, SemIR::IntLiteralType::SingletonInstId),
  163. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  164. return AddInst<AccessInstT>(block, loc_id,
  165. {elem_type_id, aggregate_id, index_id});
  166. } else {
  167. return AddInst<AccessInstT>(
  168. block, loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  169. }
  170. }
  171. // Converts an element of one aggregate so that it can be used as an element of
  172. // another aggregate.
  173. //
  174. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  175. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  176. // kind of instruction used to access the source element.
  177. //
  178. // For the target: `kind` is the kind of conversion or initialization,
  179. // `target_elem_type` is the element type. For initialization, `target_id` is
  180. // the destination, `target_block` is a pending block for target location
  181. // calculations that will be spliced as the return slot of the initializer if
  182. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  183. // kind of instruction used to access the destination element.
  184. template <typename SourceAccessInstT, typename TargetAccessInstT>
  185. static auto ConvertAggregateElement(
  186. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  187. SemIR::TypeId src_elem_type,
  188. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  189. ConversionTarget::Kind kind, SemIR::InstId target_id,
  190. SemIR::TypeId target_elem_type, PendingBlock* target_block,
  191. size_t src_field_index, size_t target_field_index) -> SemIR::InstId {
  192. // Compute the location of the source element. This goes into the current code
  193. // block, not into the target block.
  194. // TODO: Ideally we would discard this instruction if it's unused.
  195. auto src_elem_id = !src_literal_elems.empty()
  196. ? src_literal_elems[src_field_index]
  197. : MakeElementAccessInst<SourceAccessInstT>(
  198. context, loc_id, src_id, src_elem_type, context,
  199. src_field_index);
  200. // If we're performing a conversion rather than an initialization, we won't
  201. // have or need a target.
  202. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  203. if (!target.is_initializer()) {
  204. return Convert(context, loc_id, src_elem_id, target);
  205. }
  206. // Compute the location of the target element and initialize it.
  207. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  208. target.init_block = target_block;
  209. target.init_id = MakeElementAccessInst<TargetAccessInstT>(
  210. context, loc_id, target_id, target_elem_type, *target_block,
  211. target_field_index);
  212. return Convert(context, loc_id, src_elem_id, target);
  213. }
  214. // Performs a conversion from a tuple to an array type. This function only
  215. // converts the type, and does not perform a final conversion to the requested
  216. // expression category.
  217. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  218. SemIR::ArrayType array_type,
  219. SemIR::InstId value_id, ConversionTarget target)
  220. -> SemIR::InstId {
  221. auto& sem_ir = context.sem_ir();
  222. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  223. auto value = sem_ir.insts().Get(value_id);
  224. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  225. // If we're initializing from a tuple literal, we will use its elements
  226. // directly. Otherwise, materialize a temporary if needed and index into the
  227. // result.
  228. llvm::ArrayRef<SemIR::InstId> literal_elems;
  229. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  230. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  231. } else {
  232. value_id = MaterializeIfInitializing(context, value_id);
  233. }
  234. // Check that the tuple is the right size.
  235. std::optional<uint64_t> array_bound =
  236. sem_ir.GetArrayBoundValue(array_type.bound_id);
  237. if (!array_bound) {
  238. // TODO: Should this fall back to using `ImplicitAs`?
  239. if (target.diagnose) {
  240. CARBON_DIAGNOSTIC(ArrayInitDependentBound, Error,
  241. "cannot initialize array with dependent bound from a "
  242. "list of initializers");
  243. context.emitter().Emit(value_loc_id, ArrayInitDependentBound);
  244. }
  245. return SemIR::ErrorInst::SingletonInstId;
  246. }
  247. if (tuple_elem_types.size() != array_bound) {
  248. if (target.diagnose) {
  249. CARBON_DIAGNOSTIC(ArrayInitFromLiteralArgCountMismatch, Error,
  250. "cannot initialize array of {0} element{0:s} from {1} "
  251. "initializer{1:s}",
  252. IntAsSelect, IntAsSelect);
  253. CARBON_DIAGNOSTIC(
  254. ArrayInitFromExprArgCountMismatch, Error,
  255. "cannot initialize array of {0} element{0:s} from tuple "
  256. "with {1} element{1:s}",
  257. IntAsSelect, IntAsSelect);
  258. context.emitter().Emit(value_loc_id,
  259. literal_elems.empty()
  260. ? ArrayInitFromExprArgCountMismatch
  261. : ArrayInitFromLiteralArgCountMismatch,
  262. *array_bound, tuple_elem_types.size());
  263. }
  264. return SemIR::ErrorInst::SingletonInstId;
  265. }
  266. PendingBlock target_block_storage(context);
  267. PendingBlock* target_block =
  268. target.init_block ? target.init_block : &target_block_storage;
  269. // Arrays are always initialized in-place. Allocate a temporary as the
  270. // destination for the array initialization if we weren't given one.
  271. SemIR::InstId return_slot_arg_id = target.init_id;
  272. if (!target.init_id.has_value()) {
  273. return_slot_arg_id = target_block->AddInst<SemIR::TemporaryStorage>(
  274. value_loc_id, {.type_id = target.type_id});
  275. }
  276. // Initialize each element of the array from the corresponding element of the
  277. // tuple.
  278. // TODO: Annotate diagnostics coming from here with the array element index,
  279. // if initializing from a tuple literal.
  280. llvm::SmallVector<SemIR::InstId> inits;
  281. inits.reserve(*array_bound + 1);
  282. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  283. // TODO: This call recurses back into conversion. Switch to an iterative
  284. // approach.
  285. auto init_id =
  286. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  287. context, value_loc_id, value_id, src_type_id, literal_elems,
  288. ConversionTarget::FullInitializer, return_slot_arg_id,
  289. array_type.element_type_id, target_block, i, i);
  290. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  291. return SemIR::ErrorInst::SingletonInstId;
  292. }
  293. inits.push_back(init_id);
  294. }
  295. // Flush the temporary here if we didn't insert it earlier, so we can add a
  296. // reference to the return slot.
  297. target_block->InsertHere();
  298. return AddInst<SemIR::ArrayInit>(context, value_loc_id,
  299. {.type_id = target.type_id,
  300. .inits_id = sem_ir.inst_blocks().Add(inits),
  301. .dest_id = return_slot_arg_id});
  302. }
  303. // Performs a conversion from a tuple to a tuple type. This function only
  304. // converts the type, and does not perform a final conversion to the requested
  305. // expression category.
  306. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  307. SemIR::TupleType dest_type,
  308. SemIR::InstId value_id, ConversionTarget target)
  309. -> SemIR::InstId {
  310. auto& sem_ir = context.sem_ir();
  311. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  312. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  313. auto value = sem_ir.insts().Get(value_id);
  314. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  315. // If we're initializing from a tuple literal, we will use its elements
  316. // directly. Otherwise, materialize a temporary if needed and index into the
  317. // result.
  318. llvm::ArrayRef<SemIR::InstId> literal_elems;
  319. auto literal_elems_id = SemIR::InstBlockId::None;
  320. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  321. literal_elems_id = tuple_literal->elements_id;
  322. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  323. } else {
  324. value_id = MaterializeIfInitializing(context, value_id);
  325. }
  326. // Check that the tuples are the same size.
  327. if (src_elem_types.size() != dest_elem_types.size()) {
  328. if (target.diagnose) {
  329. CARBON_DIAGNOSTIC(
  330. TupleInitElementCountMismatch, Error,
  331. "cannot initialize tuple of {0} element{0:s} from tuple "
  332. "with {1} element{1:s}",
  333. IntAsSelect, IntAsSelect);
  334. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  335. dest_elem_types.size(), src_elem_types.size());
  336. }
  337. return SemIR::ErrorInst::SingletonInstId;
  338. }
  339. // If we're forming an initializer, then we want an initializer for each
  340. // element. Otherwise, we want a value representation for each element.
  341. // Perform a final destination store if we're performing an in-place
  342. // initialization.
  343. bool is_init = target.is_initializer();
  344. ConversionTarget::Kind inner_kind =
  345. !is_init ? ConversionTarget::Value
  346. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  347. SemIR::InitRepr::InPlace
  348. ? ConversionTarget::FullInitializer
  349. : ConversionTarget::Initializer;
  350. // Initialize each element of the destination from the corresponding element
  351. // of the source.
  352. // TODO: Annotate diagnostics coming from here with the element index.
  353. auto new_block =
  354. literal_elems_id.has_value()
  355. ? SemIR::CopyOnWriteInstBlock(sem_ir, literal_elems_id)
  356. : SemIR::CopyOnWriteInstBlock(
  357. sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  358. src_elem_types.size()});
  359. for (auto [i, src_type_id, dest_type_id] :
  360. llvm::enumerate(src_elem_types, dest_elem_types)) {
  361. // TODO: This call recurses back into conversion. Switch to an iterative
  362. // approach.
  363. auto init_id =
  364. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  365. context, value_loc_id, value_id, src_type_id, literal_elems,
  366. inner_kind, target.init_id, dest_type_id, target.init_block, i, i);
  367. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  368. return SemIR::ErrorInst::SingletonInstId;
  369. }
  370. new_block.Set(i, init_id);
  371. }
  372. if (is_init) {
  373. target.init_block->InsertHere();
  374. return AddInst<SemIR::TupleInit>(context, value_loc_id,
  375. {.type_id = target.type_id,
  376. .elements_id = new_block.id(),
  377. .dest_id = target.init_id});
  378. } else {
  379. return AddInst<SemIR::TupleValue>(
  380. context, value_loc_id,
  381. {.type_id = target.type_id, .elements_id = new_block.id()});
  382. }
  383. }
  384. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  385. template <typename TargetAccessInstT>
  386. static auto ConvertStructToStructOrClass(Context& context,
  387. SemIR::StructType src_type,
  388. SemIR::StructType dest_type,
  389. SemIR::InstId value_id,
  390. ConversionTarget target)
  391. -> SemIR::InstId {
  392. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  393. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  394. constexpr bool ToClass =
  395. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  396. auto& sem_ir = context.sem_ir();
  397. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  398. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  399. bool dest_has_vptr = !dest_elem_fields.empty() &&
  400. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  401. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  402. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  403. auto value = sem_ir.insts().Get(value_id);
  404. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  405. // If we're initializing from a struct literal, we will use its elements
  406. // directly. Otherwise, materialize a temporary if needed and index into the
  407. // result.
  408. llvm::ArrayRef<SemIR::InstId> literal_elems;
  409. auto literal_elems_id = SemIR::InstBlockId::None;
  410. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  411. literal_elems_id = struct_literal->elements_id;
  412. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  413. } else {
  414. value_id = MaterializeIfInitializing(context, value_id);
  415. }
  416. // Check that the structs are the same size.
  417. // TODO: If not, include the name of the first source field that doesn't
  418. // exist in the destination or vice versa in the diagnostic.
  419. if (src_elem_fields.size() != dest_elem_fields_size) {
  420. if (target.diagnose) {
  421. CARBON_DIAGNOSTIC(
  422. StructInitElementCountMismatch, Error,
  423. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  424. "with {2} field{2:s}",
  425. BoolAsSelect, IntAsSelect, IntAsSelect);
  426. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  427. ToClass, dest_elem_fields_size,
  428. src_elem_fields.size());
  429. }
  430. return SemIR::ErrorInst::SingletonInstId;
  431. }
  432. // Prepare to look up fields in the source by index.
  433. Map<SemIR::NameId, int32_t> src_field_indexes;
  434. if (src_type.fields_id != dest_type.fields_id) {
  435. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  436. auto result = src_field_indexes.Insert(field.name_id, i);
  437. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  438. }
  439. }
  440. // If we're forming an initializer, then we want an initializer for each
  441. // element. Otherwise, we want a value representation for each element.
  442. // Perform a final destination store if we're performing an in-place
  443. // initialization.
  444. bool is_init = target.is_initializer();
  445. ConversionTarget::Kind inner_kind =
  446. !is_init ? ConversionTarget::Value
  447. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  448. SemIR::InitRepr::InPlace
  449. ? ConversionTarget::FullInitializer
  450. : ConversionTarget::Initializer;
  451. // Initialize each element of the destination from the corresponding element
  452. // of the source.
  453. // TODO: Annotate diagnostics coming from here with the element index.
  454. auto new_block =
  455. literal_elems_id.has_value() && !dest_has_vptr
  456. ? SemIR::CopyOnWriteInstBlock(sem_ir, literal_elems_id)
  457. : SemIR::CopyOnWriteInstBlock(
  458. sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  459. dest_elem_fields.size()});
  460. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  461. if (dest_field.name_id == SemIR::NameId::Vptr) {
  462. // CARBON_CHECK(ToClass, "Only classes should have vptrs.");
  463. auto dest_id =
  464. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  465. {.type_id = dest_field.type_id,
  466. .base_id = target.init_id,
  467. .index = SemIR::ElementIndex(i)});
  468. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  469. context, value_loc_id, {.type_id = dest_field.type_id});
  470. auto init_id =
  471. AddInst<SemIR::InitializeFrom>(context, value_loc_id,
  472. {.type_id = dest_field.type_id,
  473. .src_id = vtable_ptr_id,
  474. .dest_id = dest_id});
  475. new_block.Set(i, init_id);
  476. continue;
  477. }
  478. // Find the matching source field.
  479. auto src_field_index = i;
  480. if (src_type.fields_id != dest_type.fields_id) {
  481. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  482. src_field_index = lookup.value();
  483. } else {
  484. if (target.diagnose) {
  485. if (literal_elems_id.has_value()) {
  486. CARBON_DIAGNOSTIC(
  487. StructInitMissingFieldInLiteral, Error,
  488. "missing value for field `{0}` in struct initialization",
  489. SemIR::NameId);
  490. context.emitter().Emit(value_loc_id,
  491. StructInitMissingFieldInLiteral,
  492. dest_field.name_id);
  493. } else {
  494. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  495. "cannot convert from struct type {0} to {1}: "
  496. "missing field `{2}` in source type",
  497. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  498. context.emitter().Emit(value_loc_id,
  499. StructInitMissingFieldInConversion, value_id,
  500. target.type_id, dest_field.name_id);
  501. }
  502. }
  503. return SemIR::ErrorInst::SingletonInstId;
  504. }
  505. }
  506. auto src_field = src_elem_fields[src_field_index];
  507. // TODO: This call recurses back into conversion. Switch to an iterative
  508. // approach.
  509. auto init_id =
  510. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  511. context, value_loc_id, value_id, src_field.type_id, literal_elems,
  512. inner_kind, target.init_id, dest_field.type_id, target.init_block,
  513. src_field_index, src_field_index + dest_vptr_offset);
  514. if (init_id == SemIR::ErrorInst::SingletonInstId) {
  515. return SemIR::ErrorInst::SingletonInstId;
  516. }
  517. new_block.Set(i, init_id);
  518. }
  519. if (ToClass) {
  520. target.init_block->InsertHere();
  521. CARBON_CHECK(is_init,
  522. "Converting directly to a class value is not supported");
  523. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  524. {.type_id = target.type_id,
  525. .elements_id = new_block.id(),
  526. .dest_id = target.init_id});
  527. } else if (is_init) {
  528. target.init_block->InsertHere();
  529. return AddInst<SemIR::StructInit>(context, value_loc_id,
  530. {.type_id = target.type_id,
  531. .elements_id = new_block.id(),
  532. .dest_id = target.init_id});
  533. } else {
  534. return AddInst<SemIR::StructValue>(
  535. context, value_loc_id,
  536. {.type_id = target.type_id, .elements_id = new_block.id()});
  537. }
  538. }
  539. // Performs a conversion from a struct to a struct type. This function only
  540. // converts the type, and does not perform a final conversion to the requested
  541. // expression category.
  542. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  543. SemIR::StructType dest_type,
  544. SemIR::InstId value_id,
  545. ConversionTarget target) -> SemIR::InstId {
  546. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  547. context, src_type, dest_type, value_id, target);
  548. }
  549. // Performs a conversion from a struct to a class type. This function only
  550. // converts the type, and does not perform a final conversion to the requested
  551. // expression category.
  552. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  553. SemIR::ClassType dest_type,
  554. SemIR::InstId value_id,
  555. ConversionTarget target) -> SemIR::InstId {
  556. PendingBlock target_block(context);
  557. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  558. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  559. auto object_repr_id =
  560. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  561. if (object_repr_id == SemIR::ErrorInst::SingletonTypeId) {
  562. return SemIR::ErrorInst::SingletonInstId;
  563. }
  564. auto dest_struct_type =
  565. context.types().GetAs<SemIR::StructType>(object_repr_id);
  566. // If we're trying to create a class value, form a temporary for the value to
  567. // point to.
  568. bool need_temporary = !target.is_initializer();
  569. if (need_temporary) {
  570. target.kind = ConversionTarget::Initializer;
  571. target.init_block = &target_block;
  572. target.init_id = target_block.AddInst<SemIR::TemporaryStorage>(
  573. context.insts().GetLocId(value_id), {.type_id = target.type_id});
  574. }
  575. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  576. context, src_type, dest_struct_type, value_id, target);
  577. if (need_temporary) {
  578. target_block.InsertHere();
  579. result_id =
  580. AddInst<SemIR::Temporary>(context, context.insts().GetLocId(value_id),
  581. {.type_id = target.type_id,
  582. .storage_id = target.init_id,
  583. .init_id = result_id});
  584. }
  585. return result_id;
  586. }
  587. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  588. // in order from derived to base.
  589. using InheritancePath =
  590. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  591. // Computes the inheritance path from class `derived_id` to class `base_id`.
  592. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  593. static auto ComputeInheritancePath(Context& context, SemIRLoc loc,
  594. SemIR::TypeId derived_id,
  595. SemIR::TypeId base_id)
  596. -> std::optional<InheritancePath> {
  597. // We intend for NRVO to be applied to `result`. All `return` statements in
  598. // this function should `return result;`.
  599. std::optional<InheritancePath> result(std::in_place);
  600. if (!TryToCompleteType(context, derived_id, loc)) {
  601. // TODO: Should we give an error here? If we don't, and there is an
  602. // inheritance path when the class is defined, we may have a coherence
  603. // problem.
  604. result = std::nullopt;
  605. return result;
  606. }
  607. while (derived_id != base_id) {
  608. auto derived_class_type =
  609. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  610. if (!derived_class_type) {
  611. result = std::nullopt;
  612. break;
  613. }
  614. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  615. auto base_type_id = derived_class.GetBaseType(
  616. context.sem_ir(), derived_class_type->specific_id);
  617. if (!base_type_id.has_value()) {
  618. result = std::nullopt;
  619. break;
  620. }
  621. result->push_back({derived_class.base_id, base_type_id});
  622. derived_id = base_type_id;
  623. }
  624. return result;
  625. }
  626. // Performs a conversion from a derived class value or reference to a base class
  627. // value or reference.
  628. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  629. SemIR::InstId value_id,
  630. const InheritancePath& path) -> SemIR::InstId {
  631. // Materialize a temporary if necessary.
  632. value_id = ConvertToValueOrRefExpr(context, value_id);
  633. // Add a series of `.base` accesses.
  634. for (auto [base_id, base_type_id] : path) {
  635. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  636. value_id = AddInst<SemIR::ClassElementAccess>(context, loc_id,
  637. {.type_id = base_type_id,
  638. .base_id = value_id,
  639. .index = base_decl.index});
  640. }
  641. return value_id;
  642. }
  643. // Performs a conversion from a derived class pointer to a base class pointer.
  644. static auto ConvertDerivedPointerToBasePointer(
  645. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  646. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  647. const InheritancePath& path) -> SemIR::InstId {
  648. // Form `*p`.
  649. ptr_id = ConvertToValueExpr(context, ptr_id);
  650. auto ref_id = AddInst<SemIR::Deref>(
  651. context, loc_id,
  652. {.type_id = src_ptr_type.pointee_id, .pointer_id = ptr_id});
  653. // Convert as a reference expression.
  654. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  655. // Take the address.
  656. return AddInst<SemIR::AddrOf>(
  657. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  658. }
  659. // Returns whether `category` is a valid expression category to produce as a
  660. // result of a conversion with kind `target_kind`, or at most needs a temporary
  661. // to be materialized.
  662. static auto IsValidExprCategoryForConversionTarget(
  663. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  664. switch (target_kind) {
  665. case ConversionTarget::Value:
  666. return category == SemIR::ExprCategory::Value;
  667. case ConversionTarget::ValueOrRef:
  668. case ConversionTarget::Discarded:
  669. return category == SemIR::ExprCategory::Value ||
  670. category == SemIR::ExprCategory::DurableRef ||
  671. category == SemIR::ExprCategory::EphemeralRef ||
  672. category == SemIR::ExprCategory::Initializing;
  673. case ConversionTarget::ExplicitAs:
  674. return true;
  675. case ConversionTarget::Initializer:
  676. case ConversionTarget::FullInitializer:
  677. return category == SemIR::ExprCategory::Initializing;
  678. }
  679. }
  680. // Determines whether the initialization representation of the type is a copy of
  681. // the value representation.
  682. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  683. SemIR::TypeId type_id) -> bool {
  684. // The initializing representation is a copy of the value representation if
  685. // they're both copies of the object representation.
  686. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  687. SemIR::ValueRepr::ForType(sem_ir, type_id)
  688. .IsCopyOfObjectRepr(sem_ir, type_id);
  689. }
  690. // Determines whether we can pull a value directly out of an initializing
  691. // expression of type `type_id` to initialize a target of type `type_id` and
  692. // kind `target_kind`.
  693. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  694. SemIR::TypeId type_id,
  695. ConversionTarget::Kind target_kind)
  696. -> bool {
  697. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  698. target_kind)) {
  699. // We don't want a value expression.
  700. return false;
  701. }
  702. // We can pull a value out of an initializing expression if it holds one.
  703. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  704. }
  705. // Returns the non-adapter type that is compatible with the specified type.
  706. static auto GetTransitiveAdaptedType(Context& context, SemIR::TypeId type_id)
  707. -> SemIR::TypeId {
  708. // If the type is an adapter, its object representation type is its compatible
  709. // non-adapter type.
  710. while (auto class_type =
  711. context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  712. auto& class_info = context.classes().Get(class_type->class_id);
  713. auto adapted_type_id =
  714. class_info.GetAdaptedType(context.sem_ir(), class_type->specific_id);
  715. if (!adapted_type_id.has_value()) {
  716. break;
  717. }
  718. type_id = adapted_type_id;
  719. }
  720. // Otherwise, the type itself is a non-adapter type.
  721. return type_id;
  722. }
  723. static auto PerformBuiltinConversion(Context& context, SemIR::LocId loc_id,
  724. SemIR::InstId value_id,
  725. ConversionTarget target) -> SemIR::InstId {
  726. auto& sem_ir = context.sem_ir();
  727. auto value = sem_ir.insts().Get(value_id);
  728. auto value_type_id = value.type_id();
  729. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  730. // Various forms of implicit conversion are supported as builtin conversions,
  731. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  732. // prelude. There are a few reasons we need to perform some of these
  733. // conversions as builtins:
  734. //
  735. // 1) Conversions from struct and tuple *literals* have special rules that
  736. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  737. // recurse into the elements of the literal before performing
  738. // initialization in order to avoid unnecessary conversions between
  739. // expression categories that would be performed by `ImplicitAs.Convert`.
  740. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  741. // the value of the facet, not only its type, and therefore cannot be
  742. // modeled by `ImplicitAs`.
  743. // 3) Some of these conversions are used while checking the library
  744. // definition of `ImplicitAs` itself or implementations of it.
  745. //
  746. // We also expect to see better performance by avoiding an `impl` lookup for
  747. // common conversions.
  748. //
  749. // TODO: We should provide a debugging flag to turn off as many of these
  750. // builtin conversions as we can so that we can test that they do the same
  751. // thing as the library implementations.
  752. //
  753. // The builtin conversions that correspond to `impl`s in the library all
  754. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  755. // being specialized in any of these cases.
  756. // If the value is already of the right kind and expression category, there's
  757. // nothing to do. Performing a conversion would decompose and rebuild tuples
  758. // and structs, so it's important that we bail out early in this case.
  759. if (value_type_id == target.type_id) {
  760. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  761. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  762. return value_id;
  763. }
  764. // If the source is an initializing expression, we may be able to pull a
  765. // value right out of it.
  766. if (value_cat == SemIR::ExprCategory::Initializing &&
  767. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  768. return AddInst<SemIR::ValueOfInitializer>(
  769. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  770. }
  771. // PerformBuiltinConversion converts each part of a tuple or struct, even
  772. // when the types are the same. This is not done for classes since they have
  773. // to define their conversions as part of their api.
  774. //
  775. // If a class adapts a tuple or struct, we convert each of its parts when
  776. // there's no other conversion going on (the source and target types are the
  777. // same). To do so, we have to insert a conversion of the value up to the
  778. // foundation and back down, and a conversion of the initializing object if
  779. // there is one.
  780. //
  781. // Implementation note: We do the conversion through a call to
  782. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  783. // extraneous `converted` semir instructions on the adapted types, and as a
  784. // shortcut to doing the explicit calls to walk the parts of the
  785. // tuple/struct which happens inside PerformBuiltinConversion().
  786. if (auto foundation_type_id =
  787. GetTransitiveAdaptedType(context, value_type_id);
  788. foundation_type_id != value_type_id &&
  789. (context.types().Is<SemIR::TupleType>(foundation_type_id) ||
  790. context.types().Is<SemIR::StructType>(foundation_type_id))) {
  791. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  792. context, loc_id,
  793. {.type_id = foundation_type_id, .source_id = value_id});
  794. auto foundation_init_id = target.init_id;
  795. if (foundation_init_id != SemIR::InstId::None) {
  796. foundation_init_id = target.init_block->AddInst<SemIR::AsCompatible>(
  797. loc_id,
  798. {.type_id = foundation_type_id, .source_id = target.init_id});
  799. }
  800. {
  801. // While the types are the same, the conversion can still fail if it
  802. // performs a copy while converting the value to another category, and
  803. // the type (or some part of it) is not copyable.
  804. DiagnosticAnnotationScope annotate_diagnostics(
  805. &context.emitter(), [&](auto& builder) {
  806. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  807. builder.Note(value_id, InCopy, value_id);
  808. });
  809. foundation_value_id =
  810. PerformBuiltinConversion(context, loc_id, foundation_value_id,
  811. {.kind = target.kind,
  812. .type_id = foundation_type_id,
  813. .init_id = foundation_init_id,
  814. .init_block = target.init_block,
  815. .diagnose = target.diagnose});
  816. if (foundation_value_id == SemIR::ErrorInst::SingletonInstId) {
  817. return SemIR::ErrorInst::SingletonInstId;
  818. }
  819. }
  820. return AddInst<SemIR::AsCompatible>(
  821. context, loc_id,
  822. {.type_id = target.type_id, .source_id = foundation_value_id});
  823. }
  824. }
  825. // T explicitly converts to U if T is compatible with U.
  826. if (target.kind == ConversionTarget::Kind::ExplicitAs &&
  827. target.type_id != value_type_id) {
  828. auto target_foundation_id =
  829. GetTransitiveAdaptedType(context, target.type_id);
  830. auto value_foundation_id = GetTransitiveAdaptedType(context, value_type_id);
  831. if (target_foundation_id == value_foundation_id) {
  832. // For a struct or tuple literal, perform a category conversion if
  833. // necessary.
  834. if (SemIR::GetExprCategory(context.sem_ir(), value_id) ==
  835. SemIR::ExprCategory::Mixed) {
  836. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  837. {.kind = ConversionTarget::Value,
  838. .type_id = value_type_id,
  839. .diagnose = target.diagnose});
  840. }
  841. return AddInst<SemIR::AsCompatible>(
  842. context, loc_id, {.type_id = target.type_id, .source_id = value_id});
  843. }
  844. }
  845. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  846. // converts to Ui.
  847. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  848. if (auto src_tuple_type =
  849. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  850. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  851. value_id, target);
  852. }
  853. }
  854. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  855. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  856. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  857. // to Ui.
  858. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  859. if (auto src_struct_type =
  860. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  861. return ConvertStructToStruct(context, *src_struct_type,
  862. *target_struct_type, value_id, target);
  863. }
  864. }
  865. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  866. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  867. if (auto src_tuple_type =
  868. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  869. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  870. value_id, target);
  871. }
  872. }
  873. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  874. // if it converts to the struct type that is the class's representation type
  875. // (a struct with the same fields as the class, plus a base field where
  876. // relevant).
  877. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  878. if (auto src_struct_type =
  879. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  880. if (!context.classes()
  881. .Get(target_class_type->class_id)
  882. .adapt_id.has_value()) {
  883. return ConvertStructToClass(context, *src_struct_type,
  884. *target_class_type, value_id, target);
  885. }
  886. }
  887. // An expression of type T converts to U if T is a class derived from U.
  888. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  889. target.type_id);
  890. path && !path->empty()) {
  891. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  892. }
  893. }
  894. // A pointer T* converts to U* if T is a class derived from U.
  895. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  896. if (auto src_pointer_type =
  897. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  898. if (auto path = ComputeInheritancePath(context, loc_id,
  899. src_pointer_type->pointee_id,
  900. target_pointer_type->pointee_id);
  901. path && !path->empty()) {
  902. return ConvertDerivedPointerToBasePointer(
  903. context, loc_id, *src_pointer_type, target.type_id, value_id,
  904. *path);
  905. }
  906. }
  907. }
  908. if (target.type_id == SemIR::TypeType::SingletonTypeId) {
  909. // A tuple of types converts to type `type`.
  910. // TODO: This should apply even for non-literal tuples.
  911. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  912. llvm::SmallVector<SemIR::TypeId> type_ids;
  913. for (auto tuple_inst_id :
  914. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  915. // TODO: This call recurses back into conversion. Switch to an
  916. // iterative approach.
  917. type_ids.push_back(
  918. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose)
  919. .type_id);
  920. }
  921. auto tuple_type_id = GetTupleType(context, type_ids);
  922. return sem_ir.types().GetInstId(tuple_type_id);
  923. }
  924. // `{}` converts to `{} as type`.
  925. // TODO: This conversion should also be performed for a non-literal value
  926. // of type `{}`.
  927. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  928. struct_literal &&
  929. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  930. value_id = sem_ir.types().GetInstId(value_type_id);
  931. }
  932. // Facet type conversions: a value T of facet type F1 can be implicitly
  933. // converted to facet type F2 if T satisfies the requirements of F2.
  934. //
  935. // TODO: Support this conversion in general. For now we only support it in
  936. // the case where F1 is a facet type and F2 is `type`.
  937. // TODO: Support converting tuple and struct values to facet types,
  938. // combining the above conversions and this one in a single conversion.
  939. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  940. return AddInst<SemIR::FacetAccessType>(
  941. context, loc_id,
  942. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  943. }
  944. }
  945. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  946. (sem_ir.types().Is<SemIR::TypeType>(value_type_id) ||
  947. sem_ir.types().Is<SemIR::FacetType>(value_type_id))) {
  948. // The value is a type or facet value, so it has a constant value. We get
  949. // that to unwrap things like NameRef and get to the underlying type or
  950. // facet value instruction so that we can use `TryGetAs`.
  951. auto const_value_id = sem_ir.constant_values().GetConstantInstId(value_id);
  952. if (auto facet_access_type_inst =
  953. sem_ir.insts().TryGetAs<SemIR::FacetAccessType>(const_value_id)) {
  954. // Conversion from a `FacetAccessType` to a `FacetValue` of the target
  955. // `FacetType` if the instruction in the `FacetAccessType` is of a
  956. // `FacetType` that satisfies the requirements of the target `FacetType`.
  957. // If the `FacetType` exactly matches the target `FacetType` then we can
  958. // shortcut and use that value, and avoid impl lookup.
  959. auto facet_value_inst_id = facet_access_type_inst->facet_value_inst_id;
  960. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  961. return facet_value_inst_id;
  962. }
  963. }
  964. // Conversion from a facet value (which has type `FacetType`) or a type
  965. // value (which has type `TypeType`) to a facet value. We can do this if the
  966. // type satisfies the requirements of the target `FacetType`, as determined
  967. // by finding impl witnesses for the target FacetType.
  968. auto lookup_result = LookupImplWitness(
  969. context, loc_id, sem_ir.constant_values().Get(const_value_id),
  970. sem_ir.types().GetConstantId(target.type_id));
  971. if (lookup_result.has_value()) {
  972. if (lookup_result.has_error_value()) {
  973. return SemIR::ErrorInst::SingletonInstId;
  974. } else {
  975. // We bind the input value to the target `FacetType` with a
  976. // `FacetValue`, which requires an instruction of type `TypeType`. So if
  977. // we are converting from a facet value, we get its `type` via an extra
  978. // `FacetAccessType` instruction.
  979. auto type_inst_id = SemIR::InstId::None;
  980. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  981. type_inst_id =
  982. AddInst(context, loc_id,
  983. SemIR::FacetAccessType{
  984. .type_id = SemIR::TypeType::SingletonTypeId,
  985. .facet_value_inst_id = const_value_id,
  986. });
  987. } else {
  988. type_inst_id = const_value_id;
  989. }
  990. return AddInst<SemIR::FacetValue>(
  991. context, loc_id,
  992. {.type_id = target.type_id,
  993. .type_inst_id = type_inst_id,
  994. .witnesses_block_id = lookup_result.inst_block_id()});
  995. }
  996. }
  997. }
  998. // No builtin conversion applies.
  999. return value_id;
  1000. }
  1001. // Given a value expression, form a corresponding initializer that copies from
  1002. // that value, if it is possible to do so.
  1003. static auto PerformCopy(Context& context, SemIR::InstId expr_id, bool diagnose)
  1004. -> SemIR::InstId {
  1005. auto expr = context.insts().Get(expr_id);
  1006. auto type_id = expr.type_id();
  1007. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  1008. return SemIR::ErrorInst::SingletonInstId;
  1009. }
  1010. if (InitReprIsCopyOfValueRepr(context.sem_ir(), type_id)) {
  1011. // For simple by-value types, no explicit action is required. Initializing
  1012. // from a value expression is treated as copying the value.
  1013. return expr_id;
  1014. }
  1015. // TODO: We don't yet have rules for whether and when a class type is
  1016. // copyable, or how to perform the copy.
  1017. if (diagnose) {
  1018. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1019. "cannot copy value of type {0}", TypeOfInstId);
  1020. context.emitter().Emit(expr_id, CopyOfUncopyableType, expr_id);
  1021. }
  1022. return SemIR::ErrorInst::SingletonInstId;
  1023. }
  1024. static auto DiagnoseConversionFailureToConstraintValue(Context& context,
  1025. SemIR::LocId loc_id,
  1026. SemIR::InstId expr_id,
  1027. ConversionTarget target)
  1028. -> DiagnosticBuilder {
  1029. CARBON_DCHECK(target.type_id == SemIR::TypeType::SingletonTypeId ||
  1030. context.types().Is<SemIR::FacetType>(target.type_id));
  1031. auto type_of_expr_id = context.insts().Get(expr_id).type_id();
  1032. if (context.types().IsFacetType(type_of_expr_id)) {
  1033. // If the source type is/has a facet value, then we can include its
  1034. // FacetType in the diagnostic to help explain what interfaces the
  1035. // source type implements.
  1036. auto facet_value_inst_id = SemIR::InstId::None;
  1037. if (auto facet_access_type =
  1038. context.insts().TryGetAs<SemIR::FacetAccessType>(expr_id)) {
  1039. facet_value_inst_id = facet_access_type->facet_value_inst_id;
  1040. } else if (context.types().Is<SemIR::FacetType>(type_of_expr_id)) {
  1041. facet_value_inst_id = expr_id;
  1042. }
  1043. if (facet_value_inst_id.has_value()) {
  1044. CARBON_DIAGNOSTIC(
  1045. ConversionFailureFacetToFacet, Error,
  1046. "cannot{0:| implicitly} convert type {1} that implements {2} "
  1047. "into type implementing {3}{0: with `as`|}",
  1048. BoolAsSelect, InstIdAsType, TypeOfInstId, SemIR::TypeId);
  1049. return context.emitter().Build(
  1050. loc_id, ConversionFailureFacetToFacet,
  1051. target.kind == ConversionTarget::ExplicitAs, expr_id,
  1052. facet_value_inst_id, target.type_id);
  1053. } else {
  1054. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  1055. "cannot{0:| implicitly} convert type {1} "
  1056. "into type implementing {2}{0: with `as`|}",
  1057. BoolAsSelect, InstIdAsType, SemIR::TypeId);
  1058. return context.emitter().Build(
  1059. loc_id, ConversionFailureTypeToFacet,
  1060. target.kind == ConversionTarget::ExplicitAs, expr_id, target.type_id);
  1061. }
  1062. } else {
  1063. CARBON_DIAGNOSTIC(
  1064. ConversionFailureNonTypeToFacet, Error,
  1065. "cannot{0:| implicitly} convert non-type value of type {1} "
  1066. "{2:to|into type implementing} {3}{0: with `as`|}",
  1067. BoolAsSelect, TypeOfInstId, BoolAsSelect, SemIR::TypeId);
  1068. return context.emitter().Build(
  1069. loc_id, ConversionFailureNonTypeToFacet,
  1070. target.kind == ConversionTarget::ExplicitAs, expr_id,
  1071. target.type_id == SemIR::TypeType::SingletonTypeId, target.type_id);
  1072. }
  1073. }
  1074. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1075. ConversionTarget target) -> SemIR::InstId {
  1076. auto& sem_ir = context.sem_ir();
  1077. auto orig_expr_id = expr_id;
  1078. // Start by making sure both sides are non-errors. If any part is an error,
  1079. // the result is an error and we shouldn't diagnose.
  1080. if (sem_ir.insts().Get(expr_id).type_id() ==
  1081. SemIR::ErrorInst::SingletonTypeId ||
  1082. target.type_id == SemIR::ErrorInst::SingletonTypeId) {
  1083. return SemIR::ErrorInst::SingletonInstId;
  1084. }
  1085. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  1086. // TODO: We currently encounter this for use of namespaces and functions.
  1087. // We should provide a better diagnostic for inappropriate use of
  1088. // namespace names, and allow use of functions as values.
  1089. if (target.diagnose) {
  1090. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1091. "expression cannot be used as a value");
  1092. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1093. }
  1094. return SemIR::ErrorInst::SingletonInstId;
  1095. }
  1096. // We can only perform initialization for complete, non-abstract types. Note
  1097. // that `RequireConcreteType` returns true for facet types, since their
  1098. // representation is fixed. This allows us to support using the `Self` of an
  1099. // interface inside its definition.
  1100. if (!RequireConcreteType(
  1101. context, target.type_id, loc_id,
  1102. [&] {
  1103. CARBON_CHECK(!target.is_initializer(),
  1104. "Initialization of incomplete types is expected to be "
  1105. "caught elsewhere.");
  1106. if (!target.diagnose) {
  1107. return context.emitter().BuildSuppressed();
  1108. }
  1109. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1110. "forming value of incomplete type {0}",
  1111. SemIR::TypeId);
  1112. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1113. "invalid use of incomplete type {0}",
  1114. SemIR::TypeId);
  1115. return context.emitter().Build(
  1116. loc_id,
  1117. target.kind == ConversionTarget::Value
  1118. ? IncompleteTypeInValueConversion
  1119. : IncompleteTypeInConversion,
  1120. target.type_id);
  1121. },
  1122. [&] {
  1123. if (!target.diagnose || !target.is_initializer()) {
  1124. return context.emitter().BuildSuppressed();
  1125. }
  1126. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1127. "initialization of abstract type {0}",
  1128. SemIR::TypeId);
  1129. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1130. target.type_id);
  1131. })) {
  1132. return SemIR::ErrorInst::SingletonInstId;
  1133. }
  1134. // Check whether any builtin conversion applies.
  1135. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target);
  1136. if (expr_id == SemIR::ErrorInst::SingletonInstId) {
  1137. return expr_id;
  1138. }
  1139. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1140. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1141. SemIR::InstId interface_args[] = {
  1142. context.types().GetInstId(target.type_id)};
  1143. Operator op = {
  1144. .interface_name = target.kind == ConversionTarget::ExplicitAs
  1145. ? llvm::StringLiteral("As")
  1146. : llvm::StringLiteral("ImplicitAs"),
  1147. .interface_args_ref = interface_args,
  1148. .op_name = "Convert",
  1149. };
  1150. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1151. if (!target.diagnose) {
  1152. return context.emitter().BuildSuppressed();
  1153. }
  1154. if (target.type_id == SemIR::TypeType::SingletonTypeId ||
  1155. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1156. // TODO: Move this to PerformBuiltinConversion(). See
  1157. // https://github.com/carbon-language/carbon-lang/issues/5122.
  1158. return DiagnoseConversionFailureToConstraintValue(context, loc_id,
  1159. expr_id, target);
  1160. } else {
  1161. // TODO: Should this message change to say "object of type" when
  1162. // converting from a reference expression?
  1163. CARBON_DIAGNOSTIC(ConversionFailure, Error,
  1164. "cannot{0:| implicitly} convert value of type {1} to "
  1165. "{2}{0: with `as`|}",
  1166. BoolAsSelect, TypeOfInstId, SemIR::TypeId);
  1167. return context.emitter().Build(
  1168. loc_id, ConversionFailure,
  1169. target.kind == ConversionTarget::ExplicitAs, expr_id,
  1170. target.type_id);
  1171. }
  1172. });
  1173. // Pull a value directly out of the initializer if possible and wanted.
  1174. if (expr_id != SemIR::ErrorInst::SingletonInstId &&
  1175. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1176. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1177. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1178. }
  1179. }
  1180. // Track that we performed a type conversion, if we did so.
  1181. if (orig_expr_id != expr_id) {
  1182. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1183. {.type_id = target.type_id,
  1184. .original_id = orig_expr_id,
  1185. .result_id = expr_id});
  1186. }
  1187. // For `as`, don't perform any value category conversions. In particular, an
  1188. // identity conversion shouldn't change the expression category.
  1189. if (target.kind == ConversionTarget::ExplicitAs) {
  1190. return expr_id;
  1191. }
  1192. // Now perform any necessary value category conversions.
  1193. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  1194. case SemIR::ExprCategory::NotExpr:
  1195. case SemIR::ExprCategory::Mixed:
  1196. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1197. sem_ir.insts().Get(expr_id));
  1198. case SemIR::ExprCategory::Error:
  1199. return SemIR::ErrorInst::SingletonInstId;
  1200. case SemIR::ExprCategory::Initializing:
  1201. if (target.is_initializer()) {
  1202. if (orig_expr_id == expr_id) {
  1203. // Don't fill in the return slot if we created the expression through
  1204. // a conversion. In that case, we will have created it with the
  1205. // target already set.
  1206. // TODO: Find a better way to track whether we need to do this.
  1207. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  1208. *target.init_block);
  1209. }
  1210. break;
  1211. }
  1212. // Commit to using a temporary for this initializing expression.
  1213. // TODO: Don't create a temporary if the initializing representation
  1214. // is already a value representation.
  1215. expr_id = FinalizeTemporary(context, expr_id,
  1216. target.kind == ConversionTarget::Discarded);
  1217. // We now have an ephemeral reference.
  1218. [[fallthrough]];
  1219. case SemIR::ExprCategory::DurableRef:
  1220. case SemIR::ExprCategory::EphemeralRef:
  1221. // If a reference expression is an acceptable result, we're done.
  1222. if (target.kind == ConversionTarget::ValueOrRef ||
  1223. target.kind == ConversionTarget::Discarded) {
  1224. break;
  1225. }
  1226. // If we have a reference and don't want one, form a value binding.
  1227. // TODO: Support types with custom value representations.
  1228. expr_id = AddInst<SemIR::BindValue>(
  1229. context, context.insts().GetLocId(expr_id),
  1230. {.type_id = target.type_id, .value_id = expr_id});
  1231. // We now have a value expression.
  1232. [[fallthrough]];
  1233. case SemIR::ExprCategory::Value:
  1234. // When initializing from a value, perform a copy.
  1235. if (target.is_initializer()) {
  1236. expr_id = PerformCopy(context, expr_id, target.diagnose);
  1237. }
  1238. break;
  1239. }
  1240. // Perform a final destination store, if necessary.
  1241. if (target.kind == ConversionTarget::FullInitializer) {
  1242. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1243. init_rep.kind == SemIR::InitRepr::ByCopy) {
  1244. target.init_block->InsertHere();
  1245. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1246. {.type_id = target.type_id,
  1247. .src_id = expr_id,
  1248. .dest_id = target.init_id});
  1249. }
  1250. }
  1251. return expr_id;
  1252. }
  1253. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1254. SemIR::InstId value_id) -> SemIR::InstId {
  1255. PendingBlock target_block(context);
  1256. return Convert(context, loc_id, value_id,
  1257. {.kind = ConversionTarget::Initializer,
  1258. .type_id = context.insts().Get(target_id).type_id(),
  1259. .init_id = target_id,
  1260. .init_block = &target_block});
  1261. }
  1262. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1263. -> SemIR::InstId {
  1264. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1265. {.kind = ConversionTarget::Value,
  1266. .type_id = context.insts().Get(expr_id).type_id()});
  1267. }
  1268. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1269. -> SemIR::InstId {
  1270. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  1271. {.kind = ConversionTarget::ValueOrRef,
  1272. .type_id = context.insts().Get(expr_id).type_id()});
  1273. }
  1274. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1275. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1276. -> SemIR::InstId {
  1277. return Convert(context, loc_id, expr_id,
  1278. {.kind = ConversionTarget::Value, .type_id = type_id});
  1279. }
  1280. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1281. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1282. -> SemIR::InstId {
  1283. return Convert(context, loc_id, expr_id,
  1284. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1285. }
  1286. // Like ConvertToValueOfType but failure to convert does not result in
  1287. // diagnostics. An ErrorInst instruction is still returned on failure.
  1288. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1289. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1290. -> SemIR::InstId {
  1291. return Convert(
  1292. context, loc_id, expr_id,
  1293. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1294. }
  1295. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1296. SemIR::InstId value_id) -> SemIR::InstId {
  1297. return ConvertToValueOfType(
  1298. context, loc_id, value_id,
  1299. GetSingletonType(context, SemIR::BoolType::SingletonInstId));
  1300. }
  1301. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1302. SemIR::InstId value_id, SemIR::TypeId type_id)
  1303. -> SemIR::InstId {
  1304. return Convert(context, as_node, value_id,
  1305. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  1306. }
  1307. // TODO: Consider moving this to pattern_match.h.
  1308. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1309. SemIR::InstId self_id,
  1310. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1311. SemIR::InstId return_slot_arg_id,
  1312. const SemIR::Function& callee,
  1313. SemIR::SpecificId callee_specific_id)
  1314. -> SemIR::InstBlockId {
  1315. // The callee reference can be invalidated by conversions, so ensure all reads
  1316. // from it are done before conversion calls.
  1317. auto callee_decl_id = callee.latest_decl_id();
  1318. auto param_patterns =
  1319. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1320. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1321. // The caller should have ensured this callee has the right arity.
  1322. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1323. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1324. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1325. "missing object argument in method call");
  1326. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1327. context.emitter()
  1328. .Build(call_loc_id, MissingObjectInMethodCall)
  1329. .Note(callee_decl_id, InCallToFunction)
  1330. .Emit();
  1331. self_id = SemIR::ErrorInst::SingletonInstId;
  1332. }
  1333. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1334. callee.param_patterns_id, return_slot_pattern_id,
  1335. self_id, arg_refs, return_slot_arg_id);
  1336. }
  1337. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1338. bool diagnose) -> TypeExpr {
  1339. auto type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1340. SemIR::TypeType::SingletonTypeId);
  1341. if (type_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1342. return {.inst_id = type_inst_id,
  1343. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1344. }
  1345. auto type_const_id = context.constant_values().Get(type_inst_id);
  1346. if (!type_const_id.is_constant()) {
  1347. if (diagnose) {
  1348. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1349. "cannot evaluate type expression");
  1350. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1351. }
  1352. return {.inst_id = SemIR::ErrorInst::SingletonInstId,
  1353. .type_id = SemIR::ErrorInst::SingletonTypeId};
  1354. }
  1355. return {.inst_id = type_inst_id,
  1356. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1357. }
  1358. } // namespace Carbon::Check
  1359. // NOLINTEND(misc-no-recursion)