convert.cpp 55 KB

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