import_ref.cpp 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994
  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/import_ref.h"
  5. #include "common/check.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/parse/node_ids.h"
  11. #include "toolchain/sem_ir/constant.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/import_ir.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/inst_kind.h"
  17. #include "toolchain/sem_ir/type_info.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. // Adds the ImportIR, excluding the update to the check_ir_map.
  21. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  22. -> SemIR::ImportIRId {
  23. context.import_ir_constant_values().push_back(
  24. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  25. return context.import_irs().Add(import_ir);
  26. }
  27. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  28. auto ir_id = SemIR::ImportIRId::Invalid;
  29. if (import_ir.sem_ir != nullptr) {
  30. ir_id = AddImportIR(context, import_ir);
  31. } else {
  32. // We don't have a check_ir_id, so add without touching check_ir_map.
  33. ir_id = InternalAddImportIR(context, import_ir);
  34. }
  35. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl,
  36. "ApiForImpl must be the first IR");
  37. }
  38. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  39. -> SemIR::ImportIRId {
  40. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  41. if (!ir_id.is_valid()) {
  42. // Note this updates check_ir_map.
  43. ir_id = InternalAddImportIR(context, import_ir);
  44. } else if (import_ir.is_export) {
  45. // We're processing an `export import`. In case the IR was indirectly added
  46. // as a non-export, mark it as an export.
  47. context.import_irs().Get(ir_id).is_export = true;
  48. }
  49. return ir_id;
  50. }
  51. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  52. SemIR::EntityNameId entity_name_id =
  53. SemIR::EntityNameId::Invalid) -> SemIR::InstId {
  54. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  55. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  56. .entity_name_id = entity_name_id};
  57. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  58. context.MakeImportedLocAndInst(import_ir_inst_id, inst));
  59. // ImportRefs have a dedicated block because this may be called during
  60. // processing where the instruction shouldn't be inserted in the current inst
  61. // block.
  62. context.import_ref_ids().push_back(import_ref_id);
  63. return import_ref_id;
  64. }
  65. // Adds an import_ref instruction for an instruction that we have already loaded
  66. // from an imported IR, with a known constant value. This is useful when the
  67. // instruction has a symbolic constant value, in order to produce an instruction
  68. // that hold that symbolic constant.
  69. static auto AddLoadedImportRef(Context& context, SemIR::TypeId type_id,
  70. SemIR::ImportIRInst import_ir_inst,
  71. SemIR::ConstantId const_id) -> SemIR::InstId {
  72. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  73. SemIR::ImportRefLoaded inst = {
  74. .type_id = type_id,
  75. .import_ir_inst_id = import_ir_inst_id,
  76. .entity_name_id = SemIR::EntityNameId::Invalid};
  77. auto inst_id = context.AddPlaceholderInstInNoBlock(
  78. context.MakeImportedLocAndInst(import_ir_inst_id, inst));
  79. context.import_ref_ids().push_back(inst_id);
  80. context.constant_values().Set(inst_id, const_id);
  81. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  82. import_ir_inst.inst_id, const_id);
  83. return inst_id;
  84. }
  85. static auto GetCanonicalImportIRInst(Context& context,
  86. const SemIR::File* cursor_ir,
  87. SemIR::InstId cursor_inst_id)
  88. -> SemIR::ImportIRInst {
  89. while (true) {
  90. // Step through an instruction with an imported location to the imported
  91. // instruction.
  92. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  93. if (loc_id.is_import_ir_inst_id()) {
  94. auto import_ir_inst =
  95. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  96. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  97. cursor_inst_id = import_ir_inst.inst_id;
  98. continue;
  99. }
  100. // Step through export declarations to their exported value.
  101. if (auto export_decl =
  102. cursor_ir->insts().TryGetAs<SemIR::ExportDecl>(cursor_inst_id)) {
  103. cursor_inst_id = export_decl->value_id;
  104. continue;
  105. }
  106. // Reached a non-imported entity.
  107. break;
  108. }
  109. auto ir_id = SemIR::ImportIRId::Invalid;
  110. if (cursor_ir != &context.sem_ir()) {
  111. // This uses AddImportIR in case it was indirectly found, which can
  112. // happen with two or more steps of exports.
  113. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  114. .is_export = false,
  115. .sem_ir = cursor_ir});
  116. }
  117. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  118. }
  119. auto GetCanonicalImportIRInst(Context& context, SemIR::InstId inst_id)
  120. -> SemIR::ImportIRInst {
  121. return GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  122. }
  123. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  124. SemIR::ImportIRInst prev_import_ir_inst,
  125. SemIR::ImportIRId new_ir_id,
  126. const SemIR::File* new_import_ir,
  127. SemIR::InstId new_inst_id) -> void {
  128. auto new_import_ir_inst =
  129. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  130. if (new_import_ir_inst == prev_import_ir_inst) {
  131. return;
  132. }
  133. auto conflict_id =
  134. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id});
  135. context.DiagnoseDuplicateName(conflict_id, prev_id);
  136. }
  137. // Returns an instruction that has the specified constant value.
  138. static auto GetInstWithConstantValue(const SemIR::File& file,
  139. SemIR::ConstantId const_id)
  140. -> SemIR::InstId {
  141. if (!const_id.is_valid()) {
  142. return SemIR::InstId::Invalid;
  143. }
  144. // For template constants, the corresponding instruction has the desired
  145. // constant value.
  146. if (!const_id.is_symbolic()) {
  147. return file.constant_values().GetInstId(const_id);
  148. }
  149. // For abstract symbolic constants, the corresponding instruction has the
  150. // desired constant value.
  151. const auto& symbolic_const =
  152. file.constant_values().GetSymbolicConstant(const_id);
  153. if (!symbolic_const.generic_id.is_valid()) {
  154. return file.constant_values().GetInstId(const_id);
  155. }
  156. // For a symbolic constant in a generic, pick the corresponding instruction
  157. // out of the eval block for the generic.
  158. const auto& generic = file.generics().Get(symbolic_const.generic_id);
  159. auto block = generic.GetEvalBlock(symbolic_const.index.region());
  160. return file.inst_blocks().Get(block)[symbolic_const.index.index()];
  161. }
  162. namespace {
  163. class ImportRefResolver;
  164. // The result of attempting to resolve an imported instruction to a constant.
  165. struct ResolveResult {
  166. // The new constant value, if known.
  167. SemIR::ConstantId const_id;
  168. // Whether resolution has been attempted once and needs to be retried.
  169. bool retry = false;
  170. // Produces a resolve result that tries resolving this instruction again. If
  171. // `const_id` is specified, then this is the end of the second phase, and the
  172. // constant value will be passed to the next resolution attempt. Otherwise,
  173. // this is the end of the first phase.
  174. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  175. -> ResolveResult {
  176. return {.const_id = const_id, .retry = true};
  177. }
  178. // Produces a resolve result that provides the given constant value. Requires
  179. // that there is no new work.
  180. static auto Done(SemIR::ConstantId const_id) -> ResolveResult {
  181. return {.const_id = const_id};
  182. }
  183. };
  184. } // namespace
  185. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  186. SemIR::ConstantId const_id) -> ResolveResult;
  187. namespace {
  188. // A context within which we are performing an import. Tracks information about
  189. // the source and destination. This provides a restricted interface compared to
  190. // ImportResolver: in particular, it does not have access to a work list.
  191. // Therefore code that accepts an ImportContext is unable to enqueue new work.
  192. class ImportContext {
  193. public:
  194. // A generic that we have partially imported.
  195. struct PendingGeneric {
  196. SemIR::GenericId import_id;
  197. SemIR::GenericId local_id;
  198. };
  199. // A specific that we have partially imported.
  200. struct PendingSpecific {
  201. SemIR::SpecificId import_id;
  202. SemIR::SpecificId local_id;
  203. };
  204. explicit ImportContext(Context& context, SemIR::ImportIRId import_ir_id)
  205. : context_(context),
  206. import_ir_id_(import_ir_id),
  207. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  208. // Returns the file we are importing from.
  209. auto import_ir() -> const SemIR::File& { return import_ir_; }
  210. // Accessors into value stores of the file we are importing from.
  211. auto import_classes() -> decltype(auto) { return import_ir().classes(); }
  212. auto import_constant_values() -> decltype(auto) {
  213. return import_ir().constant_values();
  214. }
  215. auto import_entity_names() -> decltype(auto) {
  216. return import_ir().entity_names();
  217. }
  218. auto import_facet_types() -> decltype(auto) {
  219. return import_ir().facet_types();
  220. }
  221. auto import_functions() -> decltype(auto) { return import_ir().functions(); }
  222. auto import_generics() -> decltype(auto) { return import_ir().generics(); }
  223. auto import_identifiers() -> decltype(auto) {
  224. return import_ir().identifiers();
  225. }
  226. auto import_impls() -> decltype(auto) { return import_ir().impls(); }
  227. auto import_inst_blocks() -> decltype(auto) {
  228. return import_ir().inst_blocks();
  229. }
  230. auto import_insts() -> decltype(auto) { return import_ir().insts(); }
  231. auto import_interfaces() -> decltype(auto) {
  232. return import_ir().interfaces();
  233. }
  234. auto import_ints() -> decltype(auto) { return import_ir().ints(); }
  235. auto import_name_scopes() -> decltype(auto) {
  236. return import_ir().name_scopes();
  237. }
  238. auto import_specifics() -> decltype(auto) { return import_ir().specifics(); }
  239. auto import_string_literal_values() -> decltype(auto) {
  240. return import_ir().string_literal_values();
  241. }
  242. auto import_struct_type_fields() -> decltype(auto) {
  243. return import_ir().struct_type_fields();
  244. }
  245. auto import_type_blocks() -> decltype(auto) {
  246. return import_ir().type_blocks();
  247. }
  248. auto import_types() -> decltype(auto) { return import_ir().types(); }
  249. // Returns the local file's import ID for the IR we are importing from.
  250. auto import_ir_id() -> SemIR::ImportIRId { return import_ir_id_; }
  251. // A value store for local constant values of imported instructions. This maps
  252. // from `InstId`s in the import IR to corresponding `ConstantId`s in the local
  253. // IR.
  254. auto local_constant_values_for_import_insts() -> decltype(auto) {
  255. return local_context().import_ir_constant_values()[import_ir_id_.index];
  256. }
  257. // Returns the file we are importing into.
  258. auto local_ir() -> SemIR::File& { return context_.sem_ir(); }
  259. // Returns the type-checking context we are importing into.
  260. auto local_context() -> Context& { return context_; }
  261. // Accessors into value stores of the file we are importing into.
  262. auto local_classes() -> decltype(auto) { return local_ir().classes(); }
  263. auto local_constant_values() -> decltype(auto) {
  264. return local_ir().constant_values();
  265. }
  266. auto local_entity_names() -> decltype(auto) {
  267. return local_ir().entity_names();
  268. }
  269. auto local_facet_types() -> decltype(auto) {
  270. return local_ir().facet_types();
  271. }
  272. auto local_functions() -> decltype(auto) { return local_ir().functions(); }
  273. auto local_generics() -> decltype(auto) { return local_ir().generics(); }
  274. auto local_identifiers() -> decltype(auto) {
  275. return local_ir().identifiers();
  276. }
  277. auto local_impls() -> decltype(auto) { return local_ir().impls(); }
  278. auto local_import_ir_insts() -> decltype(auto) {
  279. return local_ir().import_ir_insts();
  280. }
  281. auto local_inst_blocks() -> decltype(auto) {
  282. return local_ir().inst_blocks();
  283. }
  284. auto local_insts() -> decltype(auto) { return local_ir().insts(); }
  285. auto local_interfaces() -> decltype(auto) { return local_ir().interfaces(); }
  286. auto local_ints() -> decltype(auto) { return local_ir().ints(); }
  287. auto local_name_scopes() -> decltype(auto) {
  288. return local_ir().name_scopes();
  289. }
  290. auto local_specifics() -> decltype(auto) { return local_ir().specifics(); }
  291. auto local_string_literal_values() -> decltype(auto) {
  292. return local_ir().string_literal_values();
  293. }
  294. auto local_struct_type_fields() -> decltype(auto) {
  295. return local_ir().struct_type_fields();
  296. }
  297. auto local_types() -> decltype(auto) { return local_ir().types(); }
  298. // Add a generic that has been partially imported but needs to be finished.
  299. auto AddPendingGeneric(PendingGeneric pending) -> void {
  300. pending_generics_.push_back(pending);
  301. }
  302. // Add a specific that has been partially imported but needs to be finished.
  303. auto AddPendingSpecific(PendingSpecific pending) -> void {
  304. pending_specifics_.push_back(pending);
  305. }
  306. protected:
  307. auto pending_generics() -> llvm::SmallVector<PendingGeneric>& {
  308. return pending_generics_;
  309. }
  310. auto pending_specifics() -> llvm::SmallVector<PendingSpecific>& {
  311. return pending_specifics_;
  312. }
  313. private:
  314. Context& context_;
  315. SemIR::ImportIRId import_ir_id_;
  316. const SemIR::File& import_ir_;
  317. // TODO: The following members don't belong here. This pending work mechanism
  318. // can probably be removed entirely if we stop importing generic eval blocks
  319. // and instead evaluate them directly in the imported IR.
  320. // Generics that we have partially imported but not yet finished importing.
  321. llvm::SmallVector<PendingGeneric> pending_generics_;
  322. // Specifics that we have partially imported but not yet finished importing.
  323. llvm::SmallVector<PendingSpecific> pending_specifics_;
  324. };
  325. // Resolves an instruction from an imported IR into a constant referring to the
  326. // current IR.
  327. //
  328. // Calling Resolve on an instruction operates in an iterative manner, tracking
  329. // Work items on work_stack_. At a high level, the loop is:
  330. //
  331. // 1. If a constant value is already known for the work item and was not set by
  332. // this work item, it's considered resolved.
  333. // - The constant check avoids performance costs of deduplication on add.
  334. // - If we've processed this work item before, then we now process it again.
  335. // It didn't complete last time, even though we have a constant value
  336. // already.
  337. //
  338. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  339. // in three phases. The first and second phases can add work to the worklist
  340. // and end in a retry, in which case those phases will be rerun once the
  341. // added work is done. The rerun cannot also end in a retry, so this results
  342. // in at most three calls, but in practice one or two calls is almost always
  343. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  344. // it's important to only perform expensive work once, even when the same
  345. // phase is rerun.
  346. //
  347. // - First phase:
  348. // - Gather all input constants necessary to form the constant value of the
  349. // instruction. Gathering constants directly adds unresolved values to
  350. // work_stack_.
  351. // - If HasNewWork() reports that any work was added, then return Retry():
  352. // this instruction needs another call to complete. Gather the
  353. // now-resolved constants and continue to the next step once the retry
  354. // happens.
  355. //
  356. // - Second phase:
  357. // - Build the constant value of the instruction.
  358. // - Gather all input constants necessary to finish importing the
  359. // instruction. This is only necessary for instructions like classes that
  360. // can be forward-declared. For these instructions, we first import the
  361. // constant value and then later import the rest of the declaration in
  362. // order to break cycles.
  363. // - If HasNewWork() reports that any work was added, then return
  364. // Retry(constant_value): this instruction needs another call to
  365. // complete. Gather the now-resolved constants and continue to the next
  366. // step once the retry happens.
  367. //
  368. // - Third phase:
  369. // - After the second phase, the constant value for the instruction is
  370. // already set, and will be passed back into TryResolve*Inst on retry. It
  371. // should not be created again.
  372. // - Fill in any remaining information to complete the import of the
  373. // instruction. For example, when importing a class declaration, build
  374. // the class scope and information about the definition.
  375. // - Return ResolveAs/ResolveAsConstant to finish the resolution process.
  376. // This will cause the Resolve loop to set a constant value if we didn't
  377. // retry at the end of the second phase.
  378. //
  379. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  380. // remain, and may no longer be at the top of the stack; update the state of
  381. // the work item to track what work still needs to be done.
  382. //
  383. // The same instruction can be enqueued for resolution multiple times. However,
  384. // we will only reach the second phase once: once a constant value is set, only
  385. // the resolution step that set it will retry.
  386. //
  387. // TODO: Fix class `extern` handling and merging, rewrite tests.
  388. // - check/testdata/class/cross_package_import.carbon
  389. // - check/testdata/class/extern.carbon
  390. // TODO: Fix function `extern` handling and merging, rewrite tests.
  391. // - check/testdata/function/declaration/import.carbon
  392. // - check/testdata/packages/cross_package_import.carbon
  393. class ImportRefResolver : public ImportContext {
  394. public:
  395. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  396. : ImportContext(context, import_ir_id) {}
  397. // Iteratively resolves an imported instruction's inner references until a
  398. // constant ID referencing the current IR is produced. See the class comment
  399. // for more details.
  400. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId {
  401. work_stack_.push_back({.inst_id = inst_id});
  402. while (!work_stack_.empty()) {
  403. auto work = work_stack_.back();
  404. CARBON_CHECK(work.inst_id.is_valid());
  405. // Step 1: check for a constant value.
  406. auto existing = FindResolvedConstId(work.inst_id);
  407. if (existing.const_id.is_valid() && !work.retry_with_constant_value) {
  408. work_stack_.pop_back();
  409. continue;
  410. }
  411. // Step 2: resolve the instruction.
  412. initial_work_ = work_stack_.size();
  413. auto [new_const_id, retry] =
  414. TryResolveInst(*this, work.inst_id, existing.const_id);
  415. CARBON_CHECK(!HasNewWork() || retry);
  416. CARBON_CHECK(
  417. !existing.const_id.is_valid() || existing.const_id == new_const_id,
  418. "Constant value changed in third phase.");
  419. if (!existing.const_id.is_valid()) {
  420. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  421. }
  422. // Step 3: pop or retry.
  423. if (retry) {
  424. work_stack_[initial_work_ - 1].retry_with_constant_value =
  425. new_const_id.is_valid();
  426. } else {
  427. work_stack_.pop_back();
  428. }
  429. }
  430. auto constant_id = local_constant_values_for_import_insts().Get(inst_id);
  431. CARBON_CHECK(constant_id.is_valid());
  432. return constant_id;
  433. }
  434. // Performs resolution for one instruction and then performs all work we
  435. // deferred.
  436. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  437. auto const_id = ResolveOneInst(inst_id);
  438. PerformPendingWork();
  439. return const_id;
  440. }
  441. // Wraps constant evaluation with logic to handle constants.
  442. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  443. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  444. }
  445. // Wraps constant evaluation with logic to handle types.
  446. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  447. if (!import_type_id.is_valid()) {
  448. return import_type_id;
  449. }
  450. auto import_type_const_id =
  451. import_ir().types().GetConstantId(import_type_id);
  452. CARBON_CHECK(import_type_const_id.is_valid());
  453. if (auto import_type_inst_id =
  454. import_ir().constant_values().GetInstId(import_type_const_id);
  455. SemIR::IsSingletonInstId(import_type_inst_id)) {
  456. // Builtins don't require constant resolution; we can use them directly.
  457. return local_context().GetSingletonType(import_type_inst_id);
  458. } else {
  459. return local_context().GetTypeIdForTypeConstant(
  460. ResolveConstant(import_type_id.AsConstantId()));
  461. }
  462. }
  463. // Returns true if new unresolved constants were found as part of this
  464. // `Resolve` step.
  465. auto HasNewWork() -> bool {
  466. CARBON_CHECK(initial_work_ <= work_stack_.size(),
  467. "Work shouldn't decrease");
  468. return initial_work_ < work_stack_.size();
  469. }
  470. // Returns the ConstantId for an InstId. Adds unresolved constants to
  471. // work_stack_.
  472. auto GetLocalConstantValueOrPush(SemIR::InstId inst_id) -> SemIR::ConstantId {
  473. auto const_id = local_constant_values_for_import_insts().Get(inst_id);
  474. if (!const_id.is_valid()) {
  475. work_stack_.push_back({.inst_id = inst_id});
  476. }
  477. return const_id;
  478. }
  479. private:
  480. // A step in work_stack_.
  481. struct Work {
  482. // The instruction to work on.
  483. SemIR::InstId inst_id;
  484. // Whether this work item set the constant value for the instruction and
  485. // requested a retry.
  486. bool retry_with_constant_value = false;
  487. };
  488. // The constant found by FindResolvedConstId.
  489. struct ResolvedConstId {
  490. // The constant for the instruction. Invalid if not yet resolved.
  491. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  492. // Instructions which are indirect but equivalent to the current instruction
  493. // being resolved, and should have their constant set to the same. Empty
  494. // when const_id is valid.
  495. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  496. };
  497. // Looks to see if an instruction has been resolved. If a constant is only
  498. // found indirectly, sets the constant for any indirect steps that don't
  499. // already have the constant. If a constant isn't found, returns the indirect
  500. // instructions so that they can have the resolved constant assigned later.
  501. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  502. ResolvedConstId result;
  503. if (auto existing_const_id =
  504. local_constant_values_for_import_insts().Get(inst_id);
  505. existing_const_id.is_valid()) {
  506. result.const_id = existing_const_id;
  507. return result;
  508. }
  509. const auto* cursor_ir = &import_ir();
  510. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  511. auto cursor_inst_id = inst_id;
  512. while (true) {
  513. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  514. if (!loc_id.is_import_ir_inst_id()) {
  515. return result;
  516. }
  517. auto ir_inst =
  518. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  519. const auto* prev_ir = cursor_ir;
  520. auto prev_inst_id = cursor_inst_id;
  521. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  522. cursor_ir_id = local_context().GetImportIRId(*cursor_ir);
  523. if (!cursor_ir_id.is_valid()) {
  524. // TODO: Should we figure out a location to assign here?
  525. cursor_ir_id =
  526. AddImportIR(local_context(), {.decl_id = SemIR::InstId::Invalid,
  527. .is_export = false,
  528. .sem_ir = cursor_ir});
  529. }
  530. cursor_inst_id = ir_inst.inst_id;
  531. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id,
  532. "{0}", cursor_ir->insts().Get(cursor_inst_id));
  533. if (auto const_id = local_context()
  534. .import_ir_constant_values()[cursor_ir_id.index]
  535. .Get(cursor_inst_id);
  536. const_id.is_valid()) {
  537. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  538. result.const_id = const_id;
  539. result.indirect_insts.clear();
  540. return result;
  541. } else {
  542. result.indirect_insts.push_back(
  543. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  544. }
  545. }
  546. }
  547. // Sets a resolved constant into the current and indirect instructions.
  548. auto SetResolvedConstId(SemIR::InstId inst_id,
  549. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  550. SemIR::ConstantId const_id) -> void {
  551. local_constant_values_for_import_insts().Set(inst_id, const_id);
  552. for (auto indirect_inst : indirect_insts) {
  553. local_context()
  554. .import_ir_constant_values()[indirect_inst.ir_id.index]
  555. .Set(indirect_inst.inst_id, const_id);
  556. }
  557. }
  558. auto PerformPendingWork() -> void;
  559. llvm::SmallVector<Work> work_stack_;
  560. // The size of work_stack_ at the start of resolving the current instruction.
  561. size_t initial_work_ = 0;
  562. };
  563. } // namespace
  564. static auto AddImportRef(ImportContext& context, SemIR::InstId inst_id,
  565. SemIR::EntityNameId entity_name_id =
  566. SemIR::EntityNameId::Invalid) -> SemIR::InstId {
  567. return AddImportRef(context.local_context(),
  568. {.ir_id = context.import_ir_id(), .inst_id = inst_id},
  569. entity_name_id);
  570. }
  571. static auto AddLoadedImportRef(ImportContext& context, SemIR::TypeId type_id,
  572. SemIR::InstId inst_id,
  573. SemIR::ConstantId const_id) -> SemIR::InstId {
  574. return AddLoadedImportRef(
  575. context.local_context(), type_id,
  576. {.ir_id = context.import_ir_id(), .inst_id = inst_id}, const_id);
  577. }
  578. static auto AddImportIRInst(ImportContext& context, SemIR::InstId inst_id)
  579. -> SemIR::ImportIRInstId {
  580. return context.local_import_ir_insts().Add(
  581. {.ir_id = context.import_ir_id(), .inst_id = inst_id});
  582. }
  583. // Returns the ConstantId for an InstId. Adds unresolved constants to
  584. // the resolver's work stack.
  585. static auto GetLocalConstantId(ImportRefResolver& resolver,
  586. SemIR::InstId inst_id) -> SemIR::ConstantId {
  587. return resolver.GetLocalConstantValueOrPush(inst_id);
  588. }
  589. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  590. // constants to the resolver's work stack.
  591. static auto GetLocalConstantId(ImportRefResolver& resolver,
  592. SemIR::ConstantId const_id)
  593. -> SemIR::ConstantId {
  594. return GetLocalConstantId(
  595. resolver, GetInstWithConstantValue(resolver.import_ir(), const_id));
  596. }
  597. // Returns the local constant InstId for an imported InstId.
  598. static auto GetLocalConstantInstId(ImportRefResolver& resolver,
  599. SemIR::InstId inst_id) -> SemIR::InstId {
  600. auto const_id = GetLocalConstantId(resolver, inst_id);
  601. return resolver.local_constant_values().GetInstIdIfValid(const_id);
  602. }
  603. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  604. // work_stack_.
  605. static auto GetLocalConstantId(ImportRefResolver& resolver,
  606. SemIR::TypeId type_id) -> SemIR::ConstantId {
  607. return GetLocalConstantId(resolver,
  608. resolver.import_types().GetConstantId(type_id));
  609. }
  610. // Returns the ConstantId for an InstId that is required to have already been
  611. // imported.
  612. static auto GetLocalConstantIdChecked(ImportContext& context,
  613. SemIR::InstId inst_id)
  614. -> SemIR::ConstantId {
  615. auto result_id =
  616. context.local_constant_values_for_import_insts().Get(inst_id);
  617. CARBON_CHECK(result_id.is_valid());
  618. return result_id;
  619. }
  620. // Returns the ConstantId for a ConstantId that is required to have already been
  621. // imported.
  622. static auto GetLocalConstantIdChecked(ImportContext& context,
  623. SemIR::ConstantId const_id)
  624. -> SemIR::ConstantId {
  625. return GetLocalConstantIdChecked(
  626. context, GetInstWithConstantValue(context.import_ir(), const_id));
  627. }
  628. // Returns the ConstantId for a TypeId that is required to have already been
  629. // imported.
  630. static auto GetLocalConstantIdChecked(ImportContext& context,
  631. SemIR::TypeId type_id)
  632. -> SemIR::ConstantId {
  633. return GetLocalConstantIdChecked(
  634. context, context.import_types().GetConstantId(type_id));
  635. }
  636. // Translates a NameId from the import IR to a local NameId.
  637. static auto GetLocalNameId(ImportContext& context, SemIR::NameId import_name_id)
  638. -> SemIR::NameId {
  639. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  640. return SemIR::NameId::ForIdentifier(context.local_identifiers().Add(
  641. context.import_identifiers().Get(ident_id)));
  642. }
  643. return import_name_id;
  644. }
  645. // Gets the local constant values corresponding to an imported inst block.
  646. static auto GetLocalInstBlockContents(ImportRefResolver& resolver,
  647. SemIR::InstBlockId import_block_id)
  648. -> llvm::SmallVector<SemIR::InstId> {
  649. llvm::SmallVector<SemIR::InstId> inst_ids;
  650. if (!import_block_id.is_valid() ||
  651. import_block_id == SemIR::InstBlockId::Empty) {
  652. return inst_ids;
  653. }
  654. // Import all the values in the block.
  655. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  656. inst_ids.reserve(import_block.size());
  657. for (auto import_inst_id : import_block) {
  658. auto const_id = GetLocalConstantId(resolver, import_inst_id);
  659. inst_ids.push_back(
  660. resolver.local_constant_values().GetInstIdIfValid(const_id));
  661. }
  662. return inst_ids;
  663. }
  664. // Gets a local canonical instruction block ID corresponding to an imported inst
  665. // block whose contents were already imported, for example by
  666. // GetLocalInstBlockContents.
  667. static auto GetLocalCanonicalInstBlockId(ImportContext& context,
  668. SemIR::InstBlockId import_block_id,
  669. llvm::ArrayRef<SemIR::InstId> contents)
  670. -> SemIR::InstBlockId {
  671. if (!import_block_id.is_valid()) {
  672. return SemIR::InstBlockId::Invalid;
  673. }
  674. return context.local_inst_blocks().AddCanonical(contents);
  675. }
  676. // Gets an incomplete local version of an imported generic. Most fields are
  677. // set in the third phase.
  678. static auto MakeIncompleteGeneric(ImportContext& context, SemIR::InstId decl_id,
  679. SemIR::GenericId generic_id)
  680. -> SemIR::GenericId {
  681. if (!generic_id.is_valid()) {
  682. return SemIR::GenericId::Invalid;
  683. }
  684. return context.local_generics().Add(
  685. {.decl_id = decl_id,
  686. .bindings_id = SemIR::InstBlockId::Invalid,
  687. .self_specific_id = SemIR::SpecificId::Invalid});
  688. }
  689. namespace {
  690. // Local information associated with an imported generic.
  691. struct GenericData {
  692. llvm::SmallVector<SemIR::InstId> bindings;
  693. };
  694. } // namespace
  695. // Gets a local version of the data associated with a generic.
  696. static auto GetLocalGenericData(ImportRefResolver& resolver,
  697. SemIR::GenericId generic_id) -> GenericData {
  698. if (!generic_id.is_valid()) {
  699. return GenericData();
  700. }
  701. const auto& generic = resolver.import_generics().Get(generic_id);
  702. return {.bindings = GetLocalInstBlockContents(resolver, generic.bindings_id)};
  703. }
  704. // Adds the given local generic data to the given generic.
  705. static auto SetGenericData(ImportContext& context,
  706. SemIR::GenericId import_generic_id,
  707. SemIR::GenericId new_generic_id,
  708. const GenericData& generic_data) -> void {
  709. if (!import_generic_id.is_valid()) {
  710. return;
  711. }
  712. const auto& import_generic = context.import_generics().Get(import_generic_id);
  713. auto& new_generic = context.local_generics().Get(new_generic_id);
  714. new_generic.bindings_id = GetLocalCanonicalInstBlockId(
  715. context, import_generic.bindings_id, generic_data.bindings);
  716. // Track that we need to fill in the remaining information in
  717. // FinishPendingGeneric.
  718. context.AddPendingGeneric(
  719. {.import_id = import_generic_id, .local_id = new_generic_id});
  720. }
  721. // Gets a local constant value corresponding to an imported generic ID. May
  722. // add work to the work stack and return `Invalid`.
  723. static auto GetLocalConstantId(ImportRefResolver& resolver,
  724. SemIR::GenericId generic_id)
  725. -> SemIR::ConstantId {
  726. if (!generic_id.is_valid()) {
  727. return SemIR::ConstantId::Invalid;
  728. }
  729. auto import_decl_inst_id = resolver.import_generics().Get(generic_id).decl_id;
  730. auto import_decl_inst = resolver.import_insts().Get(import_decl_inst_id);
  731. if (import_decl_inst.Is<SemIR::ImplDecl>()) {
  732. // For an impl declaration, the imported entity can be found via the
  733. // declaration.
  734. return GetLocalConstantId(resolver, import_decl_inst_id);
  735. }
  736. // For all other kinds of declaration, the imported entity can be found via
  737. // the type of the declaration.
  738. return GetLocalConstantId(resolver, import_decl_inst.type_id());
  739. }
  740. // Gets a local generic ID given the corresponding local constant ID returned
  741. // by GetLocalConstantId for the imported generic. Does not add any new work.
  742. static auto GetLocalGenericId(ImportContext& context,
  743. SemIR::ConstantId local_const_id)
  744. -> SemIR::GenericId {
  745. if (!local_const_id.is_valid()) {
  746. return SemIR::GenericId::Invalid;
  747. }
  748. auto inst = context.local_insts().Get(
  749. context.local_constant_values().GetInstId(local_const_id));
  750. CARBON_KIND_SWITCH(inst) {
  751. case CARBON_KIND(SemIR::FunctionType fn_type): {
  752. return context.local_functions().Get(fn_type.function_id).generic_id;
  753. }
  754. case CARBON_KIND(SemIR::GenericClassType class_type): {
  755. return context.local_classes().Get(class_type.class_id).generic_id;
  756. }
  757. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  758. return context.local_interfaces()
  759. .Get(interface_type.interface_id)
  760. .generic_id;
  761. }
  762. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  763. return context.local_impls().Get(impl_decl.impl_id).generic_id;
  764. }
  765. default: {
  766. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  767. }
  768. }
  769. }
  770. namespace {
  771. // Local information associated with an imported specific.
  772. struct SpecificData {
  773. SemIR::ConstantId generic_const_id;
  774. llvm::SmallVector<SemIR::InstId> args;
  775. };
  776. } // namespace
  777. // Gets local information about an imported specific.
  778. static auto GetLocalSpecificData(ImportRefResolver& resolver,
  779. SemIR::SpecificId specific_id)
  780. -> SpecificData {
  781. if (!specific_id.is_valid()) {
  782. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  783. }
  784. const auto& specific = resolver.import_specifics().Get(specific_id);
  785. return {
  786. .generic_const_id = GetLocalConstantId(resolver, specific.generic_id),
  787. .args = GetLocalInstBlockContents(resolver, specific.args_id),
  788. };
  789. }
  790. // Gets a local specific whose data was already imported by
  791. // GetLocalSpecificData. Does not add any new work.
  792. static auto GetOrAddLocalSpecific(ImportContext& context,
  793. SemIR::SpecificId import_specific_id,
  794. const SpecificData& data)
  795. -> SemIR::SpecificId {
  796. if (!import_specific_id.is_valid()) {
  797. return SemIR::SpecificId::Invalid;
  798. }
  799. // Form a corresponding local specific ID.
  800. const auto& import_specific =
  801. context.import_specifics().Get(import_specific_id);
  802. auto generic_id = GetLocalGenericId(context, data.generic_const_id);
  803. auto args_id =
  804. GetLocalCanonicalInstBlockId(context, import_specific.args_id, data.args);
  805. // Get the specific.
  806. auto specific_id = context.local_specifics().GetOrAdd(generic_id, args_id);
  807. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  808. auto& specific = context.local_specifics().Get(specific_id);
  809. if (!specific.decl_block_id.is_valid() ||
  810. (import_specific.definition_block_id.is_valid() &&
  811. !specific.definition_block_id.is_valid())) {
  812. context.AddPendingSpecific(
  813. {.import_id = import_specific_id, .local_id = specific_id});
  814. }
  815. return specific_id;
  816. }
  817. // Adds unresolved constants for each parameter's type to the resolver's work
  818. // stack.
  819. static auto LoadLocalPatternConstantIds(ImportRefResolver& resolver,
  820. SemIR::InstBlockId param_patterns_id)
  821. -> void {
  822. if (!param_patterns_id.is_valid() ||
  823. param_patterns_id == SemIR::InstBlockId::Empty) {
  824. return;
  825. }
  826. const auto& param_patterns =
  827. resolver.import_inst_blocks().Get(param_patterns_id);
  828. for (auto pattern_id : param_patterns) {
  829. auto pattern_inst = resolver.import_insts().Get(pattern_id);
  830. GetLocalConstantId(resolver, pattern_inst.type_id());
  831. if (auto addr = pattern_inst.TryAs<SemIR::AddrPattern>()) {
  832. pattern_id = addr->inner_id;
  833. pattern_inst = resolver.import_insts().Get(pattern_id);
  834. GetLocalConstantId(resolver, pattern_inst.type_id());
  835. }
  836. pattern_id = resolver.import_insts()
  837. .GetAs<SemIR::ValueParamPattern>(pattern_id)
  838. .subpattern_id;
  839. pattern_inst = resolver.import_insts().Get(pattern_id);
  840. // If the parameter is a symbolic binding, build the
  841. // SymbolicBindingPattern constant.
  842. if (pattern_inst.Is<SemIR::SymbolicBindingPattern>()) {
  843. GetLocalConstantId(resolver, pattern_id);
  844. }
  845. }
  846. }
  847. // Returns a version of param_patterns_id localized to the current IR.
  848. //
  849. // Must only be called after a call to
  850. // LoadLocalPatternConstantIds(param_patterns_id) has completed without adding
  851. // any new work to work_stack_.
  852. //
  853. // TODO: This is inconsistent with the rest of this class, which expects
  854. // the relevant constants to be explicitly passed in. That makes it
  855. // easier to statically detect when an input isn't loaded, but makes it
  856. // harder to support importing more complex inst structures. We should
  857. // take a holistic look at how to balance those concerns. For example,
  858. // could the same function be used to load the constants and use them, with
  859. // a parameter to select between the two?
  860. static auto GetLocalParamPatternsId(ImportContext& context,
  861. SemIR::InstBlockId param_patterns_id)
  862. -> SemIR::InstBlockId {
  863. if (!param_patterns_id.is_valid() ||
  864. param_patterns_id == SemIR::InstBlockId::Empty) {
  865. return param_patterns_id;
  866. }
  867. const auto& param_patterns =
  868. context.import_inst_blocks().Get(param_patterns_id);
  869. llvm::SmallVector<SemIR::InstId> new_patterns;
  870. for (auto param_id : param_patterns) {
  871. // Figure out the pattern structure. This echoes
  872. // Function::GetParamPatternInfoFromPatternId.
  873. auto addr_pattern_id = param_id;
  874. auto addr_inst =
  875. context.import_insts().TryGetAs<SemIR::AddrPattern>(addr_pattern_id);
  876. auto param_pattern_id = addr_pattern_id;
  877. if (addr_inst) {
  878. param_pattern_id = addr_inst->inner_id;
  879. }
  880. auto param_pattern = context.import_insts().GetAs<SemIR::ValueParamPattern>(
  881. param_pattern_id);
  882. auto binding_id = param_pattern.subpattern_id;
  883. auto binding =
  884. context.import_insts().GetAs<SemIR::AnyBindingPattern>(binding_id);
  885. // Rebuild the pattern.
  886. auto entity_name =
  887. context.import_entity_names().Get(binding.entity_name_id);
  888. auto name_id = GetLocalNameId(context, entity_name.name_id);
  889. auto type_id = context.local_context().GetTypeIdForTypeConstant(
  890. GetLocalConstantIdChecked(context, binding.type_id));
  891. auto new_param_id = SemIR::InstId::Invalid;
  892. switch (binding.kind) {
  893. case SemIR::BindingPattern::Kind: {
  894. auto entity_name_id = context.local_entity_names().Add(
  895. {.name_id = name_id,
  896. .parent_scope_id = SemIR::NameScopeId::Invalid,
  897. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  898. new_param_id =
  899. context.local_context().AddInstInNoBlock<SemIR::BindingPattern>(
  900. AddImportIRInst(context, binding_id),
  901. {.type_id = type_id, .entity_name_id = entity_name_id});
  902. break;
  903. }
  904. case SemIR::SymbolicBindingPattern::Kind: {
  905. // We already imported a constant value for this symbolic binding.
  906. // We can reuse most of it, but update the value to point to our
  907. // specific parameter, and preserve the constant value.
  908. auto bind_const_id = GetLocalConstantIdChecked(context, binding_id);
  909. auto new_binding_inst =
  910. context.local_insts().GetAs<SemIR::SymbolicBindingPattern>(
  911. context.local_constant_values().GetInstId(bind_const_id));
  912. new_param_id = context.local_context().AddInstInNoBlock(
  913. AddImportIRInst(context, binding_id), new_binding_inst);
  914. context.local_constant_values().Set(new_param_id, bind_const_id);
  915. break;
  916. }
  917. default: {
  918. CARBON_FATAL("Unexpected kind: ", binding.kind);
  919. }
  920. }
  921. new_param_id = context.local_context().AddInstInNoBlock(
  922. context.local_context()
  923. .MakeImportedLocAndInst<SemIR::ValueParamPattern>(
  924. AddImportIRInst(context, param_pattern_id),
  925. {.type_id = type_id,
  926. .subpattern_id = new_param_id,
  927. .runtime_index = param_pattern.runtime_index}));
  928. if (addr_inst) {
  929. type_id = context.local_context().GetTypeIdForTypeConstant(
  930. GetLocalConstantIdChecked(context, addr_inst->type_id));
  931. new_param_id = context.local_context().AddInstInNoBlock(
  932. context.local_context().MakeImportedLocAndInst<SemIR::AddrPattern>(
  933. AddImportIRInst(context, addr_pattern_id),
  934. {.type_id = type_id, .inner_id = new_param_id}));
  935. }
  936. new_patterns.push_back(new_param_id);
  937. }
  938. return context.local_inst_blocks().Add(new_patterns);
  939. }
  940. // Returns a version of import_return_slot_pattern_id localized to the current
  941. // IR.
  942. static auto GetLocalReturnSlotPatternId(
  943. ImportContext& context, SemIR::InstId import_return_slot_pattern_id)
  944. -> SemIR::InstId {
  945. if (!import_return_slot_pattern_id.is_valid()) {
  946. return SemIR::InstId::Invalid;
  947. }
  948. auto param_pattern = context.import_insts().GetAs<SemIR::OutParamPattern>(
  949. import_return_slot_pattern_id);
  950. auto return_slot_pattern =
  951. context.import_insts().GetAs<SemIR::ReturnSlotPattern>(
  952. param_pattern.subpattern_id);
  953. auto type_id = context.local_context().GetTypeIdForTypeConstant(
  954. GetLocalConstantIdChecked(context, return_slot_pattern.type_id));
  955. auto new_return_slot_pattern_id = context.local_context().AddInstInNoBlock(
  956. context.local_context().MakeImportedLocAndInst<SemIR::ReturnSlotPattern>(
  957. AddImportIRInst(context, param_pattern.subpattern_id),
  958. {.type_id = type_id, .type_inst_id = SemIR::InstId::Invalid}));
  959. return context.local_context().AddInstInNoBlock(
  960. context.local_context().MakeImportedLocAndInst<SemIR::OutParamPattern>(
  961. AddImportIRInst(context, import_return_slot_pattern_id),
  962. {.type_id = type_id,
  963. .subpattern_id = new_return_slot_pattern_id,
  964. .runtime_index = param_pattern.runtime_index}));
  965. }
  966. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  967. // unresolved constants to the resolver's work stack.
  968. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  969. SemIR::NameScopeId name_scope_id)
  970. -> SemIR::NameScopeId {
  971. // Get the instruction that created the scope.
  972. auto [inst_id, inst] =
  973. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  974. if (!inst) {
  975. // Map scopes that aren't associated with an instruction to invalid
  976. // scopes. For now, such scopes aren't used, and we don't have a good way
  977. // to remap them.
  978. return SemIR::NameScopeId::Invalid;
  979. }
  980. // Get the constant value for the scope.
  981. auto const_id = GetLocalConstantId(resolver, inst_id);
  982. if (!const_id.is_valid()) {
  983. return SemIR::NameScopeId::Invalid;
  984. }
  985. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  986. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  987. CARBON_KIND_SWITCH(name_scope_inst) {
  988. case CARBON_KIND(SemIR::Namespace inst): {
  989. return inst.name_scope_id;
  990. }
  991. case CARBON_KIND(SemIR::ClassType inst): {
  992. return resolver.local_classes().Get(inst.class_id).scope_id;
  993. }
  994. case CARBON_KIND(SemIR::FacetType inst): {
  995. const SemIR::FacetTypeInfo& facet_type_info =
  996. resolver.local_facet_types().Get(inst.facet_type_id);
  997. // This is specifically the facet type produced by an interface
  998. // declaration, and so should consist of a single interface.
  999. // TODO: Will also have to handle named constraints here, once those are
  1000. // implemented.
  1001. auto interface = facet_type_info.TryAsSingleInterface();
  1002. CARBON_CHECK(interface);
  1003. return resolver.local_interfaces().Get(interface->interface_id).scope_id;
  1004. }
  1005. case CARBON_KIND(SemIR::ImplDecl inst): {
  1006. return resolver.local_impls().Get(inst.impl_id).scope_id;
  1007. }
  1008. case SemIR::StructValue::Kind: {
  1009. auto type_inst =
  1010. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  1011. CARBON_KIND_SWITCH(type_inst) {
  1012. case CARBON_KIND(SemIR::GenericClassType inst): {
  1013. return resolver.local_classes().Get(inst.class_id).scope_id;
  1014. }
  1015. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  1016. return resolver.local_interfaces().Get(inst.interface_id).scope_id;
  1017. }
  1018. default: {
  1019. break;
  1020. }
  1021. }
  1022. break;
  1023. }
  1024. default: {
  1025. if (const_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1026. return SemIR::NameScopeId::Invalid;
  1027. }
  1028. break;
  1029. }
  1030. }
  1031. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  1032. name_scope_inst);
  1033. }
  1034. // Given an imported entity base, returns an incomplete, local version of it.
  1035. //
  1036. // Most fields are set in the third phase once they're imported. Import enough
  1037. // of the parameter lists that we know whether this interface is a generic
  1038. // interface and can build the right constant value for it.
  1039. //
  1040. // TODO: Support extern.
  1041. static auto GetIncompleteLocalEntityBase(
  1042. ImportContext& context, SemIR::InstId decl_id,
  1043. const SemIR::EntityWithParamsBase& import_base)
  1044. -> SemIR::EntityWithParamsBase {
  1045. // Translate the extern_library_id if present.
  1046. auto extern_library_id = SemIR::LibraryNameId::Invalid;
  1047. if (import_base.extern_library_id.is_valid()) {
  1048. if (import_base.extern_library_id.index >= 0) {
  1049. auto val = context.import_string_literal_values().Get(
  1050. import_base.extern_library_id.AsStringLiteralValueId());
  1051. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  1052. context.local_string_literal_values().Add(val));
  1053. } else {
  1054. extern_library_id = import_base.extern_library_id;
  1055. }
  1056. }
  1057. return {
  1058. .name_id = GetLocalNameId(context, import_base.name_id),
  1059. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1060. .generic_id =
  1061. MakeIncompleteGeneric(context, decl_id, import_base.generic_id),
  1062. .first_param_node_id = Parse::NodeId::Invalid,
  1063. .last_param_node_id = Parse::NodeId::Invalid,
  1064. .pattern_block_id = SemIR::InstBlockId::Invalid,
  1065. .implicit_param_patterns_id =
  1066. import_base.implicit_param_patterns_id.is_valid()
  1067. ? SemIR::InstBlockId::Empty
  1068. : SemIR::InstBlockId::Invalid,
  1069. .param_patterns_id = import_base.param_patterns_id.is_valid()
  1070. ? SemIR::InstBlockId::Empty
  1071. : SemIR::InstBlockId::Invalid,
  1072. .call_params_id = SemIR::InstBlockId::Invalid,
  1073. .is_extern = import_base.is_extern,
  1074. .extern_library_id = extern_library_id,
  1075. .non_owning_decl_id = import_base.non_owning_decl_id.is_valid()
  1076. ? decl_id
  1077. : SemIR::InstId::Invalid,
  1078. .first_owning_decl_id = import_base.first_owning_decl_id.is_valid()
  1079. ? decl_id
  1080. : SemIR::InstId::Invalid,
  1081. };
  1082. }
  1083. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1084. // lookup.
  1085. static auto AddNameScopeImportRefs(ImportContext& context,
  1086. const SemIR::NameScope& import_scope,
  1087. SemIR::NameScope& new_scope) -> void {
  1088. for (auto entry : import_scope.entries()) {
  1089. if (entry.inst_id.is_poisoned()) {
  1090. continue;
  1091. }
  1092. auto ref_id = AddImportRef(context, entry.inst_id);
  1093. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1094. .inst_id = ref_id,
  1095. .access_kind = entry.access_kind});
  1096. }
  1097. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1098. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1099. }
  1100. }
  1101. // Given a block ID for a list of associated entities of a witness, returns a
  1102. // version localized to the current IR.
  1103. static auto AddAssociatedEntities(ImportContext& context,
  1104. SemIR::NameScopeId local_name_scope_id,
  1105. SemIR::InstBlockId associated_entities_id)
  1106. -> SemIR::InstBlockId {
  1107. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1108. return SemIR::InstBlockId::Empty;
  1109. }
  1110. auto associated_entities =
  1111. context.import_inst_blocks().Get(associated_entities_id);
  1112. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1113. new_associated_entities.reserve(associated_entities.size());
  1114. for (auto inst_id : associated_entities) {
  1115. // Determine the name of the associated entity, by switching on its kind.
  1116. SemIR::NameId import_name_id = SemIR::NameId::Invalid;
  1117. if (auto associated_const =
  1118. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1119. inst_id)) {
  1120. import_name_id = associated_const->name_id;
  1121. } else if (auto function_decl =
  1122. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1123. inst_id)) {
  1124. auto function =
  1125. context.import_functions().Get(function_decl->function_id);
  1126. import_name_id = function.name_id;
  1127. } else if (auto import_ref =
  1128. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1129. inst_id)) {
  1130. import_name_id =
  1131. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1132. } else {
  1133. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1134. context.import_insts().Get(inst_id).kind());
  1135. }
  1136. auto name_id = GetLocalNameId(context, import_name_id);
  1137. auto entity_name_id = context.local_entity_names().Add(
  1138. {.name_id = name_id,
  1139. .parent_scope_id = local_name_scope_id,
  1140. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  1141. new_associated_entities.push_back(
  1142. AddImportRef(context, inst_id, entity_name_id));
  1143. }
  1144. return context.local_inst_blocks().Add(new_associated_entities);
  1145. }
  1146. // Produces a resolve result that provides the given constant value. Retries
  1147. // instead if work has been added.
  1148. static auto RetryOrDone(ImportRefResolver& resolver, SemIR::ConstantId const_id)
  1149. -> ResolveResult {
  1150. if (resolver.HasNewWork()) {
  1151. return ResolveResult::Retry();
  1152. }
  1153. return ResolveResult::Done(const_id);
  1154. }
  1155. // Produces a resolve result for the given instruction that describes a constant
  1156. // value. This should only be used for instructions that describe constants, and
  1157. // not for instructions that represent declarations. For a declaration, we need
  1158. // an associated location, so AddInstInNoBlock should be used instead. Requires
  1159. // that there is no new work.
  1160. static auto ResolveAsUntyped(ImportContext& context, SemIR::Inst inst)
  1161. -> ResolveResult {
  1162. auto result =
  1163. TryEvalInst(context.local_context(), SemIR::InstId::Invalid, inst);
  1164. CARBON_CHECK(result.is_constant(), "{0} is not constant", inst);
  1165. return ResolveResult::Done(result);
  1166. }
  1167. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1168. template <typename InstT>
  1169. static auto ResolveAs(ImportContext& context, InstT inst) -> ResolveResult {
  1170. return ResolveAsUntyped(context, inst);
  1171. }
  1172. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1173. SemIR::AdaptDecl inst,
  1174. SemIR::InstId import_inst_id) -> ResolveResult {
  1175. auto adapted_type_const_id = GetLocalConstantId(
  1176. resolver,
  1177. resolver.import_constant_values().Get(inst.adapted_type_inst_id));
  1178. if (resolver.HasNewWork()) {
  1179. return ResolveResult::Retry();
  1180. }
  1181. auto adapted_type_inst_id =
  1182. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1183. inst.adapted_type_inst_id, adapted_type_const_id);
  1184. // Create a corresponding instruction to represent the declaration.
  1185. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1186. resolver.local_context().MakeImportedLocAndInst<SemIR::AdaptDecl>(
  1187. AddImportIRInst(resolver, import_inst_id),
  1188. {.adapted_type_inst_id = adapted_type_inst_id}));
  1189. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  1190. }
  1191. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1192. SemIR::ArrayType inst) -> ResolveResult {
  1193. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1194. auto element_type_const_id =
  1195. GetLocalConstantId(resolver, inst.element_type_id);
  1196. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1197. if (resolver.HasNewWork()) {
  1198. return ResolveResult::Retry();
  1199. }
  1200. auto element_type_id =
  1201. resolver.local_context().GetTypeIdForTypeConstant(element_type_const_id);
  1202. return ResolveAs<SemIR::ArrayType>(
  1203. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1204. .bound_id = bound_id,
  1205. .element_type_id = element_type_id});
  1206. }
  1207. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1208. SemIR::AssociatedEntity inst) -> ResolveResult {
  1209. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1210. if (resolver.HasNewWork()) {
  1211. return ResolveResult::Retry();
  1212. }
  1213. // Add a lazy reference to the target declaration.
  1214. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1215. return ResolveAs<SemIR::AssociatedEntity>(
  1216. resolver, {.type_id = resolver.local_context().GetTypeIdForTypeConstant(
  1217. type_const_id),
  1218. .index = inst.index,
  1219. .decl_id = decl_id});
  1220. }
  1221. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1222. SemIR::AssociatedEntityType inst)
  1223. -> ResolveResult {
  1224. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1225. auto entity_type_const_id = GetLocalConstantId(resolver, inst.entity_type_id);
  1226. auto interface_inst_id = GetLocalConstantId(resolver, inst.interface_type_id);
  1227. if (resolver.HasNewWork()) {
  1228. return ResolveResult::Retry();
  1229. }
  1230. return ResolveAs<SemIR::AssociatedEntityType>(
  1231. resolver,
  1232. {.type_id = SemIR::TypeType::SingletonTypeId,
  1233. .interface_type_id =
  1234. resolver.local_context().GetTypeIdForTypeConstant(interface_inst_id),
  1235. .entity_type_id = resolver.local_context().GetTypeIdForTypeConstant(
  1236. entity_type_const_id)});
  1237. }
  1238. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1239. SemIR::BaseDecl inst,
  1240. SemIR::InstId import_inst_id) -> ResolveResult {
  1241. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1242. auto base_type_const_id = GetLocalConstantId(
  1243. resolver, resolver.import_constant_values().Get(inst.base_type_inst_id));
  1244. if (resolver.HasNewWork()) {
  1245. return ResolveResult::Retry();
  1246. }
  1247. auto base_type_inst_id =
  1248. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1249. inst.base_type_inst_id, base_type_const_id);
  1250. // Create a corresponding instruction to represent the declaration.
  1251. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1252. resolver.local_context().MakeImportedLocAndInst<SemIR::BaseDecl>(
  1253. AddImportIRInst(resolver, import_inst_id),
  1254. {.type_id =
  1255. resolver.local_context().GetTypeIdForTypeConstant(type_const_id),
  1256. .base_type_inst_id = base_type_inst_id,
  1257. .index = inst.index}));
  1258. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  1259. }
  1260. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1261. SemIR::BindAlias inst) -> ResolveResult {
  1262. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1263. return RetryOrDone(resolver, value_id);
  1264. }
  1265. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1266. SemIR::BindSymbolicName inst) -> ResolveResult {
  1267. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1268. if (resolver.HasNewWork()) {
  1269. return ResolveResult::Retry();
  1270. }
  1271. const auto& import_entity_name =
  1272. resolver.import_entity_names().Get(inst.entity_name_id);
  1273. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1274. auto entity_name_id = resolver.local_entity_names().Add(
  1275. {.name_id = name_id,
  1276. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1277. .bind_index = import_entity_name.bind_index});
  1278. return ResolveAs<SemIR::BindSymbolicName>(
  1279. resolver,
  1280. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1281. .entity_name_id = entity_name_id,
  1282. .value_id = SemIR::InstId::Invalid});
  1283. }
  1284. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1285. SemIR::SymbolicBindingPattern inst)
  1286. -> ResolveResult {
  1287. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1288. if (resolver.HasNewWork()) {
  1289. return ResolveResult::Retry();
  1290. }
  1291. const auto& import_entity_name =
  1292. resolver.import_entity_names().Get(inst.entity_name_id);
  1293. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1294. auto entity_name_id = resolver.local_entity_names().Add(
  1295. {.name_id = name_id,
  1296. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1297. .bind_index = import_entity_name.bind_index});
  1298. return ResolveAs<SemIR::SymbolicBindingPattern>(
  1299. resolver,
  1300. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1301. .entity_name_id = entity_name_id});
  1302. }
  1303. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1304. SemIR::BoundMethod inst) -> ResolveResult {
  1305. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1306. SemIR::BoundMethodType::SingletonInstId);
  1307. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1308. auto function_id = GetLocalConstantInstId(resolver, inst.function_id);
  1309. if (resolver.HasNewWork()) {
  1310. return ResolveResult::Retry();
  1311. }
  1312. return ResolveAs<SemIR::BoundMethod>(
  1313. resolver, {.type_id = resolver.local_context().GetSingletonType(
  1314. SemIR::BoundMethodType::SingletonInstId),
  1315. .object_id = object_id,
  1316. .function_id = function_id});
  1317. }
  1318. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1319. -> ResolveResult {
  1320. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1321. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1322. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1323. if (resolver.HasNewWork()) {
  1324. return ResolveResult::Retry();
  1325. }
  1326. return ResolveAs<SemIR::Call>(
  1327. resolver,
  1328. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1329. .callee_id = callee_id,
  1330. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1331. }
  1332. // Makes an incomplete class. This is necessary even with classes with a
  1333. // complete declaration, because things such as `Self` may refer back to the
  1334. // type.
  1335. static auto MakeIncompleteClass(ImportContext& context,
  1336. const SemIR::Class& import_class,
  1337. SemIR::SpecificId enclosing_specific_id)
  1338. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1339. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::SingletonTypeId,
  1340. .class_id = SemIR::ClassId::Invalid,
  1341. .decl_block_id = SemIR::InstBlockId::Empty};
  1342. auto class_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1343. context.local_context().MakeImportedLocAndInst(
  1344. AddImportIRInst(context, import_class.latest_decl_id()), class_decl));
  1345. // Regardless of whether ClassDecl is a complete type, we first need an
  1346. // incomplete type so that any references have something to point at.
  1347. class_decl.class_id = context.local_classes().Add(
  1348. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1349. {.self_type_id = SemIR::TypeId::Invalid,
  1350. .inheritance_kind = import_class.inheritance_kind,
  1351. .is_dynamic = import_class.is_dynamic}});
  1352. if (import_class.has_parameters()) {
  1353. class_decl.type_id = context.local_context().GetGenericClassType(
  1354. class_decl.class_id, enclosing_specific_id);
  1355. }
  1356. // Write the class ID into the ClassDecl.
  1357. context.local_context().ReplaceInstBeforeConstantUse(class_decl_id,
  1358. class_decl);
  1359. auto self_const_id = context.local_constant_values().Get(class_decl_id);
  1360. return {class_decl.class_id, self_const_id};
  1361. }
  1362. // Fills out the class definition for an incomplete class.
  1363. static auto AddClassDefinition(ImportContext& context,
  1364. const SemIR::Class& import_class,
  1365. SemIR::Class& new_class,
  1366. SemIR::InstId complete_type_witness_id,
  1367. SemIR::InstId base_id, SemIR::InstId adapt_id)
  1368. -> void {
  1369. new_class.definition_id = new_class.first_owning_decl_id;
  1370. new_class.complete_type_witness_id = complete_type_witness_id;
  1371. new_class.scope_id = context.local_name_scopes().Add(
  1372. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1373. new_class.parent_scope_id);
  1374. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1375. const auto& import_scope =
  1376. context.import_name_scopes().Get(import_class.scope_id);
  1377. // Push a block so that we can add scoped instructions to it.
  1378. context.local_context().inst_block_stack().Push();
  1379. AddNameScopeImportRefs(context, import_scope, new_scope);
  1380. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1381. if (import_class.base_id.is_valid()) {
  1382. new_class.base_id = base_id;
  1383. }
  1384. if (import_class.adapt_id.is_valid()) {
  1385. new_class.adapt_id = adapt_id;
  1386. }
  1387. }
  1388. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1389. SemIR::ClassDecl inst,
  1390. SemIR::ConstantId class_const_id)
  1391. -> ResolveResult {
  1392. // TODO: The handling of interfaces repeats a lot with the handling of
  1393. // classes, and will likely also be repeated for named constraints and
  1394. // choice types. Factor out some of this functionality.
  1395. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1396. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1397. if (!class_const_id.is_valid()) {
  1398. auto import_specific_id = SemIR::SpecificId::Invalid;
  1399. if (auto import_generic_class_type =
  1400. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1401. inst.type_id)) {
  1402. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1403. }
  1404. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1405. if (resolver.HasNewWork()) {
  1406. // This is the end of the first phase. Don't make a new class yet if
  1407. // we already have new work.
  1408. return ResolveResult::Retry();
  1409. }
  1410. // On the second phase, create a forward declaration of the class for any
  1411. // recursive references.
  1412. auto enclosing_specific_id =
  1413. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1414. std::tie(class_id, class_const_id) =
  1415. MakeIncompleteClass(resolver, import_class, enclosing_specific_id);
  1416. } else {
  1417. // On the third phase, compute the class ID from the constant
  1418. // value of the declaration.
  1419. auto class_const_inst = resolver.local_insts().Get(
  1420. resolver.local_constant_values().GetInstId(class_const_id));
  1421. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1422. class_id = class_type->class_id;
  1423. } else {
  1424. auto generic_class_type =
  1425. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1426. class_const_inst.type_id());
  1427. class_id = generic_class_type.class_id;
  1428. }
  1429. }
  1430. // Load constants for the definition.
  1431. auto parent_scope_id =
  1432. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1433. LoadLocalPatternConstantIds(resolver,
  1434. import_class.implicit_param_patterns_id);
  1435. LoadLocalPatternConstantIds(resolver, import_class.param_patterns_id);
  1436. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1437. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1438. auto complete_type_witness_const_id =
  1439. import_class.complete_type_witness_id.is_valid()
  1440. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1441. : SemIR::ConstantId::Invalid;
  1442. auto base_id = import_class.base_id.is_valid()
  1443. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1444. : SemIR::InstId::Invalid;
  1445. auto adapt_id = import_class.adapt_id.is_valid()
  1446. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1447. : SemIR::InstId::Invalid;
  1448. if (resolver.HasNewWork()) {
  1449. return ResolveResult::Retry(class_const_id);
  1450. }
  1451. auto& new_class = resolver.local_classes().Get(class_id);
  1452. new_class.parent_scope_id = parent_scope_id;
  1453. new_class.implicit_param_patterns_id = GetLocalParamPatternsId(
  1454. resolver, import_class.implicit_param_patterns_id);
  1455. new_class.param_patterns_id =
  1456. GetLocalParamPatternsId(resolver, import_class.param_patterns_id);
  1457. SetGenericData(resolver, import_class.generic_id, new_class.generic_id,
  1458. generic_data);
  1459. new_class.self_type_id =
  1460. resolver.local_context().GetTypeIdForTypeConstant(self_const_id);
  1461. if (import_class.is_defined()) {
  1462. auto complete_type_witness_id = AddLoadedImportRef(
  1463. resolver,
  1464. resolver.local_context().GetSingletonType(
  1465. SemIR::WitnessType::SingletonInstId),
  1466. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1467. AddClassDefinition(resolver, import_class, new_class,
  1468. complete_type_witness_id, base_id, adapt_id);
  1469. }
  1470. return ResolveResult::Done(class_const_id);
  1471. }
  1472. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1473. SemIR::ClassType inst) -> ResolveResult {
  1474. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1475. auto class_const_id = GetLocalConstantId(
  1476. resolver,
  1477. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1478. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1479. if (resolver.HasNewWork()) {
  1480. return ResolveResult::Retry();
  1481. }
  1482. // Find the corresponding class type. For a non-generic class, this is the
  1483. // type of the class declaration. For a generic class, build a class type
  1484. // referencing this specialization of the generic class.
  1485. auto class_const_inst = resolver.local_insts().Get(
  1486. resolver.local_constant_values().GetInstId(class_const_id));
  1487. if (class_const_inst.Is<SemIR::ClassType>()) {
  1488. return ResolveResult::Done(class_const_id);
  1489. } else {
  1490. auto generic_class_type =
  1491. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1492. class_const_inst.type_id());
  1493. auto specific_id =
  1494. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1495. return ResolveAs<SemIR::ClassType>(
  1496. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1497. .class_id = generic_class_type.class_id,
  1498. .specific_id = specific_id});
  1499. }
  1500. }
  1501. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1502. SemIR::CompleteTypeWitness inst)
  1503. -> ResolveResult {
  1504. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1505. SemIR::WitnessType::SingletonInstId);
  1506. auto object_repr_const_id = GetLocalConstantId(resolver, inst.object_repr_id);
  1507. if (resolver.HasNewWork()) {
  1508. return ResolveResult::Retry();
  1509. }
  1510. auto object_repr_id =
  1511. resolver.local_context().GetTypeIdForTypeConstant(object_repr_const_id);
  1512. return ResolveAs<SemIR::CompleteTypeWitness>(
  1513. resolver, {.type_id = resolver.local_context().GetSingletonType(
  1514. SemIR::WitnessType::SingletonInstId),
  1515. .object_repr_id = object_repr_id});
  1516. }
  1517. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1518. SemIR::ConstType inst) -> ResolveResult {
  1519. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1520. auto inner_const_id = GetLocalConstantId(resolver, inst.inner_id);
  1521. if (resolver.HasNewWork()) {
  1522. return ResolveResult::Retry();
  1523. }
  1524. auto inner_type_id =
  1525. resolver.local_context().GetTypeIdForTypeConstant(inner_const_id);
  1526. return ResolveAs<SemIR::ConstType>(
  1527. resolver,
  1528. {.type_id = SemIR::TypeType::SingletonTypeId, .inner_id = inner_type_id});
  1529. }
  1530. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1531. SemIR::ExportDecl inst) -> ResolveResult {
  1532. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1533. return RetryOrDone(resolver, value_id);
  1534. }
  1535. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1536. SemIR::FieldDecl inst,
  1537. SemIR::InstId import_inst_id) -> ResolveResult {
  1538. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1539. if (resolver.HasNewWork()) {
  1540. return ResolveResult::Retry();
  1541. }
  1542. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1543. resolver.local_context().MakeImportedLocAndInst<SemIR::FieldDecl>(
  1544. AddImportIRInst(resolver, import_inst_id),
  1545. {.type_id =
  1546. resolver.local_context().GetTypeIdForTypeConstant(const_id),
  1547. .name_id = GetLocalNameId(resolver, inst.name_id),
  1548. .index = inst.index}));
  1549. return {.const_id = resolver.local_constant_values().Get(inst_id)};
  1550. }
  1551. // Make a declaration of a function. This is done as a separate step from
  1552. // importing the function declaration in order to resolve cycles.
  1553. static auto MakeFunctionDecl(ImportContext& context,
  1554. const SemIR::Function& import_function,
  1555. SemIR::SpecificId specific_id)
  1556. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1557. SemIR::FunctionDecl function_decl = {
  1558. .type_id = SemIR::TypeId::Invalid,
  1559. .function_id = SemIR::FunctionId::Invalid,
  1560. .decl_block_id = SemIR::InstBlockId::Empty};
  1561. auto function_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1562. context.local_context().MakeImportedLocAndInst(
  1563. AddImportIRInst(context, import_function.first_decl_id()),
  1564. function_decl));
  1565. // Start with an incomplete function.
  1566. function_decl.function_id = context.local_functions().Add(
  1567. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  1568. {.return_slot_pattern_id = SemIR::InstId::Invalid,
  1569. .builtin_function_kind = import_function.builtin_function_kind}});
  1570. function_decl.type_id = context.local_context().GetFunctionType(
  1571. function_decl.function_id, specific_id);
  1572. // Write the function ID and type into the FunctionDecl.
  1573. context.local_context().ReplaceInstBeforeConstantUse(function_decl_id,
  1574. function_decl);
  1575. return {function_decl.function_id,
  1576. context.local_constant_values().Get(function_decl_id)};
  1577. }
  1578. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1579. SemIR::FunctionDecl inst,
  1580. SemIR::ConstantId function_const_id)
  1581. -> ResolveResult {
  1582. const auto& import_function =
  1583. resolver.import_functions().Get(inst.function_id);
  1584. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1585. if (!function_const_id.is_valid()) {
  1586. auto import_specific_id = resolver.import_types()
  1587. .GetAs<SemIR::FunctionType>(inst.type_id)
  1588. .specific_id;
  1589. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1590. if (resolver.HasNewWork()) {
  1591. // This is the end of the first phase. Don't make a new function yet if
  1592. // we already have new work.
  1593. return ResolveResult::Retry();
  1594. }
  1595. // On the second phase, create a forward declaration of the interface.
  1596. auto specific_id =
  1597. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1598. std::tie(function_id, function_const_id) =
  1599. MakeFunctionDecl(resolver, import_function, specific_id);
  1600. } else {
  1601. // On the third phase, compute the function ID from the constant value of
  1602. // the declaration.
  1603. auto function_const_inst = resolver.local_insts().Get(
  1604. resolver.local_constant_values().GetInstId(function_const_id));
  1605. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1606. function_const_inst.type_id());
  1607. function_id = function_type.function_id;
  1608. }
  1609. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1610. if (import_function.return_slot_pattern_id.is_valid()) {
  1611. return_type_const_id = GetLocalConstantId(
  1612. resolver, resolver.import_insts()
  1613. .Get(import_function.return_slot_pattern_id)
  1614. .type_id());
  1615. }
  1616. auto parent_scope_id =
  1617. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1618. LoadLocalPatternConstantIds(resolver,
  1619. import_function.implicit_param_patterns_id);
  1620. LoadLocalPatternConstantIds(resolver, import_function.param_patterns_id);
  1621. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1622. if (resolver.HasNewWork()) {
  1623. return ResolveResult::Retry(function_const_id);
  1624. }
  1625. // Add the function declaration.
  1626. auto& new_function = resolver.local_functions().Get(function_id);
  1627. new_function.parent_scope_id = parent_scope_id;
  1628. new_function.implicit_param_patterns_id = GetLocalParamPatternsId(
  1629. resolver, import_function.implicit_param_patterns_id);
  1630. new_function.param_patterns_id =
  1631. GetLocalParamPatternsId(resolver, import_function.param_patterns_id);
  1632. new_function.return_slot_pattern_id = GetLocalReturnSlotPatternId(
  1633. resolver, import_function.return_slot_pattern_id);
  1634. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1635. generic_data);
  1636. if (import_function.definition_id.is_valid()) {
  1637. new_function.definition_id = new_function.first_owning_decl_id;
  1638. }
  1639. return ResolveResult::Done(function_const_id);
  1640. }
  1641. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1642. SemIR::FunctionType inst) -> ResolveResult {
  1643. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1644. auto fn_val_id = GetLocalConstantInstId(
  1645. resolver,
  1646. resolver.import_functions().Get(inst.function_id).first_decl_id());
  1647. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1648. if (resolver.HasNewWork()) {
  1649. return ResolveResult::Retry();
  1650. }
  1651. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  1652. return ResolveAs<SemIR::FunctionType>(
  1653. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1654. .function_id = resolver.local_types()
  1655. .GetAs<SemIR::FunctionType>(fn_type_id)
  1656. .function_id,
  1657. .specific_id = GetOrAddLocalSpecific(
  1658. resolver, inst.specific_id, specific_data)});
  1659. }
  1660. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1661. SemIR::GenericClassType inst) -> ResolveResult {
  1662. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1663. auto class_val_id = GetLocalConstantInstId(
  1664. resolver,
  1665. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1666. if (resolver.HasNewWork()) {
  1667. return ResolveResult::Retry();
  1668. }
  1669. auto class_val = resolver.local_insts().Get(class_val_id);
  1670. CARBON_CHECK(
  1671. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1672. return ResolveResult::Done(
  1673. resolver.local_types().GetConstantId(class_val.type_id()));
  1674. }
  1675. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1676. SemIR::GenericInterfaceType inst)
  1677. -> ResolveResult {
  1678. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1679. auto interface_val_id = GetLocalConstantInstId(
  1680. resolver,
  1681. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  1682. if (resolver.HasNewWork()) {
  1683. return ResolveResult::Retry();
  1684. }
  1685. auto interface_val = resolver.local_insts().Get(interface_val_id);
  1686. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  1687. interface_val.type_id()));
  1688. return ResolveResult::Done(
  1689. resolver.local_types().GetConstantId(interface_val.type_id()));
  1690. }
  1691. // Make a declaration of an impl. This is done as a separate step from
  1692. // importing the impl definition in order to resolve cycles.
  1693. static auto MakeImplDeclaration(ImportContext& context,
  1694. const SemIR::Impl& import_impl)
  1695. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1696. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::Invalid,
  1697. .decl_block_id = SemIR::InstBlockId::Empty};
  1698. auto impl_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1699. context.local_context().MakeImportedLocAndInst(
  1700. AddImportIRInst(context, import_impl.latest_decl_id()), impl_decl));
  1701. impl_decl.impl_id = context.local_impls().Add(
  1702. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  1703. {.self_id = SemIR::InstId::Invalid,
  1704. .constraint_id = SemIR::InstId::Invalid,
  1705. .witness_id = SemIR::InstId::Invalid}});
  1706. // Write the impl ID into the ImplDecl.
  1707. context.local_context().ReplaceInstBeforeConstantUse(impl_decl_id, impl_decl);
  1708. return {impl_decl.impl_id, context.local_constant_values().Get(impl_decl_id)};
  1709. }
  1710. // Imports the definition of an impl.
  1711. static auto AddImplDefinition(ImportContext& context,
  1712. const SemIR::Impl& import_impl,
  1713. SemIR::Impl& new_impl, SemIR::InstId witness_id)
  1714. -> void {
  1715. new_impl.definition_id = new_impl.first_owning_decl_id;
  1716. new_impl.witness_id = witness_id;
  1717. if (import_impl.scope_id.is_valid()) {
  1718. new_impl.scope_id = context.local_name_scopes().Add(
  1719. new_impl.first_owning_decl_id, SemIR::NameId::Invalid,
  1720. new_impl.parent_scope_id);
  1721. // Import the contents of the definition scope, if we might need it. Name
  1722. // lookup is never performed into this scope by a user of the impl, so
  1723. // this is only necessary in the same library that defined the impl, in
  1724. // order to support defining members of the impl out of line in the impl
  1725. // file when the impl is defined in the API file.
  1726. // TODO: Check to see if this impl is owned by the API file, rather than
  1727. // merely being imported into it.
  1728. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1729. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  1730. const auto& import_scope =
  1731. context.import_name_scopes().Get(import_impl.scope_id);
  1732. // Push a block so that we can add scoped instructions to it.
  1733. context.local_context().inst_block_stack().Push();
  1734. AddNameScopeImportRefs(context, import_scope, new_scope);
  1735. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  1736. }
  1737. }
  1738. }
  1739. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1740. SemIR::ImplDecl inst,
  1741. SemIR::ConstantId impl_const_id)
  1742. -> ResolveResult {
  1743. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1744. // functions. Factor out the commonality.
  1745. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  1746. SemIR::ImplId impl_id = SemIR::ImplId::Invalid;
  1747. if (!impl_const_id.is_valid()) {
  1748. if (resolver.HasNewWork()) {
  1749. // This is the end of the first phase. Don't make a new impl yet if we
  1750. // already have new work.
  1751. return ResolveResult::Retry();
  1752. }
  1753. // On the second phase, create a forward declaration of the impl for any
  1754. // recursive references.
  1755. std::tie(impl_id, impl_const_id) =
  1756. MakeImplDeclaration(resolver, import_impl);
  1757. } else {
  1758. // On the third phase, compute the impl ID from the "constant value" of
  1759. // the declaration, which is a reference to the created ImplDecl.
  1760. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  1761. resolver.local_constant_values().GetInstId(impl_const_id));
  1762. impl_id = impl_const_inst.impl_id;
  1763. }
  1764. // Load constants for the definition.
  1765. auto parent_scope_id =
  1766. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  1767. LoadLocalPatternConstantIds(resolver, import_impl.implicit_param_patterns_id);
  1768. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  1769. auto self_const_id = GetLocalConstantId(
  1770. resolver, resolver.import_constant_values().Get(import_impl.self_id));
  1771. auto constraint_const_id = GetLocalConstantId(
  1772. resolver,
  1773. resolver.import_constant_values().Get(import_impl.constraint_id));
  1774. if (resolver.HasNewWork()) {
  1775. return ResolveResult::Retry(impl_const_id);
  1776. }
  1777. auto& new_impl = resolver.local_impls().Get(impl_id);
  1778. new_impl.parent_scope_id = parent_scope_id;
  1779. new_impl.implicit_param_patterns_id =
  1780. GetLocalParamPatternsId(resolver, import_impl.implicit_param_patterns_id);
  1781. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  1782. generic_data);
  1783. // Create instructions for self and constraint to hold the symbolic constant
  1784. // value for a generic impl.
  1785. new_impl.self_id =
  1786. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1787. import_impl.self_id, self_const_id);
  1788. new_impl.constraint_id =
  1789. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1790. import_impl.constraint_id, constraint_const_id);
  1791. if (import_impl.is_defined()) {
  1792. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  1793. AddImplDefinition(resolver, import_impl, new_impl, witness_id);
  1794. }
  1795. // If the `impl` is declared in the API file corresponding to the current
  1796. // file, add this to impl lookup so that it can be found by redeclarations
  1797. // in the current file.
  1798. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1799. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  1800. }
  1801. return ResolveResult::Done(impl_const_id);
  1802. }
  1803. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1804. SemIR::ImportRefLoaded /*inst*/,
  1805. SemIR::InstId inst_id) -> ResolveResult {
  1806. // Return the constant for the instruction of the imported constant.
  1807. auto constant_id = resolver.import_constant_values().Get(inst_id);
  1808. if (!constant_id.is_valid()) {
  1809. return ResolveResult::Done(SemIR::ErrorInst::SingletonConstantId);
  1810. }
  1811. if (!constant_id.is_constant()) {
  1812. resolver.local_context().TODO(
  1813. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  1814. return ResolveResult::Done(SemIR::ErrorInst::SingletonConstantId);
  1815. }
  1816. auto new_constant_id = GetLocalConstantId(
  1817. resolver, resolver.import_constant_values().GetInstId(constant_id));
  1818. return RetryOrDone(resolver, new_constant_id);
  1819. }
  1820. // Make a declaration of an interface. This is done as a separate step from
  1821. // importing the interface definition in order to resolve cycles.
  1822. static auto MakeInterfaceDecl(ImportContext& context,
  1823. const SemIR::Interface& import_interface,
  1824. SemIR::SpecificId enclosing_specific_id)
  1825. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1826. SemIR::InterfaceDecl interface_decl = {
  1827. .type_id = SemIR::TypeType::SingletonTypeId,
  1828. .interface_id = SemIR::InterfaceId::Invalid,
  1829. .decl_block_id = SemIR::InstBlockId::Empty};
  1830. auto interface_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1831. context.local_context().MakeImportedLocAndInst(
  1832. AddImportIRInst(context, import_interface.first_owning_decl_id),
  1833. interface_decl));
  1834. // Start with an incomplete interface.
  1835. interface_decl.interface_id = context.local_interfaces().Add(
  1836. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  1837. import_interface),
  1838. {}});
  1839. if (import_interface.has_parameters()) {
  1840. interface_decl.type_id = context.local_context().GetGenericInterfaceType(
  1841. interface_decl.interface_id, enclosing_specific_id);
  1842. }
  1843. // Write the interface ID into the InterfaceDecl.
  1844. context.local_context().ReplaceInstBeforeConstantUse(interface_decl_id,
  1845. interface_decl);
  1846. return {interface_decl.interface_id,
  1847. context.local_constant_values().Get(interface_decl_id)};
  1848. }
  1849. // Imports the definition for an interface that has been imported as a forward
  1850. // declaration.
  1851. static auto AddInterfaceDefinition(ImportContext& context,
  1852. const SemIR::Interface& import_interface,
  1853. SemIR::Interface& new_interface,
  1854. SemIR::InstId self_param_id) -> void {
  1855. new_interface.scope_id = context.local_name_scopes().Add(
  1856. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1857. new_interface.parent_scope_id);
  1858. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  1859. const auto& import_scope =
  1860. context.import_name_scopes().Get(import_interface.scope_id);
  1861. // Push a block so that we can add scoped instructions to it.
  1862. context.local_context().inst_block_stack().Push();
  1863. AddNameScopeImportRefs(context, import_scope, new_scope);
  1864. new_interface.associated_entities_id = AddAssociatedEntities(
  1865. context, new_interface.scope_id, import_interface.associated_entities_id);
  1866. new_interface.body_block_id =
  1867. context.local_context().inst_block_stack().Pop();
  1868. new_interface.self_param_id = self_param_id;
  1869. CARBON_CHECK(import_scope.extended_scopes().empty(),
  1870. "Interfaces don't currently have extended scopes to support.");
  1871. }
  1872. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1873. SemIR::InterfaceDecl inst,
  1874. SemIR::ConstantId interface_const_id)
  1875. -> ResolveResult {
  1876. const auto& import_interface =
  1877. resolver.import_interfaces().Get(inst.interface_id);
  1878. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1879. if (!interface_const_id.is_valid()) {
  1880. auto import_specific_id = SemIR::SpecificId::Invalid;
  1881. if (auto import_generic_interface_type =
  1882. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  1883. inst.type_id)) {
  1884. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  1885. }
  1886. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1887. if (resolver.HasNewWork()) {
  1888. // This is the end of the first phase. Don't make a new interface yet if
  1889. // we already have new work.
  1890. return ResolveResult::Retry();
  1891. }
  1892. // On the second phase, create a forward declaration of the interface.
  1893. auto enclosing_specific_id =
  1894. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1895. std::tie(interface_id, interface_const_id) =
  1896. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  1897. } else {
  1898. // On the third phase, compute the interface ID from the constant value of
  1899. // the declaration.
  1900. auto interface_const_inst = resolver.local_insts().Get(
  1901. resolver.local_constant_values().GetInstId(interface_const_id));
  1902. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  1903. const SemIR::FacetTypeInfo& facet_type_info =
  1904. resolver.local_facet_types().Get(facet_type->facet_type_id);
  1905. auto interface_type = facet_type_info.TryAsSingleInterface();
  1906. CARBON_CHECK(interface_type);
  1907. interface_id = interface_type->interface_id;
  1908. } else {
  1909. auto generic_interface_type =
  1910. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  1911. interface_const_inst.type_id());
  1912. interface_id = generic_interface_type.interface_id;
  1913. }
  1914. }
  1915. auto parent_scope_id =
  1916. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  1917. LoadLocalPatternConstantIds(resolver,
  1918. import_interface.implicit_param_patterns_id);
  1919. LoadLocalPatternConstantIds(resolver, import_interface.param_patterns_id);
  1920. auto generic_data =
  1921. GetLocalGenericData(resolver, import_interface.generic_id);
  1922. std::optional<SemIR::InstId> self_param_id;
  1923. if (import_interface.is_defined()) {
  1924. self_param_id =
  1925. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  1926. }
  1927. if (resolver.HasNewWork()) {
  1928. return ResolveResult::Retry(interface_const_id);
  1929. }
  1930. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  1931. new_interface.parent_scope_id = parent_scope_id;
  1932. new_interface.implicit_param_patterns_id = GetLocalParamPatternsId(
  1933. resolver, import_interface.implicit_param_patterns_id);
  1934. new_interface.param_patterns_id =
  1935. GetLocalParamPatternsId(resolver, import_interface.param_patterns_id);
  1936. SetGenericData(resolver, import_interface.generic_id,
  1937. new_interface.generic_id, generic_data);
  1938. if (import_interface.is_defined()) {
  1939. CARBON_CHECK(self_param_id);
  1940. AddInterfaceDefinition(resolver, import_interface, new_interface,
  1941. *self_param_id);
  1942. }
  1943. return ResolveResult::Done(interface_const_id);
  1944. }
  1945. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1946. SemIR::FacetAccessType inst) -> ResolveResult {
  1947. auto facet_value_inst_id =
  1948. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  1949. if (resolver.HasNewWork()) {
  1950. return ResolveResult::Retry();
  1951. }
  1952. return ResolveAs<SemIR::FacetAccessType>(
  1953. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1954. .facet_value_inst_id = facet_value_inst_id});
  1955. }
  1956. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1957. SemIR::FacetAccessWitness inst)
  1958. -> ResolveResult {
  1959. auto facet_value_inst_id =
  1960. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  1961. if (resolver.HasNewWork()) {
  1962. return ResolveResult::Retry();
  1963. }
  1964. return ResolveAs<SemIR::FacetAccessWitness>(
  1965. resolver, {.type_id = resolver.local_context().GetSingletonType(
  1966. SemIR::WitnessType::SingletonInstId),
  1967. .facet_value_inst_id = facet_value_inst_id});
  1968. }
  1969. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1970. SemIR::FacetType inst) -> ResolveResult {
  1971. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1972. const SemIR::FacetTypeInfo& facet_type_info =
  1973. resolver.import_facet_types().Get(inst.facet_type_id);
  1974. for (auto interface : facet_type_info.impls_constraints) {
  1975. GetLocalConstantId(resolver, resolver.import_interfaces()
  1976. .Get(interface.interface_id)
  1977. .first_owning_decl_id);
  1978. GetLocalSpecificData(resolver, interface.specific_id);
  1979. }
  1980. for (auto rewrite : facet_type_info.rewrite_constraints) {
  1981. GetLocalConstantId(resolver, rewrite.lhs_const_id);
  1982. GetLocalConstantId(resolver, rewrite.rhs_const_id);
  1983. }
  1984. if (resolver.HasNewWork()) {
  1985. return ResolveResult::Retry();
  1986. }
  1987. llvm::SmallVector<SemIR::FacetTypeInfo::ImplsConstraint> impls_constraints;
  1988. for (auto interface : facet_type_info.impls_constraints) {
  1989. auto interface_const_id =
  1990. GetLocalConstantId(resolver, resolver.import_interfaces()
  1991. .Get(interface.interface_id)
  1992. .first_owning_decl_id);
  1993. auto specific_data = GetLocalSpecificData(resolver, interface.specific_id);
  1994. // Find the corresponding interface type. For a non-generic interface,
  1995. // this is the type of the interface declaration. For a generic interface,
  1996. // build a interface type referencing this specialization of the generic
  1997. // interface.
  1998. auto interface_const_inst = resolver.local_insts().Get(
  1999. resolver.local_constant_values().GetInstId(interface_const_id));
  2000. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2001. const SemIR::FacetTypeInfo& new_facet_type_info =
  2002. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2003. impls_constraints.append(new_facet_type_info.impls_constraints);
  2004. } else {
  2005. auto generic_interface_type =
  2006. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2007. interface_const_inst.type_id());
  2008. auto specific_id =
  2009. GetOrAddLocalSpecific(resolver, interface.specific_id, specific_data);
  2010. impls_constraints.push_back(
  2011. {generic_interface_type.interface_id, specific_id});
  2012. }
  2013. }
  2014. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>
  2015. rewrite_constraints;
  2016. for (auto rewrite : facet_type_info.rewrite_constraints) {
  2017. rewrite_constraints.push_back(
  2018. {.lhs_const_id = GetLocalConstantId(resolver, rewrite.lhs_const_id),
  2019. .rhs_const_id = GetLocalConstantId(resolver, rewrite.rhs_const_id)});
  2020. }
  2021. // TODO: Also process the other requirements.
  2022. SemIR::FacetTypeId facet_type_id =
  2023. resolver.local_facet_types().Add(SemIR::FacetTypeInfo{
  2024. .impls_constraints = impls_constraints,
  2025. .rewrite_constraints = rewrite_constraints,
  2026. .other_requirements = facet_type_info.other_requirements});
  2027. return ResolveAs<SemIR::FacetType>(
  2028. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2029. .facet_type_id = facet_type_id});
  2030. }
  2031. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2032. SemIR::FacetValue inst) -> ResolveResult {
  2033. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2034. auto type_inst_id = GetLocalConstantInstId(resolver, inst.type_inst_id);
  2035. auto witness_inst_id = GetLocalConstantInstId(resolver, inst.witness_inst_id);
  2036. if (resolver.HasNewWork()) {
  2037. return ResolveResult::Retry();
  2038. }
  2039. return ResolveAs<SemIR::FacetValue>(
  2040. resolver,
  2041. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2042. .type_inst_id = type_inst_id,
  2043. .witness_inst_id = witness_inst_id});
  2044. }
  2045. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2046. SemIR::InterfaceWitness inst) -> ResolveResult {
  2047. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  2048. if (resolver.HasNewWork()) {
  2049. return ResolveResult::Retry();
  2050. }
  2051. auto elements_id =
  2052. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements);
  2053. return ResolveAs<SemIR::InterfaceWitness>(
  2054. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2055. SemIR::WitnessType::SingletonInstId),
  2056. .elements_id = elements_id});
  2057. }
  2058. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2059. SemIR::InterfaceWitnessAccess inst)
  2060. -> ResolveResult {
  2061. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2062. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2063. if (resolver.HasNewWork()) {
  2064. return ResolveResult::Retry();
  2065. }
  2066. return ResolveAs<SemIR::InterfaceWitnessAccess>(
  2067. resolver,
  2068. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2069. .witness_id = witness_id,
  2070. .index = inst.index});
  2071. }
  2072. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2073. SemIR::IntValue inst) -> ResolveResult {
  2074. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2075. if (resolver.HasNewWork()) {
  2076. return ResolveResult::Retry();
  2077. }
  2078. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2079. // to add a new canonical int in this IR.
  2080. auto int_id = inst.int_id.is_value()
  2081. ? inst.int_id
  2082. : resolver.local_ints().AddSigned(
  2083. resolver.import_ints().Get(inst.int_id));
  2084. return ResolveAs<SemIR::IntValue>(
  2085. resolver,
  2086. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2087. .int_id = int_id});
  2088. }
  2089. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2090. SemIR::IntType inst) -> ResolveResult {
  2091. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2092. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2093. if (resolver.HasNewWork()) {
  2094. return ResolveResult::Retry();
  2095. }
  2096. return ResolveAs<SemIR::IntType>(resolver,
  2097. {.type_id = SemIR::TypeType::SingletonTypeId,
  2098. .int_kind = inst.int_kind,
  2099. .bit_width_id = bit_width_id});
  2100. }
  2101. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2102. SemIR::Namespace inst,
  2103. SemIR::InstId import_inst_id) -> ResolveResult {
  2104. const auto& name_scope =
  2105. resolver.import_name_scopes().Get(inst.name_scope_id);
  2106. // A package from a different file becomes a child of the package here, as it
  2107. // would be if it were imported.
  2108. auto parent_scope_id =
  2109. inst.name_scope_id == SemIR::NameScopeId::Package
  2110. ? SemIR::NameScopeId::Package
  2111. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2112. if (resolver.HasNewWork()) {
  2113. return ResolveResult::Retry();
  2114. }
  2115. auto namespace_type_id = resolver.local_context().GetSingletonType(
  2116. SemIR::NamespaceType::SingletonInstId);
  2117. auto namespace_decl =
  2118. SemIR::Namespace{.type_id = namespace_type_id,
  2119. .name_scope_id = SemIR::NameScopeId::Invalid,
  2120. .import_id = SemIR::AbsoluteInstId::Invalid};
  2121. auto inst_id = resolver.local_context().AddPlaceholderInstInNoBlock(
  2122. resolver.local_context().MakeImportedLocAndInst(
  2123. AddImportIRInst(resolver, import_inst_id), namespace_decl));
  2124. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2125. namespace_decl.name_scope_id =
  2126. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2127. // Namespaces from this package are eagerly imported, so anything we load here
  2128. // must be a closed import.
  2129. resolver.local_name_scopes()
  2130. .Get(namespace_decl.name_scope_id)
  2131. .set_is_closed_import(true);
  2132. resolver.local_context().ReplaceInstBeforeConstantUse(inst_id,
  2133. namespace_decl);
  2134. return {.const_id = resolver.local_constant_values().Get(inst_id)};
  2135. }
  2136. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2137. SemIR::PointerType inst) -> ResolveResult {
  2138. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2139. auto pointee_const_id = GetLocalConstantId(resolver, inst.pointee_id);
  2140. if (resolver.HasNewWork()) {
  2141. return ResolveResult::Retry();
  2142. }
  2143. auto pointee_type_id =
  2144. resolver.local_context().GetTypeIdForTypeConstant(pointee_const_id);
  2145. return ResolveAs<SemIR::PointerType>(
  2146. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2147. .pointee_id = pointee_type_id});
  2148. }
  2149. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2150. SemIR::RequireCompleteType inst)
  2151. -> ResolveResult {
  2152. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2153. SemIR::WitnessType::SingletonInstId);
  2154. auto complete_type_const_id =
  2155. GetLocalConstantId(resolver, inst.complete_type_id);
  2156. if (resolver.HasNewWork()) {
  2157. return ResolveResult::Retry();
  2158. }
  2159. auto complete_type_id =
  2160. resolver.local_context().GetTypeIdForTypeConstant(complete_type_const_id);
  2161. return ResolveAs<SemIR::RequireCompleteType>(
  2162. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2163. SemIR::WitnessType::SingletonInstId),
  2164. .complete_type_id = complete_type_id});
  2165. }
  2166. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2167. SemIR::SpecificFunction inst) -> ResolveResult {
  2168. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2169. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2170. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2171. if (resolver.HasNewWork()) {
  2172. return ResolveResult::Retry();
  2173. }
  2174. auto type_id =
  2175. resolver.local_context().GetTypeIdForTypeConstant(type_const_id);
  2176. auto specific_id =
  2177. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2178. return ResolveAs<SemIR::SpecificFunction>(
  2179. resolver,
  2180. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2181. }
  2182. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2183. SemIR::StructType inst) -> ResolveResult {
  2184. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2185. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2186. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  2187. field_const_ids.reserve(orig_fields.size());
  2188. for (auto field : orig_fields) {
  2189. field_const_ids.push_back(GetLocalConstantId(resolver, field.type_id));
  2190. }
  2191. if (resolver.HasNewWork()) {
  2192. return ResolveResult::Retry();
  2193. }
  2194. // Prepare a vector of fields for GetStructType.
  2195. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2196. new_fields.reserve(orig_fields.size());
  2197. for (auto [orig_field, field_const_id] :
  2198. llvm::zip(orig_fields, field_const_ids)) {
  2199. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2200. auto field_type_id =
  2201. resolver.local_context().GetTypeIdForTypeConstant(field_const_id);
  2202. new_fields.push_back({.name_id = name_id, .type_id = field_type_id});
  2203. }
  2204. return ResolveAs<SemIR::StructType>(
  2205. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2206. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2207. new_fields)});
  2208. }
  2209. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2210. SemIR::StructValue inst) -> ResolveResult {
  2211. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2212. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2213. if (resolver.HasNewWork()) {
  2214. return ResolveResult::Retry();
  2215. }
  2216. return ResolveAs<SemIR::StructValue>(
  2217. resolver,
  2218. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2219. .elements_id =
  2220. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2221. }
  2222. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2223. SemIR::TupleType inst) -> ResolveResult {
  2224. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2225. auto orig_elem_type_ids = resolver.import_type_blocks().Get(inst.elements_id);
  2226. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  2227. elem_const_ids.reserve(orig_elem_type_ids.size());
  2228. for (auto elem_type_id : orig_elem_type_ids) {
  2229. elem_const_ids.push_back(GetLocalConstantId(resolver, elem_type_id));
  2230. }
  2231. if (resolver.HasNewWork()) {
  2232. return ResolveResult::Retry();
  2233. }
  2234. // Prepare a vector of the tuple types for GetTupleType.
  2235. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  2236. elem_type_ids.reserve(orig_elem_type_ids.size());
  2237. for (auto elem_const_id : elem_const_ids) {
  2238. elem_type_ids.push_back(
  2239. resolver.local_context().GetTypeIdForTypeConstant(elem_const_id));
  2240. }
  2241. return ResolveResult::Done(resolver.local_types().GetConstantId(
  2242. resolver.local_context().GetTupleType(elem_type_ids)));
  2243. }
  2244. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2245. SemIR::TupleValue inst) -> ResolveResult {
  2246. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2247. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2248. if (resolver.HasNewWork()) {
  2249. return ResolveResult::Retry();
  2250. }
  2251. return ResolveAs<SemIR::TupleValue>(
  2252. resolver,
  2253. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2254. .elements_id =
  2255. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2256. }
  2257. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2258. SemIR::UnboundElementType inst)
  2259. -> ResolveResult {
  2260. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2261. auto class_const_id = GetLocalConstantId(resolver, inst.class_type_id);
  2262. auto elem_const_id = GetLocalConstantId(resolver, inst.element_type_id);
  2263. if (resolver.HasNewWork()) {
  2264. return ResolveResult::Retry();
  2265. }
  2266. return ResolveAs<SemIR::UnboundElementType>(
  2267. resolver,
  2268. {.type_id = SemIR::TypeType::SingletonTypeId,
  2269. .class_type_id =
  2270. resolver.local_context().GetTypeIdForTypeConstant(class_const_id),
  2271. .element_type_id =
  2272. resolver.local_context().GetTypeIdForTypeConstant(elem_const_id)});
  2273. }
  2274. // Tries to resolve the InstId, returning a canonical constant when ready, or
  2275. // Invalid if more has been added to the stack. This is the same as
  2276. // TryResolveInst, except that it may resolve symbolic constants as canonical
  2277. // constants instead of as constants associated with a particular generic.
  2278. //
  2279. // TODO: Consider refactoring the body to a helper in order to eliminate
  2280. // recursion.
  2281. // NOLINTNEXTLINE(misc-no-recursion)
  2282. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  2283. SemIR::InstId inst_id,
  2284. SemIR::ConstantId const_id)
  2285. -> ResolveResult {
  2286. if (SemIR::IsSingletonInstId(inst_id)) {
  2287. CARBON_CHECK(!const_id.is_valid());
  2288. // Constants for builtins can be directly copied.
  2289. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  2290. }
  2291. auto untyped_inst = resolver.import_insts().Get(inst_id);
  2292. CARBON_KIND_SWITCH(untyped_inst) {
  2293. case CARBON_KIND(SemIR::AdaptDecl inst): {
  2294. return TryResolveTypedInst(resolver, inst, inst_id);
  2295. }
  2296. case CARBON_KIND(SemIR::ArrayType inst): {
  2297. return TryResolveTypedInst(resolver, inst);
  2298. }
  2299. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  2300. return TryResolveTypedInst(resolver, inst);
  2301. }
  2302. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  2303. return TryResolveTypedInst(resolver, inst);
  2304. }
  2305. case CARBON_KIND(SemIR::BaseDecl inst): {
  2306. return TryResolveTypedInst(resolver, inst, inst_id);
  2307. }
  2308. case CARBON_KIND(SemIR::BindAlias inst): {
  2309. return TryResolveTypedInst(resolver, inst);
  2310. }
  2311. case SemIR::BindName::Kind: {
  2312. // TODO: Should we be resolving BindNames at all?
  2313. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  2314. }
  2315. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  2316. return TryResolveTypedInst(resolver, inst);
  2317. }
  2318. case CARBON_KIND(SemIR::BoundMethod inst): {
  2319. return TryResolveTypedInst(resolver, inst);
  2320. }
  2321. case CARBON_KIND(SemIR::Call inst): {
  2322. return TryResolveTypedInst(resolver, inst);
  2323. }
  2324. case CARBON_KIND(SemIR::ClassDecl inst): {
  2325. return TryResolveTypedInst(resolver, inst, const_id);
  2326. }
  2327. case CARBON_KIND(SemIR::ClassType inst): {
  2328. return TryResolveTypedInst(resolver, inst);
  2329. }
  2330. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  2331. return TryResolveTypedInst(resolver, inst);
  2332. }
  2333. case CARBON_KIND(SemIR::ConstType inst): {
  2334. return TryResolveTypedInst(resolver, inst);
  2335. }
  2336. case CARBON_KIND(SemIR::ExportDecl inst): {
  2337. return TryResolveTypedInst(resolver, inst);
  2338. }
  2339. case CARBON_KIND(SemIR::FacetAccessType inst): {
  2340. return TryResolveTypedInst(resolver, inst);
  2341. }
  2342. case CARBON_KIND(SemIR::FacetAccessWitness inst): {
  2343. return TryResolveTypedInst(resolver, inst);
  2344. }
  2345. case CARBON_KIND(SemIR::FacetType inst): {
  2346. return TryResolveTypedInst(resolver, inst);
  2347. }
  2348. case CARBON_KIND(SemIR::FacetValue inst): {
  2349. return TryResolveTypedInst(resolver, inst);
  2350. }
  2351. case CARBON_KIND(SemIR::FieldDecl inst): {
  2352. return TryResolveTypedInst(resolver, inst, inst_id);
  2353. }
  2354. case CARBON_KIND(SemIR::FunctionDecl inst): {
  2355. return TryResolveTypedInst(resolver, inst, const_id);
  2356. }
  2357. case CARBON_KIND(SemIR::FunctionType inst): {
  2358. return TryResolveTypedInst(resolver, inst);
  2359. }
  2360. case CARBON_KIND(SemIR::GenericClassType inst): {
  2361. return TryResolveTypedInst(resolver, inst);
  2362. }
  2363. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  2364. return TryResolveTypedInst(resolver, inst);
  2365. }
  2366. case CARBON_KIND(SemIR::ImplDecl inst): {
  2367. return TryResolveTypedInst(resolver, inst, const_id);
  2368. }
  2369. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  2370. return TryResolveTypedInst(resolver, inst, inst_id);
  2371. }
  2372. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  2373. return TryResolveTypedInst(resolver, inst, const_id);
  2374. }
  2375. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  2376. return TryResolveTypedInst(resolver, inst);
  2377. }
  2378. case CARBON_KIND(SemIR::InterfaceWitnessAccess inst): {
  2379. return TryResolveTypedInst(resolver, inst);
  2380. }
  2381. case CARBON_KIND(SemIR::IntValue inst): {
  2382. return TryResolveTypedInst(resolver, inst);
  2383. }
  2384. case CARBON_KIND(SemIR::IntType inst): {
  2385. return TryResolveTypedInst(resolver, inst);
  2386. }
  2387. case CARBON_KIND(SemIR::Namespace inst): {
  2388. return TryResolveTypedInst(resolver, inst, inst_id);
  2389. }
  2390. case CARBON_KIND(SemIR::PointerType inst): {
  2391. return TryResolveTypedInst(resolver, inst);
  2392. }
  2393. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  2394. return TryResolveTypedInst(resolver, inst);
  2395. }
  2396. case CARBON_KIND(SemIR::SpecificFunction inst): {
  2397. return TryResolveTypedInst(resolver, inst);
  2398. }
  2399. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  2400. return TryResolveTypedInst(resolver, inst);
  2401. }
  2402. case CARBON_KIND(SemIR::StructType inst): {
  2403. return TryResolveTypedInst(resolver, inst);
  2404. }
  2405. case CARBON_KIND(SemIR::StructValue inst): {
  2406. return TryResolveTypedInst(resolver, inst);
  2407. }
  2408. case CARBON_KIND(SemIR::TupleType inst): {
  2409. return TryResolveTypedInst(resolver, inst);
  2410. }
  2411. case CARBON_KIND(SemIR::TupleValue inst): {
  2412. return TryResolveTypedInst(resolver, inst);
  2413. }
  2414. case CARBON_KIND(SemIR::UnboundElementType inst): {
  2415. return TryResolveTypedInst(resolver, inst);
  2416. }
  2417. default: {
  2418. // This instruction might have a constant value of a different kind.
  2419. auto constant_inst_id =
  2420. resolver.import_constant_values().GetConstantInstId(inst_id);
  2421. if (constant_inst_id == inst_id) {
  2422. resolver.local_context().TODO(
  2423. SemIR::LocId(AddImportIRInst(resolver, inst_id)),
  2424. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  2425. return {.const_id = SemIR::ErrorInst::SingletonConstantId};
  2426. }
  2427. // Try to resolve the constant value instead. Note that this can only
  2428. // retry once.
  2429. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  2430. constant_inst_id) == constant_inst_id,
  2431. "Constant value of constant instruction should refer to "
  2432. "the same instruction");
  2433. return TryResolveInstCanonical(resolver, constant_inst_id, const_id);
  2434. }
  2435. }
  2436. }
  2437. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  2438. // more has been added to the stack. A similar API is followed for all
  2439. // following TryResolveTypedInst helper functions.
  2440. //
  2441. // `const_id` is Invalid unless we've tried to resolve this instruction
  2442. // before, in which case it's the previous result.
  2443. //
  2444. // TODO: Error is returned when support is missing, but that should go away.
  2445. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  2446. SemIR::ConstantId const_id) -> ResolveResult {
  2447. auto inst_const_id = resolver.import_constant_values().Get(inst_id);
  2448. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  2449. return TryResolveInstCanonical(resolver, inst_id, const_id);
  2450. }
  2451. // Try to import the generic. This might add new work.
  2452. const auto& symbolic_const =
  2453. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  2454. auto generic_const_id =
  2455. GetLocalConstantId(resolver, symbolic_const.generic_id);
  2456. auto inner_const_id = SemIR::ConstantId::Invalid;
  2457. if (const_id.is_valid()) {
  2458. // For the third phase, extract the constant value that
  2459. // TryResolveInstCanonical produced previously.
  2460. inner_const_id = resolver.local_constant_values().Get(
  2461. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  2462. }
  2463. // Import the constant and rebuild the symbolic constant data.
  2464. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  2465. if (!result.const_id.is_valid()) {
  2466. // First phase: TryResolveInstCanoncial needs a retry.
  2467. return result;
  2468. }
  2469. if (!const_id.is_valid()) {
  2470. // Second phase: we have created an abstract constant. Create a
  2471. // corresponding generic constant.
  2472. if (symbolic_const.generic_id.is_valid()) {
  2473. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  2474. {.inst_id =
  2475. resolver.local_constant_values().GetInstId(result.const_id),
  2476. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  2477. .index = symbolic_const.index});
  2478. }
  2479. } else {
  2480. // Third phase: perform a consistency check and produce the constant we
  2481. // created in the second phase.
  2482. CARBON_CHECK(result.const_id == inner_const_id,
  2483. "Constant value changed in third phase.");
  2484. result.const_id = const_id;
  2485. }
  2486. return result;
  2487. }
  2488. // Resolves and returns the local contents for an imported instruction block
  2489. // of constant instructions.
  2490. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  2491. SemIR::InstBlockId import_block_id)
  2492. -> llvm::SmallVector<SemIR::InstId> {
  2493. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  2494. llvm::SmallVector<SemIR::InstId> inst_ids;
  2495. inst_ids.reserve(import_block.size());
  2496. for (auto import_inst_id : import_block) {
  2497. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  2498. resolver.ResolveOneInst(import_inst_id)));
  2499. }
  2500. return inst_ids;
  2501. }
  2502. // Resolves and returns a local eval block for a region of an imported
  2503. // generic.
  2504. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  2505. const SemIR::Generic& import_generic,
  2506. SemIR::GenericId generic_id,
  2507. SemIR::GenericInstIndex::Region region)
  2508. -> SemIR::InstBlockId {
  2509. auto import_block_id = import_generic.GetEvalBlock(region);
  2510. if (!import_block_id.is_valid()) {
  2511. return SemIR::InstBlockId::Invalid;
  2512. }
  2513. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2514. return RebuildGenericEvalBlock(resolver.local_context(), generic_id, region,
  2515. inst_ids);
  2516. }
  2517. // Fills in the remaining information in a partially-imported generic.
  2518. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  2519. ImportContext::PendingGeneric pending)
  2520. -> void {
  2521. const auto& import_generic =
  2522. resolver.import_generics().Get(pending.import_id);
  2523. // Don't store the local generic between calls: the generics list can be
  2524. // reallocated by ResolveLocalEvalBlock importing more specifics.
  2525. auto decl_block_id =
  2526. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2527. SemIR::GenericInstIndex::Region::Declaration);
  2528. resolver.local_generics().Get(pending.local_id).decl_block_id = decl_block_id;
  2529. auto local_decl_id = resolver.local_generics().Get(pending.local_id).decl_id;
  2530. auto self_specific_id = MakeSelfSpecific(resolver.local_context(),
  2531. local_decl_id, pending.local_id);
  2532. resolver.local_generics().Get(pending.local_id).self_specific_id =
  2533. self_specific_id;
  2534. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  2535. .local_id = self_specific_id});
  2536. auto definition_block_id =
  2537. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2538. SemIR::GenericInstIndex::Region::Definition);
  2539. resolver.local_generics().Get(pending.local_id).definition_block_id =
  2540. definition_block_id;
  2541. }
  2542. // Resolves and returns a local inst block of constant instructions
  2543. // corresponding to an imported inst block.
  2544. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  2545. SemIR::InstBlockId import_block_id)
  2546. -> SemIR::InstBlockId {
  2547. if (!import_block_id.is_valid()) {
  2548. return SemIR::InstBlockId::Invalid;
  2549. }
  2550. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2551. return resolver.local_inst_blocks().Add(inst_ids);
  2552. }
  2553. // Fills in the remaining information in a partially-imported specific.
  2554. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  2555. ImportContext::PendingSpecific pending)
  2556. -> void {
  2557. const auto& import_specific =
  2558. resolver.import_specifics().Get(pending.import_id);
  2559. // Don't store the local specific between calls: the specifics list can be
  2560. // reallocated by ResolveLocalInstBlock importing more specifics.
  2561. if (!resolver.local_specifics()
  2562. .Get(pending.local_id)
  2563. .decl_block_id.is_valid()) {
  2564. auto decl_block_id =
  2565. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  2566. resolver.local_specifics().Get(pending.local_id).decl_block_id =
  2567. decl_block_id;
  2568. }
  2569. if (!resolver.local_specifics()
  2570. .Get(pending.local_id)
  2571. .definition_block_id.is_valid() &&
  2572. import_specific.definition_block_id.is_valid()) {
  2573. auto definition_block_id =
  2574. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  2575. resolver.local_specifics().Get(pending.local_id).definition_block_id =
  2576. definition_block_id;
  2577. }
  2578. }
  2579. // Perform any work that we deferred until the end of the main Resolve loop.
  2580. auto ImportRefResolver::PerformPendingWork() -> void {
  2581. // Note that the individual Finish steps can add new pending work, so keep
  2582. // going until we have no more work to do.
  2583. while (!pending_generics().empty() || !pending_specifics().empty()) {
  2584. // Process generics in the order that we added them because a later
  2585. // generic might refer to an earlier one, and the calls to
  2586. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  2587. // state.
  2588. // TODO: Import the generic eval block rather than calling
  2589. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  2590. // NOLINTNEXTLINE(modernize-loop-convert)
  2591. for (size_t i = 0; i != pending_generics().size(); ++i) {
  2592. FinishPendingGeneric(*this, pending_generics()[i]);
  2593. }
  2594. pending_generics().clear();
  2595. while (!pending_specifics().empty()) {
  2596. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  2597. }
  2598. }
  2599. }
  2600. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  2601. // loaded (including the one pointed at directly by the ImportRef), and the
  2602. // final instruction's type ID.
  2603. //
  2604. // This addresses cases where an ImportRefUnloaded may point at another
  2605. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  2606. // constant-evaluated version of the instruction to work with.
  2607. static auto GetInstForLoad(Context& context,
  2608. SemIR::ImportIRInstId import_ir_inst_id)
  2609. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  2610. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  2611. {}, SemIR::TypeId::Invalid};
  2612. auto& [import_ir_insts, type_id] = result;
  2613. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  2614. // The first ImportIRInst is added directly because the IR doesn't need to be
  2615. // localized.
  2616. import_ir_insts.push_back(import_ir_inst);
  2617. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2618. while (true) {
  2619. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  2620. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  2621. if (!import_ref) {
  2622. type_id = cursor_inst.type_id();
  2623. return result;
  2624. }
  2625. import_ir_inst =
  2626. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  2627. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2628. import_ir_insts.push_back(
  2629. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  2630. .is_export = false,
  2631. .sem_ir = cursor_ir}),
  2632. .inst_id = import_ir_inst.inst_id});
  2633. }
  2634. }
  2635. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  2636. if (inst_id.is_poisoned()) {
  2637. return;
  2638. }
  2639. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  2640. if (!inst) {
  2641. return;
  2642. }
  2643. auto [indirect_insts, load_type_id] =
  2644. GetInstForLoad(context, inst->import_ir_inst_id);
  2645. // The last indirect instruction is the one to resolve. Pop it here because
  2646. // Resolve will assign the constant.
  2647. auto load_ir_inst = indirect_insts.pop_back_val();
  2648. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  2649. // The resolver calls into Context to create instructions. Don't register
  2650. // those instructions as part of the enclosing generic scope if they're
  2651. // dependent on a generic parameter.
  2652. context.generic_region_stack().Push();
  2653. auto type_id = resolver.ResolveType(load_type_id);
  2654. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  2655. context.generic_region_stack().Pop();
  2656. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  2657. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  2658. // TryEvalInst, which we want to avoid with ImportRefs.
  2659. context.sem_ir().insts().Set(
  2660. inst_id,
  2661. SemIR::ImportRefLoaded{.type_id = type_id,
  2662. .import_ir_inst_id = inst->import_ir_inst_id,
  2663. .entity_name_id = inst->entity_name_id});
  2664. // Store the constant for both the ImportRefLoaded and indirect instructions.
  2665. context.constant_values().Set(inst_id, constant_id);
  2666. for (const auto& import_ir_inst : indirect_insts) {
  2667. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  2668. import_ir_inst.inst_id, constant_id);
  2669. }
  2670. }
  2671. auto ImportImplsFromApiFile(Context& context) -> void {
  2672. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  2673. auto& import_ir = context.import_irs().Get(import_ir_id);
  2674. if (!import_ir.sem_ir) {
  2675. return;
  2676. }
  2677. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  2678. SemIR::ImplId impl_id(impl_index);
  2679. // Resolve the imported impl to a local impl ID.
  2680. ImportImpl(context, import_ir_id, impl_id);
  2681. }
  2682. }
  2683. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  2684. SemIR::ImplId impl_id) -> void {
  2685. ImportRefResolver resolver(context, import_ir_id);
  2686. context.generic_region_stack().Push();
  2687. resolver.Resolve(context.import_irs()
  2688. .Get(import_ir_id)
  2689. .sem_ir->impls()
  2690. .Get(impl_id)
  2691. .first_decl_id());
  2692. context.generic_region_stack().Pop();
  2693. }
  2694. } // namespace Carbon::Check