convert.cpp 51 KB

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