convert.cpp 57 KB

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