convert.cpp 69 KB

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