convert.cpp 60 KB

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