convert.cpp 66 KB

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