convert.cpp 60 KB

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