convert.cpp 75 KB

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