convert.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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 "llvm/ADT/STLExtras.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/diagnostics/diagnostic_kind.h"
  11. #include "toolchain/parse/node_kind.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. namespace Carbon::Check {
  16. // Given an initializing expression, find its return slot. Returns `Invalid` if
  17. // there is no return slot, because the initialization is not performed in
  18. // place.
  19. static auto FindReturnSlotForInitializer(SemIR::File& sem_ir,
  20. SemIR::InstId init_id)
  21. -> SemIR::InstId {
  22. SemIR::Inst init = sem_ir.insts().Get(init_id);
  23. switch (init.kind()) {
  24. default:
  25. CARBON_FATAL() << "Initialization from unexpected inst " << init;
  26. case SemIR::StructInit::Kind:
  27. case SemIR::TupleInit::Kind:
  28. // TODO: Track a return slot for these initializers.
  29. CARBON_FATAL() << init
  30. << " should be created with its return slot already "
  31. "filled in properly";
  32. case SemIR::InitializeFrom::Kind: {
  33. return init.As<SemIR::InitializeFrom>().dest_id;
  34. }
  35. case SemIR::Call::Kind: {
  36. auto call = init.As<SemIR::Call>();
  37. if (!SemIR::GetInitializingRepresentation(sem_ir, call.type_id)
  38. .has_return_slot()) {
  39. return SemIR::InstId::Invalid;
  40. }
  41. return sem_ir.inst_blocks().Get(call.args_id).back();
  42. }
  43. case SemIR::ArrayInit::Kind: {
  44. return sem_ir.inst_blocks()
  45. .Get(init.As<SemIR::ArrayInit>().inits_and_return_slot_id)
  46. .back();
  47. }
  48. }
  49. }
  50. // Marks the initializer `init_id` as initializing `target_id`.
  51. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  52. SemIR::InstId target_id,
  53. PendingBlock& target_block) -> void {
  54. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  55. if (return_slot_id.is_valid()) {
  56. // Replace the temporary in the return slot with a reference to our target.
  57. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  58. SemIR::TemporaryStorage::Kind)
  59. << "Return slot for initializer does not contain a temporary; "
  60. << "initialized multiple times? Have "
  61. << sem_ir.insts().Get(return_slot_id);
  62. target_block.MergeReplacing(return_slot_id, target_id);
  63. }
  64. }
  65. // Commits to using a temporary to store the result of the initializing
  66. // expression described by `init_id`, and returns the location of the
  67. // temporary. If `discarded` is `true`, the result is discarded, and no
  68. // temporary will be created if possible; if no temporary is created, the
  69. // return value will be `SemIR::InstId::Invalid`.
  70. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  71. bool discarded) -> SemIR::InstId {
  72. auto& sem_ir = context.sem_ir();
  73. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  74. if (return_slot_id.is_valid()) {
  75. // The return slot should already have a materialized temporary in it.
  76. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  77. SemIR::TemporaryStorage::Kind)
  78. << "Return slot for initializer does not contain a temporary; "
  79. << "initialized multiple times? Have "
  80. << sem_ir.insts().Get(return_slot_id);
  81. auto init = sem_ir.insts().Get(init_id);
  82. return context.AddInst(SemIR::Temporary{init.parse_node(), init.type_id(),
  83. return_slot_id, init_id});
  84. }
  85. if (discarded) {
  86. // Don't invent a temporary that we're going to discard.
  87. return SemIR::InstId::Invalid;
  88. }
  89. // The initializer has no return slot, but we want to produce a temporary
  90. // object. Materialize one now.
  91. // TODO: Consider using an invalid ID to mean that we immediately
  92. // materialize and initialize a temporary, rather than two separate
  93. // instructions.
  94. auto init = sem_ir.insts().Get(init_id);
  95. auto temporary_id = context.AddInst(
  96. SemIR::TemporaryStorage{init.parse_node(), init.type_id()});
  97. return context.AddInst(SemIR::Temporary{init.parse_node(), init.type_id(),
  98. temporary_id, init_id});
  99. }
  100. // Materialize a temporary to hold the result of the given expression if it is
  101. // an initializing expression.
  102. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  103. -> SemIR::InstId {
  104. if (GetExpressionCategory(context.sem_ir(), expr_id) ==
  105. SemIR::ExpressionCategory::Initializing) {
  106. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  107. }
  108. return expr_id;
  109. }
  110. // Creates and adds an instruction to perform element access into an aggregate.
  111. template <typename AccessInstT, typename InstBlockT>
  112. static auto MakeElemAccessInst(Context& context, Parse::Node parse_node,
  113. SemIR::InstId aggregate_id,
  114. SemIR::TypeId elem_type_id, InstBlockT& block,
  115. std::size_t i) {
  116. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  117. // TODO: Add a new instruction kind for indexing an array at a constant
  118. // index so that we don't need an integer literal instruction here, and
  119. // remove this special case.
  120. auto index_id = block.AddInst(SemIR::IntegerLiteral{
  121. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::IntegerType),
  122. context.sem_ir().integers().Add(llvm::APInt(32, i))});
  123. return block.AddInst(
  124. AccessInstT{parse_node, elem_type_id, aggregate_id, index_id});
  125. } else {
  126. return block.AddInst(AccessInstT{parse_node, elem_type_id, aggregate_id,
  127. SemIR::MemberIndex(i)});
  128. }
  129. }
  130. // Converts an element of one aggregate so that it can be used as an element of
  131. // another aggregate.
  132. //
  133. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  134. // element type, `i` is the index, and `SourceAccessInstT` is the kind of
  135. // instruction used to access the source element.
  136. //
  137. // For the target: `kind` is the kind of conversion or initialization,
  138. // `target_elem_type` is the element type. For initialization, `target_id` is
  139. // the destination, `target_block` is a pending block for target location
  140. // calculations that will be spliced as the return slot of the initializer if
  141. // necessary, `i` is the index, and `TargetAccessInstT` is the kind of
  142. // instruction used to access the destination element.
  143. template <typename SourceAccessInstT, typename TargetAccessInstT>
  144. static auto ConvertAggregateElement(
  145. Context& context, Parse::Node parse_node, SemIR::InstId src_id,
  146. SemIR::TypeId src_elem_type,
  147. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  148. ConversionTarget::Kind kind, SemIR::InstId target_id,
  149. SemIR::TypeId target_elem_type, PendingBlock* target_block, std::size_t i) {
  150. // Compute the location of the source element. This goes into the current code
  151. // block, not into the target block.
  152. // TODO: Ideally we would discard this instruction if it's unused.
  153. auto src_elem_id =
  154. !src_literal_elems.empty()
  155. ? src_literal_elems[i]
  156. : MakeElemAccessInst<SourceAccessInstT>(context, parse_node, src_id,
  157. src_elem_type, context, i);
  158. // If we're performing a conversion rather than an initialization, we won't
  159. // have or need a target.
  160. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  161. if (!target.is_initializer()) {
  162. return Convert(context, parse_node, src_elem_id, target);
  163. }
  164. // Compute the location of the target element and initialize it.
  165. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  166. target.init_block = target_block;
  167. target.init_id = MakeElemAccessInst<TargetAccessInstT>(
  168. context, parse_node, target_id, target_elem_type, *target_block, i);
  169. return Convert(context, parse_node, src_elem_id, target);
  170. }
  171. namespace {
  172. // A handle to a new block that may be modified, with copy-on-write semantics.
  173. //
  174. // The constructor is given the ID of an existing block that provides the
  175. // initial contents of the new block. The new block is lazily allocated; if no
  176. // modifications have been made, the `id()` function will return the original
  177. // block ID.
  178. //
  179. // This is intended to avoid an unnecessary block allocation in the case where
  180. // the new block ends up being exactly the same as the original block.
  181. class CopyOnWriteBlock {
  182. public:
  183. // Constructs the block. If `source_id` is valid, it is used as the initial
  184. // value of the block. Otherwise, uninitialized storage for `size` elements
  185. // is allocated.
  186. CopyOnWriteBlock(SemIR::File& file, SemIR::InstBlockId source_id, size_t size)
  187. : file_(file), source_id_(source_id) {
  188. if (!source_id_.is_valid()) {
  189. id_ = file_.inst_blocks().AddUninitialized(size);
  190. }
  191. }
  192. auto id() -> SemIR::InstBlockId const { return id_; }
  193. auto Set(int i, SemIR::InstId value) -> void {
  194. if (source_id_.is_valid() && file_.inst_blocks().Get(id_)[i] == value) {
  195. return;
  196. }
  197. if (id_ == source_id_) {
  198. id_ = file_.inst_blocks().Add(file_.inst_blocks().Get(source_id_));
  199. }
  200. file_.inst_blocks().Get(id_)[i] = value;
  201. }
  202. private:
  203. SemIR::File& file_;
  204. SemIR::InstBlockId source_id_;
  205. SemIR::InstBlockId id_ = source_id_;
  206. };
  207. } // namespace
  208. // Performs a conversion from a tuple to an array type. Does not perform a
  209. // final conversion to the requested expression category.
  210. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  211. SemIR::ArrayType array_type,
  212. SemIR::InstId value_id, ConversionTarget target)
  213. -> SemIR::InstId {
  214. auto& sem_ir = context.sem_ir();
  215. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  216. auto value = sem_ir.insts().Get(value_id);
  217. // If we're initializing from a tuple literal, we will use its elements
  218. // directly. Otherwise, materialize a temporary if needed and index into the
  219. // result.
  220. llvm::ArrayRef<SemIR::InstId> literal_elems;
  221. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  222. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  223. } else {
  224. value_id = MaterializeIfInitializing(context, value_id);
  225. }
  226. // Check that the tuple is the right size.
  227. uint64_t array_bound = sem_ir.GetArrayBoundValue(array_type.bound_id);
  228. if (tuple_elem_types.size() != array_bound) {
  229. CARBON_DIAGNOSTIC(
  230. ArrayInitFromLiteralArgCountMismatch, Error,
  231. "Cannot initialize array of {0} element(s) from {1} initializer(s).",
  232. uint64_t, size_t);
  233. CARBON_DIAGNOSTIC(ArrayInitFromExpressionArgCountMismatch, Error,
  234. "Cannot initialize array of {0} element(s) from tuple "
  235. "with {1} element(s).",
  236. uint64_t, size_t);
  237. context.emitter().Emit(value.parse_node(),
  238. literal_elems.empty()
  239. ? ArrayInitFromExpressionArgCountMismatch
  240. : ArrayInitFromLiteralArgCountMismatch,
  241. array_bound, tuple_elem_types.size());
  242. return SemIR::InstId::BuiltinError;
  243. }
  244. PendingBlock target_block_storage(context);
  245. PendingBlock* target_block =
  246. target.init_block ? target.init_block : &target_block_storage;
  247. // Arrays are always initialized in-place. Allocate a temporary as the
  248. // destination for the array initialization if we weren't given one.
  249. SemIR::InstId return_slot_id = target.init_id;
  250. if (!target.init_id.is_valid()) {
  251. return_slot_id = target_block->AddInst(
  252. SemIR::TemporaryStorage{value.parse_node(), target.type_id});
  253. }
  254. // Initialize each element of the array from the corresponding element of the
  255. // tuple.
  256. // TODO: Annotate diagnostics coming from here with the array element index,
  257. // if initializing from a tuple literal.
  258. llvm::SmallVector<SemIR::InstId> inits;
  259. inits.reserve(array_bound + 1);
  260. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  261. // TODO: This call recurses back into conversion. Switch to an iterative
  262. // approach.
  263. auto init_id =
  264. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  265. context, value.parse_node(), value_id, src_type_id, literal_elems,
  266. ConversionTarget::FullInitializer, return_slot_id,
  267. array_type.element_type_id, target_block, i);
  268. if (init_id == SemIR::InstId::BuiltinError) {
  269. return SemIR::InstId::BuiltinError;
  270. }
  271. inits.push_back(init_id);
  272. }
  273. // The last element of the refs block contains the return slot for the array
  274. // initialization. Flush the temporary here if we didn't insert it earlier.
  275. target_block->InsertHere();
  276. inits.push_back(return_slot_id);
  277. return context.AddInst(SemIR::ArrayInit{value.parse_node(), target.type_id,
  278. value_id,
  279. sem_ir.inst_blocks().Add(inits)});
  280. }
  281. // Performs a conversion from a tuple to a tuple type. Does not perform a
  282. // final conversion to the requested expression category.
  283. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  284. SemIR::TupleType dest_type,
  285. SemIR::InstId value_id, ConversionTarget target)
  286. -> SemIR::InstId {
  287. auto& sem_ir = context.sem_ir();
  288. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  289. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  290. auto value = sem_ir.insts().Get(value_id);
  291. // If we're initializing from a tuple literal, we will use its elements
  292. // directly. Otherwise, materialize a temporary if needed and index into the
  293. // result.
  294. llvm::ArrayRef<SemIR::InstId> literal_elems;
  295. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  296. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  297. literal_elems_id = tuple_literal->elements_id;
  298. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  299. } else {
  300. value_id = MaterializeIfInitializing(context, value_id);
  301. }
  302. // Check that the tuples are the same size.
  303. if (src_elem_types.size() != dest_elem_types.size()) {
  304. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  305. "Cannot initialize tuple of {0} element(s) from tuple "
  306. "with {1} element(s).",
  307. size_t, size_t);
  308. context.emitter().Emit(value.parse_node(), TupleInitElementCountMismatch,
  309. dest_elem_types.size(), src_elem_types.size());
  310. return SemIR::InstId::BuiltinError;
  311. }
  312. // If we're forming an initializer, then we want an initializer for each
  313. // element. Otherwise, we want a value representation for each element.
  314. // Perform a final destination store if we're performing an in-place
  315. // initialization.
  316. bool is_init = target.is_initializer();
  317. ConversionTarget::Kind inner_kind =
  318. !is_init ? ConversionTarget::Value
  319. : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind ==
  320. SemIR::InitializingRepresentation::InPlace
  321. ? ConversionTarget::FullInitializer
  322. : ConversionTarget::Initializer;
  323. // Initialize each element of the destination from the corresponding element
  324. // of the source.
  325. // TODO: Annotate diagnostics coming from here with the element index.
  326. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_types.size());
  327. for (auto [i, src_type_id, dest_type_id] :
  328. llvm::enumerate(src_elem_types, dest_elem_types)) {
  329. // TODO: This call recurses back into conversion. Switch to an iterative
  330. // approach.
  331. auto init_id =
  332. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  333. context, value.parse_node(), value_id, src_type_id, literal_elems,
  334. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  335. if (init_id == SemIR::InstId::BuiltinError) {
  336. return SemIR::InstId::BuiltinError;
  337. }
  338. new_block.Set(i, init_id);
  339. }
  340. return is_init ? context.AddInst(SemIR::TupleInit{value.parse_node(),
  341. target.type_id, value_id,
  342. new_block.id()})
  343. : context.AddInst(SemIR::TupleValue{value.parse_node(),
  344. target.type_id, value_id,
  345. new_block.id()});
  346. }
  347. // Performs a conversion from a struct to a struct type. Does not perform a
  348. // final conversion to the requested expression category.
  349. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  350. SemIR::StructType dest_type,
  351. SemIR::InstId value_id,
  352. ConversionTarget target) -> SemIR::InstId {
  353. auto& sem_ir = context.sem_ir();
  354. auto src_elem_fields = sem_ir.inst_blocks().Get(src_type.fields_id);
  355. auto dest_elem_fields = sem_ir.inst_blocks().Get(dest_type.fields_id);
  356. auto value = sem_ir.insts().Get(value_id);
  357. // If we're initializing from a struct literal, we will use its elements
  358. // directly. Otherwise, materialize a temporary if needed and index into the
  359. // result.
  360. llvm::ArrayRef<SemIR::InstId> literal_elems;
  361. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  362. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  363. literal_elems_id = struct_literal->elements_id;
  364. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  365. } else {
  366. value_id = MaterializeIfInitializing(context, value_id);
  367. }
  368. // Check that the structs are the same size.
  369. // TODO: If not, include the name of the first source field that doesn't
  370. // exist in the destination or vice versa in the diagnostic.
  371. if (src_elem_fields.size() != dest_elem_fields.size()) {
  372. CARBON_DIAGNOSTIC(StructInitElementCountMismatch, Error,
  373. "Cannot initialize struct of {0} element(s) from struct "
  374. "with {1} element(s).",
  375. size_t, size_t);
  376. context.emitter().Emit(value.parse_node(), StructInitElementCountMismatch,
  377. dest_elem_fields.size(), src_elem_fields.size());
  378. return SemIR::InstId::BuiltinError;
  379. }
  380. // Prepare to look up fields in the source by index.
  381. llvm::SmallDenseMap<IdentifierId, int32_t> src_field_indexes;
  382. if (src_type.fields_id != dest_type.fields_id) {
  383. for (auto [i, field_id] : llvm::enumerate(src_elem_fields)) {
  384. auto [it, added] = src_field_indexes.insert(
  385. {context.insts().GetAs<SemIR::StructTypeField>(field_id).name_id, i});
  386. CARBON_CHECK(added) << "Duplicate field in source structure";
  387. }
  388. }
  389. // If we're forming an initializer, then we want an initializer for each
  390. // element. Otherwise, we want a value representation for each element.
  391. // Perform a final destination store if we're performing an in-place
  392. // initialization.
  393. bool is_init = target.is_initializer();
  394. ConversionTarget::Kind inner_kind =
  395. !is_init ? ConversionTarget::Value
  396. : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind ==
  397. SemIR::InitializingRepresentation::InPlace
  398. ? ConversionTarget::FullInitializer
  399. : ConversionTarget::Initializer;
  400. // Initialize each element of the destination from the corresponding element
  401. // of the source.
  402. // TODO: Annotate diagnostics coming from here with the element index.
  403. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_fields.size());
  404. for (auto [i, dest_field_id] : llvm::enumerate(dest_elem_fields)) {
  405. auto dest_field =
  406. sem_ir.insts().GetAs<SemIR::StructTypeField>(dest_field_id);
  407. // Find the matching source field.
  408. auto src_field_index = i;
  409. if (src_type.fields_id != dest_type.fields_id) {
  410. auto src_field_it = src_field_indexes.find(dest_field.name_id);
  411. if (src_field_it == src_field_indexes.end()) {
  412. if (literal_elems_id.is_valid()) {
  413. CARBON_DIAGNOSTIC(
  414. StructInitMissingFieldInLiteral, Error,
  415. "Missing value for field `{0}` in struct initialization.",
  416. llvm::StringRef);
  417. context.emitter().Emit(value.parse_node(),
  418. StructInitMissingFieldInLiteral,
  419. sem_ir.identifiers().Get(dest_field.name_id));
  420. } else {
  421. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  422. "Cannot convert from struct type `{0}` to `{1}`: "
  423. "missing field `{2}` in source type.",
  424. std::string, std::string, llvm::StringRef);
  425. context.emitter().Emit(value.parse_node(),
  426. StructInitMissingFieldInConversion,
  427. sem_ir.StringifyType(value.type_id()),
  428. sem_ir.StringifyType(target.type_id),
  429. sem_ir.identifiers().Get(dest_field.name_id));
  430. }
  431. return SemIR::InstId::BuiltinError;
  432. }
  433. src_field_index = src_field_it->second;
  434. }
  435. auto src_field = sem_ir.insts().GetAs<SemIR::StructTypeField>(
  436. src_elem_fields[src_field_index]);
  437. // TODO: This call recurses back into conversion. Switch to an iterative
  438. // approach.
  439. auto init_id =
  440. ConvertAggregateElement<SemIR::StructAccess, SemIR::StructAccess>(
  441. context, value.parse_node(), value_id, src_field.field_type_id,
  442. literal_elems, inner_kind, target.init_id, dest_field.field_type_id,
  443. target.init_block, src_field_index);
  444. if (init_id == SemIR::InstId::BuiltinError) {
  445. return SemIR::InstId::BuiltinError;
  446. }
  447. new_block.Set(i, init_id);
  448. }
  449. return is_init ? context.AddInst(SemIR::StructInit{value.parse_node(),
  450. target.type_id, value_id,
  451. new_block.id()})
  452. : context.AddInst(SemIR::StructValue{value.parse_node(),
  453. target.type_id, value_id,
  454. new_block.id()});
  455. }
  456. // Returns whether `category` is a valid expression category to produce as a
  457. // result of a conversion with kind `target_kind`, or at most needs a temporary
  458. // to be materialized.
  459. static bool IsValidExpressionCategoryForConversionTarget(
  460. SemIR::ExpressionCategory category, ConversionTarget::Kind target_kind) {
  461. switch (target_kind) {
  462. case ConversionTarget::Value:
  463. return category == SemIR::ExpressionCategory::Value;
  464. case ConversionTarget::ValueOrReference:
  465. case ConversionTarget::Discarded:
  466. return category == SemIR::ExpressionCategory::Value ||
  467. category == SemIR::ExpressionCategory::DurableReference ||
  468. category == SemIR::ExpressionCategory::EphemeralReference ||
  469. category == SemIR::ExpressionCategory::Initializing;
  470. case ConversionTarget::ExplicitAs:
  471. return true;
  472. case ConversionTarget::Initializer:
  473. case ConversionTarget::FullInitializer:
  474. return category == SemIR::ExpressionCategory::Initializing;
  475. }
  476. }
  477. static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node,
  478. SemIR::InstId value_id,
  479. ConversionTarget target) -> SemIR::InstId {
  480. auto& sem_ir = context.sem_ir();
  481. auto value = sem_ir.insts().Get(value_id);
  482. auto value_type_id = value.type_id();
  483. auto target_type_inst =
  484. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(target.type_id));
  485. // Various forms of implicit conversion are supported as builtin conversions,
  486. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  487. // prelude. There are a few reasons we need to perform some of these
  488. // conversions as builtins:
  489. //
  490. // 1) Conversions from struct and tuple *literals* have special rules that
  491. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  492. // recurse into the elements of the literal before performing
  493. // initialization in order to avoid unnecessary conversions between
  494. // expression categories that would be performed by `ImplicitAs.Convert`.
  495. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  496. // the value of the facet, not only its type, and therefore cannot be
  497. // modeled by `ImplicitAs`.
  498. // 3) Some of these conversions are used while checking the library
  499. // definition of `ImplicitAs` itself or implementations of it.
  500. //
  501. // We also expect to see better performance by avoiding an `impl` lookup for
  502. // common conversions.
  503. //
  504. // TODO: We should provide a debugging flag to turn off as many of these
  505. // builtin conversions as we can so that we can test that they do the same
  506. // thing as the library implementations.
  507. //
  508. // The builtin conversions that correspond to `impl`s in the library all
  509. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  510. // being specialized in any of these cases.
  511. // If the value is already of the right kind and expression category, there's
  512. // nothing to do. Performing a conversion would decompose and rebuild tuples
  513. // and structs, so it's important that we bail out early in this case.
  514. if (value_type_id == target.type_id) {
  515. auto value_cat = SemIR::GetExpressionCategory(sem_ir, value_id);
  516. if (IsValidExpressionCategoryForConversionTarget(value_cat, target.kind)) {
  517. return value_id;
  518. }
  519. // If the source is an initializing expression, we may be able to pull a
  520. // value right out of it.
  521. if (value_cat == SemIR::ExpressionCategory::Initializing &&
  522. IsValidExpressionCategoryForConversionTarget(
  523. SemIR::ExpressionCategory::Value, target.kind) &&
  524. SemIR::GetInitializingRepresentation(sem_ir, value_type_id).kind ==
  525. SemIR::InitializingRepresentation::ByCopy) {
  526. auto value_rep = SemIR::GetValueRepresentation(sem_ir, value_type_id);
  527. if (value_rep.kind == SemIR::ValueRepresentation::Copy &&
  528. value_rep.type_id == value_type_id) {
  529. // The initializer produces an object representation by copy, and the
  530. // value representation is a copy of the object representation, so we
  531. // already have a value of the right form.
  532. return context.AddInst(
  533. SemIR::ValueOfInitializer{parse_node, value_type_id, value_id});
  534. }
  535. }
  536. }
  537. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  538. // converts to Ui.
  539. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  540. auto value_type_inst =
  541. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  542. if (auto src_tuple_type = value_type_inst.TryAs<SemIR::TupleType>()) {
  543. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  544. value_id, target);
  545. }
  546. }
  547. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  548. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  549. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  550. // to Ui.
  551. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  552. auto value_type_inst =
  553. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  554. if (auto src_struct_type = value_type_inst.TryAs<SemIR::StructType>()) {
  555. return ConvertStructToStruct(context, *src_struct_type,
  556. *target_struct_type, value_id, target);
  557. }
  558. }
  559. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  560. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  561. auto value_type_inst =
  562. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  563. if (auto src_tuple_type = value_type_inst.TryAs<SemIR::TupleType>()) {
  564. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  565. value_id, target);
  566. }
  567. }
  568. if (target.type_id == SemIR::TypeId::TypeType) {
  569. // A tuple of types converts to type `type`.
  570. // TODO: This should apply even for non-literal tuples.
  571. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  572. llvm::SmallVector<SemIR::TypeId> type_ids;
  573. for (auto tuple_inst_id :
  574. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  575. // TODO: This call recurses back into conversion. Switch to an
  576. // iterative approach.
  577. type_ids.push_back(
  578. ExpressionAsType(context, parse_node, tuple_inst_id));
  579. }
  580. auto tuple_type_id =
  581. context.CanonicalizeTupleType(parse_node, std::move(type_ids));
  582. return sem_ir.GetTypeAllowBuiltinTypes(tuple_type_id);
  583. }
  584. // `{}` converts to `{} as type`.
  585. // TODO: This conversion should also be performed for a non-literal value
  586. // of type `{}`.
  587. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  588. struct_literal &&
  589. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  590. value_id = sem_ir.GetTypeAllowBuiltinTypes(value_type_id);
  591. }
  592. }
  593. // No builtin conversion applies.
  594. return value_id;
  595. }
  596. // Given a value expression, form a corresponding initializer that copies from
  597. // that value, if it is possible to do so.
  598. static auto PerformCopy(Context& context, SemIR::InstId expr_id)
  599. -> SemIR::InstId {
  600. auto expr = context.insts().Get(expr_id);
  601. auto type_id = expr.type_id();
  602. if (type_id == SemIR::TypeId::Error) {
  603. return SemIR::InstId::BuiltinError;
  604. }
  605. // TODO: Directly track on the value representation whether it's a copy of
  606. // the object representation.
  607. auto value_rep = SemIR::GetValueRepresentation(context.sem_ir(), type_id);
  608. if (value_rep.kind == SemIR::ValueRepresentation::Copy &&
  609. value_rep.aggregate_kind == SemIR::ValueRepresentation::NotAggregate &&
  610. value_rep.type_id == type_id) {
  611. // For by-value scalar types, no explicit action is required. Initializing
  612. // from a value expression is treated as copying the value.
  613. return expr_id;
  614. }
  615. // TODO: We don't yet have rules for whether and when a class type is
  616. // copyable, or how to perform the copy.
  617. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  618. "Cannot copy value of type `{0}`.", std::string);
  619. context.emitter().Emit(expr.parse_node(), CopyOfUncopyableType,
  620. context.sem_ir().StringifyType(type_id));
  621. return SemIR::InstId::BuiltinError;
  622. }
  623. auto Convert(Context& context, Parse::Node parse_node, SemIR::InstId expr_id,
  624. ConversionTarget target) -> SemIR::InstId {
  625. auto& sem_ir = context.sem_ir();
  626. auto orig_expr_id = expr_id;
  627. // Start by making sure both sides are valid. If any part is invalid, the
  628. // result is invalid and we shouldn't error.
  629. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::TypeId::Error ||
  630. target.type_id == SemIR::TypeId::Error) {
  631. return SemIR::InstId::BuiltinError;
  632. }
  633. if (SemIR::GetExpressionCategory(sem_ir, expr_id) ==
  634. SemIR::ExpressionCategory::NotExpression) {
  635. // TODO: We currently encounter this for use of namespaces and functions.
  636. // We should provide a better diagnostic for inappropriate use of
  637. // namespace names, and allow use of functions as values.
  638. CARBON_DIAGNOSTIC(UseOfNonExpressionAsValue, Error,
  639. "Expression cannot be used as a value.");
  640. context.emitter().Emit(sem_ir.insts().Get(expr_id).parse_node(),
  641. UseOfNonExpressionAsValue);
  642. return SemIR::InstId::BuiltinError;
  643. }
  644. // We can only perform initialization for complete types.
  645. if (!context.TryToCompleteType(target.type_id, [&] {
  646. CARBON_DIAGNOSTIC(IncompleteTypeInInitialization, Error,
  647. "Initialization of incomplete type `{0}`.",
  648. std::string);
  649. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  650. "Forming value of incomplete type `{0}`.",
  651. std::string);
  652. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  653. "Invalid use of incomplete type `{0}`.", std::string);
  654. return context.emitter().Build(
  655. parse_node,
  656. target.is_initializer() ? IncompleteTypeInInitialization
  657. : target.kind == ConversionTarget::Value
  658. ? IncompleteTypeInValueConversion
  659. : IncompleteTypeInConversion,
  660. context.sem_ir().StringifyType(target.type_id, true));
  661. })) {
  662. return SemIR::InstId::BuiltinError;
  663. }
  664. // Check whether any builtin conversion applies.
  665. expr_id = PerformBuiltinConversion(context, parse_node, expr_id, target);
  666. if (expr_id == SemIR::InstId::BuiltinError) {
  667. return expr_id;
  668. }
  669. // If the types don't match at this point, we can't perform the conversion.
  670. // TODO: Look for an `ImplicitAs` impl, or an `As` impl in the case where
  671. // `target.kind == ConversionTarget::ExplicitAs`.
  672. SemIR::Inst expr = sem_ir.insts().Get(expr_id);
  673. if (expr.type_id() != target.type_id) {
  674. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  675. "Cannot implicitly convert from `{0}` to `{1}`.",
  676. std::string, std::string);
  677. CARBON_DIAGNOSTIC(ExplicitAsConversionFailure, Error,
  678. "Cannot convert from `{0}` to `{1}` with `as`.",
  679. std::string, std::string);
  680. context.emitter()
  681. .Build(parse_node,
  682. target.kind == ConversionTarget::ExplicitAs
  683. ? ExplicitAsConversionFailure
  684. : ImplicitAsConversionFailure,
  685. sem_ir.StringifyType(expr.type_id()),
  686. sem_ir.StringifyType(target.type_id))
  687. .Emit();
  688. return SemIR::InstId::BuiltinError;
  689. }
  690. // For `as`, don't perform any value category conversions. In particular, an
  691. // identity conversion shouldn't change the expression category.
  692. if (target.kind == ConversionTarget::ExplicitAs) {
  693. return expr_id;
  694. }
  695. // Now perform any necessary value category conversions.
  696. switch (SemIR::GetExpressionCategory(sem_ir, expr_id)) {
  697. case SemIR::ExpressionCategory::NotExpression:
  698. case SemIR::ExpressionCategory::Mixed:
  699. CARBON_FATAL() << "Unexpected expression " << expr
  700. << " after builtin conversions";
  701. case SemIR::ExpressionCategory::Error:
  702. return SemIR::InstId::BuiltinError;
  703. case SemIR::ExpressionCategory::Initializing:
  704. if (target.is_initializer()) {
  705. if (orig_expr_id == expr_id) {
  706. // Don't fill in the return slot if we created the expression through
  707. // a conversion. In that case, we will have created it with the
  708. // target already set.
  709. // TODO: Find a better way to track whether we need to do this.
  710. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  711. *target.init_block);
  712. }
  713. break;
  714. }
  715. // Commit to using a temporary for this initializing expression.
  716. // TODO: Don't create a temporary if the initializing representation
  717. // is already a value representation.
  718. expr_id = FinalizeTemporary(context, expr_id,
  719. target.kind == ConversionTarget::Discarded);
  720. // We now have an ephemeral reference.
  721. [[fallthrough]];
  722. case SemIR::ExpressionCategory::DurableReference:
  723. case SemIR::ExpressionCategory::EphemeralReference:
  724. // If a reference expression is an acceptable result, we're done.
  725. if (target.kind == ConversionTarget::ValueOrReference ||
  726. target.kind == ConversionTarget::Discarded) {
  727. break;
  728. }
  729. // If we have a reference and don't want one, form a value binding.
  730. // TODO: Support types with custom value representations.
  731. expr_id = context.AddInst(
  732. SemIR::BindValue{expr.parse_node(), expr.type_id(), expr_id});
  733. // We now have a value expression.
  734. [[fallthrough]];
  735. case SemIR::ExpressionCategory::Value:
  736. // When initializing from a value, perform a copy.
  737. if (target.is_initializer()) {
  738. expr_id = PerformCopy(context, expr_id);
  739. }
  740. break;
  741. }
  742. // Perform a final destination store, if necessary.
  743. if (target.kind == ConversionTarget::FullInitializer) {
  744. if (auto init_rep =
  745. SemIR::GetInitializingRepresentation(sem_ir, target.type_id);
  746. init_rep.kind == SemIR::InitializingRepresentation::ByCopy) {
  747. target.init_block->InsertHere();
  748. expr_id = context.AddInst(SemIR::InitializeFrom{
  749. parse_node, target.type_id, expr_id, target.init_id});
  750. }
  751. }
  752. return expr_id;
  753. }
  754. auto Initialize(Context& context, Parse::Node parse_node,
  755. SemIR::InstId target_id, SemIR::InstId value_id)
  756. -> SemIR::InstId {
  757. PendingBlock target_block(context);
  758. return Convert(context, parse_node, value_id,
  759. {.kind = ConversionTarget::Initializer,
  760. .type_id = context.sem_ir().insts().Get(target_id).type_id(),
  761. .init_id = target_id,
  762. .init_block = &target_block});
  763. }
  764. auto ConvertToValueExpression(Context& context, SemIR::InstId expr_id)
  765. -> SemIR::InstId {
  766. auto expr = context.sem_ir().insts().Get(expr_id);
  767. return Convert(context, expr.parse_node(), expr_id,
  768. {.kind = ConversionTarget::Value, .type_id = expr.type_id()});
  769. }
  770. auto ConvertToValueOrReferenceExpression(Context& context,
  771. SemIR::InstId expr_id)
  772. -> SemIR::InstId {
  773. auto expr = context.sem_ir().insts().Get(expr_id);
  774. return Convert(
  775. context, expr.parse_node(), expr_id,
  776. {.kind = ConversionTarget::ValueOrReference, .type_id = expr.type_id()});
  777. }
  778. auto ConvertToValueOfType(Context& context, Parse::Node parse_node,
  779. SemIR::InstId value_id, SemIR::TypeId type_id)
  780. -> SemIR::InstId {
  781. return Convert(context, parse_node, value_id,
  782. {.kind = ConversionTarget::Value, .type_id = type_id});
  783. }
  784. auto ConvertToBoolValue(Context& context, Parse::Node parse_node,
  785. SemIR::InstId value_id) -> SemIR::InstId {
  786. return ConvertToValueOfType(
  787. context, parse_node, value_id,
  788. context.GetBuiltinType(SemIR::BuiltinKind::BoolType));
  789. }
  790. auto ConvertForExplicitAs(Context& context, Parse::Node as_node,
  791. SemIR::InstId value_id, SemIR::TypeId type_id)
  792. -> SemIR::InstId {
  793. return Convert(context, as_node, value_id,
  794. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  795. }
  796. CARBON_DIAGNOSTIC(InCallToFunction, Note, "Calling function declared here.");
  797. // Convert the object argument in a method call to match the `self` parameter.
  798. static auto ConvertSelf(Context& context, Parse::Node call_parse_node,
  799. Parse::Node callee_parse_node,
  800. SemIR::SelfParameter self_param, SemIR::InstId self_id)
  801. -> SemIR::InstId {
  802. if (!self_id.is_valid()) {
  803. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  804. "Missing object argument in method call.");
  805. context.emitter()
  806. .Build(call_parse_node, MissingObjectInMethodCall)
  807. .Note(callee_parse_node, InCallToFunction)
  808. .Emit();
  809. return SemIR::InstId::BuiltinError;
  810. }
  811. DiagnosticAnnotationScope annotate_diagnostics(
  812. &context.emitter(), [&](auto& builder) {
  813. CARBON_DIAGNOSTIC(
  814. InCallToFunctionSelf, Note,
  815. "Initializing `{0}` parameter of method declared here.",
  816. llvm::StringLiteral);
  817. builder.Note(self_param.parse_node, InCallToFunctionSelf,
  818. self_param.is_addr_self.index
  819. ? llvm::StringLiteral("addr self")
  820. : llvm::StringLiteral("self"));
  821. });
  822. // For `addr self`, take the address of the object argument.
  823. auto self_or_addr_id = self_id;
  824. if (self_param.is_addr_self.index) {
  825. self_or_addr_id =
  826. ConvertToValueOrReferenceExpression(context, self_or_addr_id);
  827. auto self = context.insts().Get(self_or_addr_id);
  828. switch (SemIR::GetExpressionCategory(context.sem_ir(), self_id)) {
  829. case SemIR::ExpressionCategory::Error:
  830. case SemIR::ExpressionCategory::DurableReference:
  831. case SemIR::ExpressionCategory::EphemeralReference:
  832. break;
  833. default:
  834. CARBON_DIAGNOSTIC(AddrSelfIsNonReference, Error,
  835. "`addr self` method cannot be invoked on a value.");
  836. context.emitter().Emit(call_parse_node, AddrSelfIsNonReference);
  837. return SemIR::InstId::BuiltinError;
  838. }
  839. self_or_addr_id = context.AddInst(SemIR::AddressOf{
  840. self.parse_node(),
  841. context.GetPointerType(self.parse_node(), self.type_id()),
  842. self_or_addr_id});
  843. }
  844. return ConvertToValueOfType(context, call_parse_node, self_or_addr_id,
  845. self_param.type_id);
  846. }
  847. auto ConvertCallArgs(Context& context, Parse::Node call_parse_node,
  848. SemIR::InstId self_id,
  849. llvm::ArrayRef<SemIR::InstId> arg_refs,
  850. SemIR::InstId return_storage_id,
  851. Parse::Node callee_parse_node,
  852. SemIR::InstBlockId implicit_param_refs_id,
  853. SemIR::InstBlockId param_refs_id) -> SemIR::InstBlockId {
  854. auto implicit_param_refs =
  855. context.sem_ir().inst_blocks().Get(implicit_param_refs_id);
  856. auto param_refs = context.sem_ir().inst_blocks().Get(param_refs_id);
  857. // If sizes mismatch, fail early.
  858. if (arg_refs.size() != param_refs.size()) {
  859. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  860. "{0} argument(s) passed to function expecting "
  861. "{1} argument(s).",
  862. int, int);
  863. context.emitter()
  864. .Build(call_parse_node, CallArgCountMismatch, arg_refs.size(),
  865. param_refs.size())
  866. .Note(callee_parse_node, InCallToFunction)
  867. .Emit();
  868. return SemIR::InstBlockId::Invalid;
  869. }
  870. // Start building a block to hold the converted arguments.
  871. llvm::SmallVector<SemIR::InstId> args;
  872. args.reserve(implicit_param_refs.size() + param_refs.size() +
  873. return_storage_id.is_valid());
  874. // Check implicit parameters.
  875. for (auto implicit_param_id : implicit_param_refs) {
  876. auto param = context.insts().Get(implicit_param_id);
  877. if (auto self_param = param.TryAs<SemIR::SelfParameter>()) {
  878. auto converted_self_id = ConvertSelf(
  879. context, call_parse_node, callee_parse_node, *self_param, self_id);
  880. if (converted_self_id == SemIR::InstId::BuiltinError) {
  881. return SemIR::InstBlockId::Invalid;
  882. }
  883. args.push_back(converted_self_id);
  884. } else {
  885. // TODO: Form argument values for implicit parameters.
  886. context.TODO(call_parse_node, "Call with implicit parameters");
  887. return SemIR::InstBlockId::Invalid;
  888. }
  889. }
  890. int diag_param_index;
  891. DiagnosticAnnotationScope annotate_diagnostics(
  892. &context.emitter(), [&](auto& builder) {
  893. CARBON_DIAGNOSTIC(
  894. InCallToFunctionParam, Note,
  895. "Initializing parameter {0} of function declared here.", int);
  896. builder.Note(callee_parse_node, InCallToFunctionParam,
  897. diag_param_index + 1);
  898. });
  899. // Check type conversions per-element.
  900. for (auto [i, arg_id, param_id] : llvm::enumerate(arg_refs, param_refs)) {
  901. diag_param_index = i;
  902. auto param_type_id = context.sem_ir().insts().Get(param_id).type_id();
  903. // TODO: Convert to the proper expression category. For now, we assume
  904. // parameters are all `let` bindings.
  905. auto converted_arg_id =
  906. ConvertToValueOfType(context, call_parse_node, arg_id, param_type_id);
  907. if (converted_arg_id == SemIR::InstId::BuiltinError) {
  908. return SemIR::InstBlockId::Invalid;
  909. }
  910. args.push_back(converted_arg_id);
  911. }
  912. // Track the return storage, if present.
  913. if (return_storage_id.is_valid()) {
  914. args.push_back(return_storage_id);
  915. }
  916. return context.inst_blocks().Add(args);
  917. }
  918. auto ExpressionAsType(Context& context, Parse::Node parse_node,
  919. SemIR::InstId value_id) -> SemIR::TypeId {
  920. return context.CanonicalizeType(ConvertToValueOfType(
  921. context, parse_node, value_id, SemIR::TypeId::TypeType));
  922. }
  923. } // namespace Carbon::Check