convert.cpp 53 KB

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