import_ref.cpp 151 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687
  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 <optional>
  6. #include <tuple>
  7. #include <type_traits>
  8. #include <utility>
  9. #include "common/check.h"
  10. #include "common/growing_range.h"
  11. #include "toolchain/base/kind_switch.h"
  12. #include "toolchain/check/context.h"
  13. #include "toolchain/check/eval.h"
  14. #include "toolchain/check/generic.h"
  15. #include "toolchain/check/import.h"
  16. #include "toolchain/check/inst.h"
  17. #include "toolchain/check/name_lookup.h"
  18. #include "toolchain/check/type.h"
  19. #include "toolchain/check/type_completion.h"
  20. #include "toolchain/parse/node_ids.h"
  21. #include "toolchain/sem_ir/constant.h"
  22. #include "toolchain/sem_ir/file.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/import_ir.h"
  25. #include "toolchain/sem_ir/inst.h"
  26. #include "toolchain/sem_ir/inst_categories.h"
  27. #include "toolchain/sem_ir/inst_kind.h"
  28. #include "toolchain/sem_ir/type_info.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. namespace Carbon::Check {
  31. // Adds the ImportIR, excluding the update to the check_ir_map.
  32. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  33. -> SemIR::ImportIRId {
  34. context.import_ir_constant_values().push_back(SemIR::ConstantValueStore(
  35. SemIR::ConstantId::None,
  36. import_ir.sem_ir ? &import_ir.sem_ir->insts() : nullptr));
  37. return context.import_irs().Add(import_ir);
  38. }
  39. // Adds a special-cased IR and verifies it received the correct ID.
  40. static auto SetSpecialImportIR(Context& context, SemIR::ImportIR import_ir,
  41. SemIR::ImportIRId expected_import_ir_id)
  42. -> void {
  43. auto ir_id = SemIR::ImportIRId::None;
  44. if (import_ir.sem_ir != nullptr) {
  45. ir_id = AddImportIR(context, import_ir);
  46. } else {
  47. // We don't have a check_ir_id, so add without touching check_ir_map.
  48. context.import_ir_constant_values().push_back(
  49. SemIR::ConstantValueStore(SemIR::ConstantValueStore::Unusable));
  50. ir_id = context.import_irs().Add(import_ir);
  51. }
  52. CARBON_CHECK(ir_id == expected_import_ir_id,
  53. "Actual ImportIRId ($0) != Expected ImportIRId ({1})", ir_id,
  54. expected_import_ir_id);
  55. }
  56. auto SetSpecialImportIRs(Context& context, SemIR::ImportIR import_ir) -> void {
  57. SetSpecialImportIR(context, import_ir, SemIR::ImportIRId::ApiForImpl);
  58. SetSpecialImportIR(context,
  59. {.decl_id = SemIR::InstId::None, .is_export = false},
  60. SemIR::ImportIRId::Cpp);
  61. }
  62. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  63. -> SemIR::ImportIRId {
  64. auto& ir_id = context.check_ir_map().Get(import_ir.sem_ir->check_ir_id());
  65. if (!ir_id.has_value()) {
  66. // Note this updates check_ir_map.
  67. ir_id = InternalAddImportIR(context, import_ir);
  68. } else if (import_ir.is_export) {
  69. // We're processing an `export import`. In case the IR was indirectly added
  70. // as a non-export, mark it as an export.
  71. context.import_irs().Get(ir_id).is_export = true;
  72. }
  73. return ir_id;
  74. }
  75. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  76. SemIR::EntityNameId entity_name_id =
  77. SemIR::EntityNameId::None) -> SemIR::InstId {
  78. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  79. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  80. .entity_name_id = entity_name_id};
  81. auto import_ref_id = AddPlaceholderInstInNoBlock(
  82. context, MakeImportedLocIdAndInst(context, import_ir_inst_id, inst));
  83. // ImportRefs have a dedicated block because this may be called during
  84. // processing where the instruction shouldn't be inserted in the current inst
  85. // block.
  86. context.imports().push_back(import_ref_id);
  87. return import_ref_id;
  88. }
  89. // Adds an import_ref instruction for an instruction that we have already loaded
  90. // from an imported IR, with a known constant value. This is useful when the
  91. // instruction has a symbolic constant value, in order to produce an instruction
  92. // that hold that symbolic constant.
  93. static auto AddLoadedImportRef(Context& context, SemIR::TypeId type_id,
  94. SemIR::ImportIRInst import_ir_inst,
  95. SemIR::ConstantId const_id) -> SemIR::InstId {
  96. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  97. SemIR::ImportRefLoaded inst = {.type_id = type_id,
  98. .import_ir_inst_id = import_ir_inst_id,
  99. .entity_name_id = SemIR::EntityNameId::None};
  100. auto inst_id = AddPlaceholderInstInNoBlock(
  101. context, MakeImportedLocIdAndInst(context, import_ir_inst_id, inst));
  102. context.imports().push_back(inst_id);
  103. context.constant_values().Set(inst_id, const_id);
  104. context.import_ir_constant_values()[import_ir_inst.ir_id().index].Set(
  105. import_ir_inst.inst_id(), const_id);
  106. return inst_id;
  107. }
  108. static auto GetCanonicalImportIRInst(Context& context,
  109. const SemIR::File* target_ir,
  110. SemIR::InstId target_inst_id)
  111. -> SemIR::ImportIRInst {
  112. auto [canonical_ir, canonical_inst_id] =
  113. GetCanonicalFileAndInstId(target_ir, target_inst_id);
  114. auto ir_id = SemIR::ImportIRId::None;
  115. if (canonical_ir != &context.sem_ir()) {
  116. // This uses AddImportIR in case it was indirectly found, which can
  117. // happen with two or more steps of exports.
  118. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::None,
  119. .is_export = false,
  120. .sem_ir = canonical_ir});
  121. }
  122. return SemIR::ImportIRInst(ir_id, canonical_inst_id);
  123. }
  124. auto GetCanonicalImportIRInst(Context& context, SemIR::InstId inst_id)
  125. -> SemIR::ImportIRInst {
  126. return GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  127. }
  128. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::NameId name_id,
  129. SemIR::InstId prev_id,
  130. SemIR::ImportIRInst prev_import_ir_inst,
  131. SemIR::ImportIRId new_ir_id,
  132. const SemIR::File* new_import_ir,
  133. SemIR::InstId new_inst_id) -> void {
  134. auto new_import_ir_inst =
  135. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  136. if (new_import_ir_inst == prev_import_ir_inst) {
  137. return;
  138. }
  139. auto conflict_id =
  140. AddImportRef(context, SemIR::ImportIRInst(new_ir_id, new_inst_id));
  141. // TODO: Pass the imported name location instead of the conflict id.
  142. DiagnoseDuplicateName(context, name_id, SemIR::LocId(conflict_id),
  143. SemIR::LocId(prev_id));
  144. }
  145. namespace {
  146. class ImportRefResolver;
  147. // The result of attempting to resolve an imported instruction to a constant.
  148. struct ResolveResult {
  149. // The new constant value, if known.
  150. SemIR::ConstantId const_id;
  151. // Newly created declaration whose value is being resolved, if any.
  152. SemIR::InstId decl_id = SemIR::InstId::None;
  153. // Whether resolution has been attempted once and needs to be retried.
  154. bool retry = false;
  155. // Produces a resolve result that tries resolving this instruction again. If
  156. // `const_id` is specified, then this is the end of the second phase, and the
  157. // constant value will be passed to the next resolution attempt. Otherwise,
  158. // this is the end of the first phase.
  159. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::None,
  160. SemIR::InstId decl_id = SemIR::InstId::None)
  161. -> ResolveResult {
  162. return {.const_id = const_id, .decl_id = decl_id, .retry = true};
  163. }
  164. // Produces a resolve result that provides the given constant value. Requires
  165. // that there is no new work.
  166. static auto Done(SemIR::ConstantId const_id,
  167. SemIR::InstId decl_id = SemIR::InstId::None)
  168. -> ResolveResult {
  169. return {.const_id = const_id, .decl_id = decl_id};
  170. }
  171. };
  172. } // namespace
  173. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  174. SemIR::ConstantId const_id) -> ResolveResult;
  175. namespace {
  176. // A context within which we are performing an import. Tracks information about
  177. // the source and destination. This provides a restricted interface compared to
  178. // ImportResolver: in particular, it does not have access to a work list.
  179. // Therefore code that accepts an ImportContext is unable to enqueue new work.
  180. class ImportContext {
  181. public:
  182. // A generic that we have partially imported.
  183. struct PendingGeneric {
  184. SemIR::GenericId import_id;
  185. SemIR::GenericId local_id;
  186. };
  187. // A specific that we have partially imported.
  188. struct PendingSpecific {
  189. SemIR::SpecificId import_id;
  190. SemIR::SpecificId local_id;
  191. };
  192. // `context` must not be null.
  193. explicit ImportContext(Context* context, SemIR::ImportIRId import_ir_id)
  194. : context_(context),
  195. import_ir_id_(import_ir_id),
  196. import_ir_(*context_->import_irs().Get(import_ir_id).sem_ir) {}
  197. // Returns the file we are importing from.
  198. auto import_ir() -> const SemIR::File& { return import_ir_; }
  199. // Accessors into value stores of the file we are importing from.
  200. auto import_associated_constants() -> decltype(auto) {
  201. return import_ir().associated_constants();
  202. }
  203. auto import_classes() -> decltype(auto) { return import_ir().classes(); }
  204. auto import_vtables() -> decltype(auto) { return import_ir().vtables(); }
  205. auto import_constant_values() -> decltype(auto) {
  206. return import_ir().constant_values();
  207. }
  208. auto import_entity_names() -> decltype(auto) {
  209. return import_ir().entity_names();
  210. }
  211. auto import_facet_types() -> decltype(auto) {
  212. return import_ir().facet_types();
  213. }
  214. auto import_functions() -> decltype(auto) { return import_ir().functions(); }
  215. auto import_generics() -> decltype(auto) { return import_ir().generics(); }
  216. auto import_identifiers() -> decltype(auto) {
  217. return import_ir().identifiers();
  218. }
  219. auto import_impls() -> decltype(auto) { return import_ir().impls(); }
  220. auto import_inst_blocks() -> decltype(auto) {
  221. return import_ir().inst_blocks();
  222. }
  223. auto import_insts() -> decltype(auto) { return import_ir().insts(); }
  224. auto import_interfaces() -> decltype(auto) {
  225. return import_ir().interfaces();
  226. }
  227. auto import_ints() -> decltype(auto) { return import_ir().ints(); }
  228. auto import_name_scopes() -> decltype(auto) {
  229. return import_ir().name_scopes();
  230. }
  231. auto import_specifics() -> decltype(auto) { return import_ir().specifics(); }
  232. auto import_specific_interfaces() -> decltype(auto) {
  233. return import_ir().specific_interfaces();
  234. }
  235. auto import_string_literal_values() -> decltype(auto) {
  236. return import_ir().string_literal_values();
  237. }
  238. auto import_struct_type_fields() -> decltype(auto) {
  239. return import_ir().struct_type_fields();
  240. }
  241. auto import_types() -> decltype(auto) { return import_ir().types(); }
  242. // Returns the local file's import ID for the IR we are importing from.
  243. auto import_ir_id() -> SemIR::ImportIRId { return import_ir_id_; }
  244. // A value store for local constant values of imported instructions. This maps
  245. // from `InstId`s in the import IR to corresponding `ConstantId`s in the local
  246. // IR.
  247. auto local_constant_values_for_import_insts() -> decltype(auto) {
  248. return local_context().import_ir_constant_values()[import_ir_id_.index];
  249. }
  250. // Returns the file we are importing into.
  251. auto local_ir() -> SemIR::File& { return context_->sem_ir(); }
  252. // Returns the type-checking context we are importing into.
  253. auto local_context() -> Context& { return *context_; }
  254. // Accessors into value stores of the file we are importing into.
  255. auto local_associated_constants() -> decltype(auto) {
  256. return local_ir().associated_constants();
  257. }
  258. auto local_classes() -> decltype(auto) { return local_ir().classes(); }
  259. auto local_vtables() -> decltype(auto) { return local_ir().vtables(); }
  260. auto local_constant_values() -> decltype(auto) {
  261. return local_ir().constant_values();
  262. }
  263. auto local_entity_names() -> decltype(auto) {
  264. return local_ir().entity_names();
  265. }
  266. auto local_facet_types() -> decltype(auto) {
  267. return local_ir().facet_types();
  268. }
  269. auto local_functions() -> decltype(auto) { return local_ir().functions(); }
  270. auto local_generics() -> decltype(auto) { return local_ir().generics(); }
  271. auto local_identifiers() -> decltype(auto) {
  272. return local_ir().identifiers();
  273. }
  274. auto local_impls() -> decltype(auto) { return local_ir().impls(); }
  275. auto local_import_ir_insts() -> decltype(auto) {
  276. return local_ir().import_ir_insts();
  277. }
  278. auto local_inst_blocks() -> decltype(auto) {
  279. return local_ir().inst_blocks();
  280. }
  281. auto local_insts() -> decltype(auto) { return local_ir().insts(); }
  282. auto local_interfaces() -> decltype(auto) { return local_ir().interfaces(); }
  283. auto local_ints() -> decltype(auto) { return local_ir().ints(); }
  284. auto local_name_scopes() -> decltype(auto) {
  285. return local_ir().name_scopes();
  286. }
  287. auto local_specifics() -> decltype(auto) { return local_ir().specifics(); }
  288. auto local_specific_interfaces() -> decltype(auto) {
  289. return local_ir().specific_interfaces();
  290. }
  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 Done() to finish the resolution process. This will cause the
  376. // Resolve loop to set a constant value if we didn't retry at the end of
  377. // the second phase.
  378. //
  379. // In the common case where the second phase cannot add new work (because the
  380. // inst doesn't represent a declaration of an entity that can be forward
  381. // declared), the second and third phases are usually expressed as a call to
  382. // ResolveAsDeduplicated or ResolveAsUnique.
  383. //
  384. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  385. // remain, and may no longer be at the top of the stack; update the state of
  386. // the work item to track what work still needs to be done.
  387. //
  388. // The same instruction can be enqueued for resolution multiple times. However,
  389. // we will only reach the second phase once: once a constant value is set, only
  390. // the resolution step that set it will retry.
  391. //
  392. // TODO: Fix class `extern` handling and merging, rewrite tests.
  393. // - check/testdata/class/cross_package_import.carbon
  394. // - check/testdata/class/extern.carbon
  395. // TODO: Fix function `extern` handling and merging, rewrite tests.
  396. // - check/testdata/function/declaration/import.carbon
  397. // - check/testdata/packages/cross_package_import.carbon
  398. class ImportRefResolver : public ImportContext {
  399. public:
  400. // `context` must not be null.
  401. explicit ImportRefResolver(Context* context, SemIR::ImportIRId import_ir_id)
  402. : ImportContext(context, import_ir_id) {}
  403. // Iteratively resolves an imported instruction's inner references until a
  404. // constant ID referencing the current IR is produced. See the class comment
  405. // for more details.
  406. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId {
  407. work_stack_.push_back({.inst_id = inst_id});
  408. while (!work_stack_.empty()) {
  409. auto work = work_stack_.back();
  410. CARBON_CHECK(work.inst_id.has_value());
  411. // Step 1: check for a constant value.
  412. auto existing = FindResolvedConstId(work.inst_id);
  413. if (existing.const_id == SemIR::ErrorInst::ConstantId) {
  414. return existing.const_id;
  415. }
  416. if (existing.const_id.has_value() && !work.retry_with_constant_value) {
  417. work_stack_.pop_back();
  418. continue;
  419. }
  420. // Step 2: resolve the instruction.
  421. initial_work_ = work_stack_.size();
  422. auto [new_const_id, _, retry] =
  423. TryResolveInst(*this, work.inst_id, existing.const_id);
  424. CARBON_CHECK(!HasNewWork() || retry);
  425. CARBON_CHECK(
  426. !existing.const_id.has_value() || existing.const_id == new_const_id,
  427. "Constant value changed in third phase.");
  428. if (!existing.const_id.has_value()) {
  429. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  430. }
  431. // Step 3: pop or retry.
  432. if (retry) {
  433. work_stack_[initial_work_ - 1].retry_with_constant_value =
  434. new_const_id.has_value();
  435. } else {
  436. work_stack_.pop_back();
  437. }
  438. }
  439. auto constant_id =
  440. local_constant_values_for_import_insts().GetAttached(inst_id);
  441. CARBON_CHECK(constant_id.has_value());
  442. return constant_id;
  443. }
  444. // Performs resolution for one instruction and then performs all work we
  445. // deferred.
  446. // NOLINTNEXTLINE(misc-no-recursion)
  447. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  448. auto const_id = ResolveOneInst(inst_id);
  449. PerformPendingWork();
  450. return const_id;
  451. }
  452. // Wraps constant evaluation with logic to handle constants.
  453. // NOLINTNEXTLINE(misc-no-recursion)
  454. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  455. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  456. }
  457. // Wraps constant evaluation with logic to handle types.
  458. // NOLINTNEXTLINE(misc-no-recursion)
  459. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  460. if (!import_type_id.has_value()) {
  461. return import_type_id;
  462. }
  463. auto import_type_const_id =
  464. import_ir().types().GetConstantId(import_type_id);
  465. CARBON_CHECK(import_type_const_id.has_value());
  466. if (auto import_type_inst_id = import_ir().types().GetAsTypeInstId(
  467. import_ir().constant_values().GetInstId(import_type_const_id));
  468. SemIR::IsSingletonInstId(import_type_inst_id)) {
  469. // Builtins don't require constant resolution; we can use them directly.
  470. return GetSingletonType(local_context(), import_type_inst_id);
  471. } else {
  472. return local_context().types().GetTypeIdForTypeConstantId(
  473. ResolveConstant(import_type_id.AsConstantId()));
  474. }
  475. }
  476. // Returns true if new unresolved constants were found as part of this
  477. // `Resolve` step.
  478. auto HasNewWork() -> bool {
  479. CARBON_CHECK(initial_work_ <= work_stack_.size(),
  480. "Work shouldn't decrease");
  481. return initial_work_ < work_stack_.size();
  482. }
  483. // Returns the ConstantId for an InstId. Adds unresolved constants to
  484. // work_stack_.
  485. auto GetLocalConstantValueOrPush(SemIR::InstId inst_id) -> SemIR::ConstantId {
  486. if (!inst_id.has_value()) {
  487. return SemIR::ConstantId::None;
  488. }
  489. auto const_id =
  490. local_constant_values_for_import_insts().GetAttached(inst_id);
  491. if (!const_id.has_value()) {
  492. work_stack_.push_back({.inst_id = inst_id});
  493. }
  494. return const_id;
  495. }
  496. private:
  497. // A step in work_stack_.
  498. struct Work {
  499. // The instruction to work on.
  500. SemIR::InstId inst_id;
  501. // Whether this work item set the constant value for the instruction and
  502. // requested a retry.
  503. bool retry_with_constant_value = false;
  504. };
  505. // The constant found by FindResolvedConstId.
  506. struct ResolvedConstId {
  507. // The constant for the instruction. `None` if not yet resolved.
  508. SemIR::ConstantId const_id = SemIR::ConstantId::None;
  509. // Instructions which are indirect but equivalent to the current instruction
  510. // being resolved, and should have their constant set to the same. Empty
  511. // when `const_id` has a value.
  512. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  513. };
  514. // Looks to see if an instruction has been resolved. If a constant is only
  515. // found indirectly, sets the constant for any indirect steps that don't
  516. // already have the constant. If a constant isn't found, returns the indirect
  517. // instructions so that they can have the resolved constant assigned later.
  518. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  519. ResolvedConstId result;
  520. if (auto existing_const_id =
  521. local_constant_values_for_import_insts().GetAttached(inst_id);
  522. existing_const_id.has_value()) {
  523. result.const_id = existing_const_id;
  524. return result;
  525. }
  526. const auto* cursor_ir = &import_ir();
  527. auto cursor_inst_id = inst_id;
  528. while (true) {
  529. auto import_ir_inst_id =
  530. cursor_ir->insts().GetImportSource(cursor_inst_id);
  531. if (!import_ir_inst_id.has_value()) {
  532. return result;
  533. }
  534. auto ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
  535. if (ir_inst.ir_id() == SemIR::ImportIRId::Cpp) {
  536. local_context().TODO(SemIR::LocId::None,
  537. "Unsupported: Importing C++ indirectly");
  538. return {.const_id = SemIR::ErrorInst::ConstantId};
  539. }
  540. const auto* prev_ir = cursor_ir;
  541. auto prev_inst_id = cursor_inst_id;
  542. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id()).sem_ir;
  543. auto cursor_ir_id =
  544. AddImportIR(local_context(), {.decl_id = SemIR::InstId::None,
  545. .is_export = false,
  546. .sem_ir = cursor_ir});
  547. cursor_inst_id = ir_inst.inst_id();
  548. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id,
  549. "{0}", cursor_ir->insts().Get(cursor_inst_id));
  550. if (auto const_id = local_context()
  551. .import_ir_constant_values()[cursor_ir_id.index]
  552. .GetAttached(cursor_inst_id);
  553. const_id.has_value()) {
  554. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  555. result.const_id = const_id;
  556. result.indirect_insts.clear();
  557. return result;
  558. } else {
  559. result.indirect_insts.push_back(
  560. SemIR::ImportIRInst(cursor_ir_id, cursor_inst_id));
  561. }
  562. }
  563. }
  564. // Sets a resolved constant into the current and indirect instructions.
  565. auto SetResolvedConstId(SemIR::InstId inst_id,
  566. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  567. SemIR::ConstantId const_id) -> void {
  568. local_constant_values_for_import_insts().Set(inst_id, const_id);
  569. for (auto indirect_inst : indirect_insts) {
  570. local_context()
  571. .import_ir_constant_values()[indirect_inst.ir_id().index]
  572. .Set(indirect_inst.inst_id(), const_id);
  573. }
  574. }
  575. auto PerformPendingWork() -> void;
  576. llvm::SmallVector<Work> work_stack_;
  577. // The size of work_stack_ at the start of resolving the current instruction.
  578. size_t initial_work_ = 0;
  579. };
  580. } // namespace
  581. static auto AddImportRef(ImportContext& context, SemIR::InstId inst_id,
  582. SemIR::EntityNameId entity_name_id =
  583. SemIR::EntityNameId::None) -> SemIR::InstId {
  584. return AddImportRef(context.local_context(),
  585. SemIR::ImportIRInst(context.import_ir_id(), inst_id),
  586. entity_name_id);
  587. }
  588. static auto AddLoadedImportRef(ImportContext& context, SemIR::TypeId type_id,
  589. SemIR::InstId inst_id,
  590. SemIR::ConstantId const_id) -> SemIR::InstId {
  591. return AddLoadedImportRef(
  592. context.local_context(), type_id,
  593. SemIR::ImportIRInst(context.import_ir_id(), inst_id), const_id);
  594. }
  595. static auto AddImportIRInst(ImportContext& context, SemIR::InstId inst_id)
  596. -> SemIR::ImportIRInstId {
  597. return context.local_import_ir_insts().Add(
  598. SemIR::ImportIRInst(context.import_ir_id(), inst_id));
  599. }
  600. // Computes, sets, and returns the constant value for an instruction.
  601. static auto SetConstantValue(Context& context, SemIR::InstId inst_id,
  602. SemIR::Inst inst) -> SemIR::ConstantId {
  603. auto const_id = TryEvalInstUnsafe(context, inst_id, inst);
  604. if (const_id.is_constant()) {
  605. CARBON_VLOG_TO(context.vlog_stream(), "Constant: {0} -> {1}\n", inst,
  606. context.constant_values().GetInstId(const_id));
  607. }
  608. context.constant_values().Set(inst_id, const_id);
  609. return const_id;
  610. }
  611. // Adds an imported instruction without setting its constant value. The
  612. // instruction should later be updated by either `SetConstantValue` or
  613. // `ReplacePlaceholderImportedInst`.
  614. template <typename InstT>
  615. static auto AddPlaceholderImportedInst(ImportContext& context,
  616. SemIR::InstId import_inst_id, InstT inst)
  617. -> SemIR::InstId {
  618. auto inst_id = context.local_insts().AddInNoBlock(MakeImportedLocIdAndInst(
  619. context.local_context(), AddImportIRInst(context, import_inst_id), inst));
  620. CARBON_VLOG_TO(context.local_context().vlog_stream(),
  621. "AddPlaceholderImportedInst: {0}\n", inst);
  622. // Track the instruction in the imports block so that it's included in
  623. // formatted SemIR if it's referenced.
  624. context.local_context().imports().push_back(inst_id);
  625. return inst_id;
  626. }
  627. // Replace an imported instruction that was added by
  628. // `AddPlaceholderImportedInst` with a new instruction. Computes, sets, and
  629. // returns the new constant value.
  630. static auto ReplacePlaceholderImportedInst(ImportContext& context,
  631. SemIR::InstId inst_id,
  632. SemIR::Inst inst)
  633. -> SemIR::ConstantId {
  634. CARBON_VLOG_TO(context.local_context().vlog_stream(),
  635. "ReplaceImportedInst: {0} -> {1}\n", inst_id, inst);
  636. context.local_insts().Set(inst_id, inst);
  637. CARBON_CHECK(context.local_constant_values().Get(inst_id) ==
  638. SemIR::ConstantId::NotConstant);
  639. return SetConstantValue(context.local_context(), inst_id, inst);
  640. }
  641. // Returns the ConstantId for an InstId. Adds unresolved constants to
  642. // the resolver's work stack.
  643. static auto GetLocalConstantId(ImportRefResolver& resolver,
  644. SemIR::InstId inst_id) -> SemIR::ConstantId {
  645. return resolver.GetLocalConstantValueOrPush(inst_id);
  646. }
  647. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  648. // constants to the resolver's work stack.
  649. static auto GetLocalConstantId(ImportRefResolver& resolver,
  650. SemIR::ConstantId const_id)
  651. -> SemIR::ConstantId {
  652. return GetLocalConstantId(
  653. resolver, GetInstWithConstantValue(resolver.import_ir(), const_id));
  654. }
  655. // Returns the local constant InstId for an imported InstId.
  656. static auto GetLocalConstantInstId(ImportRefResolver& resolver,
  657. SemIR::InstId inst_id) -> SemIR::InstId {
  658. auto const_id = GetLocalConstantId(resolver, inst_id);
  659. return resolver.local_constant_values().GetInstIdIfValid(const_id);
  660. }
  661. // Returns the local constant InstId for an imported InstId.
  662. static auto GetLocalTypeInstId(ImportRefResolver& resolver,
  663. SemIR::TypeInstId inst_id) -> SemIR::TypeInstId {
  664. // The input instruction is a TypeInstId, and import does not change the type
  665. // of instructions, so the result is also a valid TypeInstId.
  666. return SemIR::TypeInstId::UnsafeMake(
  667. GetLocalConstantInstId(resolver, static_cast<SemIR::InstId>(inst_id)));
  668. }
  669. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  670. // work_stack_.
  671. static auto GetLocalConstantId(ImportRefResolver& resolver,
  672. SemIR::TypeId type_id) -> SemIR::ConstantId {
  673. return GetLocalConstantId(resolver,
  674. resolver.import_types().GetConstantId(type_id));
  675. }
  676. // Translates a NameId from the import IR to a local NameId.
  677. static auto GetLocalNameId(ImportContext& context, SemIR::NameId import_name_id)
  678. -> SemIR::NameId {
  679. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.has_value()) {
  680. return SemIR::NameId::ForIdentifier(context.local_identifiers().Add(
  681. context.import_identifiers().Get(ident_id)));
  682. }
  683. return import_name_id;
  684. }
  685. // Gets the local constant values corresponding to an imported inst block.
  686. static auto GetLocalInstBlockContents(ImportRefResolver& resolver,
  687. SemIR::InstBlockId import_block_id)
  688. -> llvm::SmallVector<SemIR::InstId> {
  689. llvm::SmallVector<SemIR::InstId> inst_ids;
  690. if (!import_block_id.has_value() ||
  691. import_block_id == SemIR::InstBlockId::Empty) {
  692. return inst_ids;
  693. }
  694. // Import all the values in the block.
  695. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  696. inst_ids.reserve(import_block.size());
  697. for (auto import_inst_id : import_block) {
  698. auto const_id = GetLocalConstantId(resolver, import_inst_id);
  699. inst_ids.push_back(
  700. resolver.local_constant_values().GetInstIdIfValid(const_id));
  701. }
  702. return inst_ids;
  703. }
  704. // Gets a local canonical instruction block ID corresponding to an imported inst
  705. // block whose contents were already imported, for example by
  706. // GetLocalInstBlockContents.
  707. static auto GetLocalCanonicalInstBlockId(ImportContext& context,
  708. SemIR::InstBlockId import_block_id,
  709. llvm::ArrayRef<SemIR::InstId> contents)
  710. -> SemIR::InstBlockId {
  711. if (!import_block_id.has_value()) {
  712. return SemIR::InstBlockId::None;
  713. }
  714. return context.local_inst_blocks().AddCanonical(contents);
  715. }
  716. // Gets a local instruction block containing ImportRefs referring to the
  717. // instructions in the specified imported instruction block.
  718. static auto GetLocalImportRefInstBlock(ImportContext& context,
  719. SemIR::InstBlockId import_inst_block_id)
  720. -> SemIR::InstBlockId {
  721. llvm::SmallVector<SemIR::InstId> elements;
  722. auto import_elements = context.import_inst_blocks().Get(import_inst_block_id);
  723. elements.reserve(import_elements.size());
  724. for (auto element : import_elements) {
  725. elements.push_back(AddImportRef(context, element));
  726. }
  727. return context.local_inst_blocks().Add(elements);
  728. }
  729. // Gets an incomplete local version of an imported generic. Most fields are
  730. // set in the third phase.
  731. static auto MakeIncompleteGeneric(ImportContext& context, SemIR::InstId decl_id,
  732. SemIR::GenericId generic_id)
  733. -> SemIR::GenericId {
  734. if (!generic_id.has_value()) {
  735. return SemIR::GenericId::None;
  736. }
  737. return context.local_generics().Add(
  738. {.decl_id = decl_id,
  739. .bindings_id = SemIR::InstBlockId::None,
  740. .self_specific_id = SemIR::SpecificId::None});
  741. }
  742. namespace {
  743. // Local information associated with an imported generic.
  744. struct GenericData {
  745. // TODO: Delete `GenericData` if we still don't use it once generic import is
  746. // more stable.
  747. };
  748. } // namespace
  749. // Gets a local version of the data associated with a generic.
  750. static auto GetLocalGenericData(ImportRefResolver& /*resolver*/,
  751. SemIR::GenericId /*generic_id*/)
  752. -> GenericData {
  753. return {};
  754. }
  755. // Adds the given local generic data to the given generic.
  756. static auto SetGenericData(ImportContext& context,
  757. SemIR::GenericId import_generic_id,
  758. SemIR::GenericId new_generic_id,
  759. const GenericData& /*generic_data*/) -> void {
  760. if (!import_generic_id.has_value()) {
  761. return;
  762. }
  763. const auto& import_generic = context.import_generics().Get(import_generic_id);
  764. auto& new_generic = context.local_generics().Get(new_generic_id);
  765. new_generic.bindings_id =
  766. GetLocalImportRefInstBlock(context, import_generic.bindings_id);
  767. // Track that we need to fill in the remaining information in
  768. // FinishPendingGeneric.
  769. context.AddPendingGeneric(
  770. {.import_id = import_generic_id, .local_id = new_generic_id});
  771. }
  772. // Gets a local constant value corresponding to an imported generic ID. May
  773. // add work to the work stack and return `None`.
  774. static auto GetLocalConstantId(ImportRefResolver& resolver,
  775. SemIR::GenericId generic_id)
  776. -> SemIR::ConstantId {
  777. if (!generic_id.has_value()) {
  778. return SemIR::ConstantId::None;
  779. }
  780. auto import_decl_inst_id = resolver.import_generics().Get(generic_id).decl_id;
  781. auto import_decl_inst =
  782. resolver.import_insts().GetWithAttachedType(import_decl_inst_id);
  783. if (import_decl_inst.Is<SemIR::ImplDecl>()) {
  784. // For an impl declaration, the imported entity can be found via the
  785. // declaration.
  786. return GetLocalConstantId(resolver, import_decl_inst_id);
  787. }
  788. // For all other kinds of declaration, the imported entity can be found via
  789. // the type of the declaration.
  790. return GetLocalConstantId(resolver, import_decl_inst.type_id());
  791. }
  792. // Gets a local generic ID given the corresponding local constant ID returned
  793. // by GetLocalConstantId for the imported generic. Does not add any new work.
  794. static auto GetLocalGenericId(ImportContext& context,
  795. SemIR::ConstantId local_const_id)
  796. -> SemIR::GenericId {
  797. if (!local_const_id.has_value()) {
  798. return SemIR::GenericId::None;
  799. }
  800. auto inst = context.local_insts().Get(
  801. context.local_constant_values().GetInstId(local_const_id));
  802. CARBON_KIND_SWITCH(inst) {
  803. case CARBON_KIND(SemIR::FunctionType fn_type): {
  804. return context.local_functions().Get(fn_type.function_id).generic_id;
  805. }
  806. case CARBON_KIND(SemIR::GenericClassType class_type): {
  807. return context.local_classes().Get(class_type.class_id).generic_id;
  808. }
  809. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  810. return context.local_interfaces()
  811. .Get(interface_type.interface_id)
  812. .generic_id;
  813. }
  814. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  815. return context.local_impls().Get(impl_decl.impl_id).generic_id;
  816. }
  817. default: {
  818. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  819. }
  820. }
  821. }
  822. namespace {
  823. // Local information associated with an imported specific.
  824. struct SpecificData {
  825. SemIR::ConstantId generic_const_id;
  826. llvm::SmallVector<SemIR::InstId> args;
  827. };
  828. } // namespace
  829. // Gets local information about an imported specific.
  830. static auto GetLocalSpecificData(ImportRefResolver& resolver,
  831. SemIR::SpecificId specific_id)
  832. -> SpecificData {
  833. if (!specific_id.has_value()) {
  834. return {.generic_const_id = SemIR::ConstantId::None, .args = {}};
  835. }
  836. const auto& specific = resolver.import_specifics().Get(specific_id);
  837. return {
  838. .generic_const_id = GetLocalConstantId(resolver, specific.generic_id),
  839. .args = GetLocalInstBlockContents(resolver, specific.args_id),
  840. };
  841. }
  842. // Gets a local specific whose data was already imported by
  843. // GetLocalSpecificData. Does not add any new work.
  844. static auto GetOrAddLocalSpecific(ImportContext& context,
  845. SemIR::SpecificId import_specific_id,
  846. const SpecificData& data)
  847. -> SemIR::SpecificId {
  848. if (!import_specific_id.has_value()) {
  849. return SemIR::SpecificId::None;
  850. }
  851. // Form a corresponding local specific ID.
  852. const auto& import_specific =
  853. context.import_specifics().Get(import_specific_id);
  854. auto generic_id = GetLocalGenericId(context, data.generic_const_id);
  855. auto args_id =
  856. GetLocalCanonicalInstBlockId(context, import_specific.args_id, data.args);
  857. // Get the specific.
  858. auto specific_id = context.local_specifics().GetOrAdd(generic_id, args_id);
  859. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  860. auto& specific = context.local_specifics().Get(specific_id);
  861. if (!specific.decl_block_id.has_value() ||
  862. (import_specific.definition_block_id.has_value() &&
  863. !specific.definition_block_id.has_value())) {
  864. context.AddPendingSpecific(
  865. {.import_id = import_specific_id, .local_id = specific_id});
  866. }
  867. return specific_id;
  868. }
  869. namespace {
  870. struct SpecificInterfaceData {
  871. SemIR::ConstantId interface_const_id;
  872. SpecificData specific_data;
  873. };
  874. } // namespace
  875. static auto GetLocalSpecificInterfaceData(
  876. ImportRefResolver& resolver, SemIR::SpecificInterface import_interface)
  877. -> SpecificInterfaceData {
  878. SemIR::ConstantId interface_const_id = SemIR::ConstantId::None;
  879. if (import_interface.interface_id.has_value()) {
  880. interface_const_id =
  881. GetLocalConstantId(resolver, resolver.import_interfaces()
  882. .Get(import_interface.interface_id)
  883. .first_owning_decl_id);
  884. }
  885. return {.interface_const_id = interface_const_id,
  886. .specific_data =
  887. GetLocalSpecificData(resolver, import_interface.specific_id)};
  888. }
  889. static auto GetLocalSpecificInterface(
  890. ImportContext& context, SemIR::SpecificInterface import_specific_interface,
  891. SpecificInterfaceData interface_data) -> SemIR::SpecificInterface {
  892. if (!interface_data.interface_const_id.has_value()) {
  893. return SemIR::SpecificInterface::None;
  894. }
  895. // Find the corresponding interface type. For a non-generic interface,
  896. // this is the type of the interface declaration. For a generic interface,
  897. // build a interface type referencing this specialization of the generic
  898. // interface.
  899. auto interface_const_inst =
  900. context.local_insts().Get(context.local_constant_values().GetInstId(
  901. interface_data.interface_const_id));
  902. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  903. const SemIR::FacetTypeInfo& new_facet_type_info =
  904. context.local_facet_types().Get(facet_type->facet_type_id);
  905. return *new_facet_type_info.TryAsSingleInterface();
  906. } else {
  907. auto generic_interface_type =
  908. context.local_types().GetAs<SemIR::GenericInterfaceType>(
  909. interface_const_inst.type_id());
  910. auto specific_id =
  911. GetOrAddLocalSpecific(context, import_specific_interface.specific_id,
  912. interface_data.specific_data);
  913. return {generic_interface_type.interface_id, specific_id};
  914. }
  915. }
  916. static auto GetLocalNameScopeIdImpl(ImportRefResolver& resolver,
  917. SemIR::ConstantId const_id)
  918. -> SemIR::NameScopeId {
  919. if (!const_id.has_value()) {
  920. return SemIR::NameScopeId::None;
  921. }
  922. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  923. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  924. CARBON_KIND_SWITCH(name_scope_inst) {
  925. case CARBON_KIND(SemIR::Namespace inst): {
  926. return inst.name_scope_id;
  927. }
  928. case CARBON_KIND(SemIR::ClassType inst): {
  929. return resolver.local_classes().Get(inst.class_id).scope_id;
  930. }
  931. case CARBON_KIND(SemIR::FacetType inst): {
  932. const SemIR::FacetTypeInfo& facet_type_info =
  933. resolver.local_facet_types().Get(inst.facet_type_id);
  934. // This is specifically the facet type produced by an interface
  935. // declaration, and so should consist of a single interface.
  936. // TODO: Will also have to handle named constraints here, once those are
  937. // implemented.
  938. auto interface = facet_type_info.TryAsSingleInterface();
  939. CARBON_CHECK(interface);
  940. return resolver.local_interfaces().Get(interface->interface_id).scope_id;
  941. }
  942. case CARBON_KIND(SemIR::ImplDecl inst): {
  943. return resolver.local_impls().Get(inst.impl_id).scope_id;
  944. }
  945. case SemIR::StructValue::Kind: {
  946. auto type_inst =
  947. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  948. CARBON_KIND_SWITCH(type_inst) {
  949. case CARBON_KIND(SemIR::GenericClassType inst): {
  950. return resolver.local_classes().Get(inst.class_id).scope_id;
  951. }
  952. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  953. return resolver.local_interfaces().Get(inst.interface_id).scope_id;
  954. }
  955. default: {
  956. break;
  957. }
  958. }
  959. break;
  960. }
  961. default: {
  962. if (const_inst_id == SemIR::ErrorInst::InstId) {
  963. return SemIR::NameScopeId::None;
  964. }
  965. break;
  966. }
  967. }
  968. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  969. name_scope_inst);
  970. }
  971. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  972. // unresolved constants to the resolver's work stack.
  973. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  974. SemIR::NameScopeId name_scope_id)
  975. -> SemIR::NameScopeId {
  976. // Get the instruction that created the scope.
  977. auto [inst_id, inst] =
  978. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  979. if (!inst) {
  980. // Map scopes that aren't associated with an instruction to `None`. For now,
  981. // such scopes aren't used, and we don't have a good way to remap them.
  982. return SemIR::NameScopeId::None;
  983. }
  984. // Get the constant value for the scope.
  985. auto const_id = GetLocalConstantId(resolver, inst_id);
  986. if (!const_id.has_value()) {
  987. return SemIR::NameScopeId::None;
  988. }
  989. auto result = GetLocalNameScopeIdImpl(resolver, const_id);
  990. CARBON_CHECK(result.has_value());
  991. return result;
  992. }
  993. // Given an imported entity base, returns an incomplete, local version of it.
  994. //
  995. // Most fields are set in the third phase once they're imported. Import enough
  996. // of the parameter lists that we know whether this interface is a generic
  997. // interface and can build the right constant value for it.
  998. //
  999. // TODO: Support extern.
  1000. static auto GetIncompleteLocalEntityBase(
  1001. ImportContext& context, SemIR::InstId decl_id,
  1002. const SemIR::EntityWithParamsBase& import_base)
  1003. -> SemIR::EntityWithParamsBase {
  1004. // Translate the extern_library_id if present.
  1005. auto extern_library_id = SemIR::LibraryNameId::None;
  1006. if (import_base.extern_library_id.has_value()) {
  1007. if (import_base.extern_library_id.index >= 0) {
  1008. auto val = context.import_string_literal_values().Get(
  1009. import_base.extern_library_id.AsStringLiteralValueId());
  1010. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  1011. context.local_string_literal_values().Add(val));
  1012. } else {
  1013. extern_library_id = import_base.extern_library_id;
  1014. }
  1015. }
  1016. return {
  1017. .name_id = GetLocalNameId(context, import_base.name_id),
  1018. .parent_scope_id = SemIR::NameScopeId::None,
  1019. .generic_id =
  1020. MakeIncompleteGeneric(context, decl_id, import_base.generic_id),
  1021. .first_param_node_id = Parse::NodeId::None,
  1022. .last_param_node_id = Parse::NodeId::None,
  1023. .pattern_block_id = SemIR::InstBlockId::None,
  1024. .implicit_param_patterns_id =
  1025. import_base.implicit_param_patterns_id.has_value()
  1026. ? SemIR::InstBlockId::Empty
  1027. : SemIR::InstBlockId::None,
  1028. .param_patterns_id = import_base.param_patterns_id.has_value()
  1029. ? SemIR::InstBlockId::Empty
  1030. : SemIR::InstBlockId::None,
  1031. .is_extern = import_base.is_extern,
  1032. .extern_library_id = extern_library_id,
  1033. .non_owning_decl_id = import_base.non_owning_decl_id.has_value()
  1034. ? decl_id
  1035. : SemIR::InstId::None,
  1036. .first_owning_decl_id = import_base.first_owning_decl_id.has_value()
  1037. ? decl_id
  1038. : SemIR::InstId::None,
  1039. };
  1040. }
  1041. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1042. // lookup.
  1043. static auto AddNameScopeImportRefs(ImportContext& context,
  1044. const SemIR::NameScope& import_scope,
  1045. SemIR::NameScope& new_scope) -> void {
  1046. for (auto entry : import_scope.entries()) {
  1047. SemIR::ScopeLookupResult result = entry.result;
  1048. if (result.is_poisoned()) {
  1049. continue;
  1050. }
  1051. auto ref_id = AddImportRef(context, result.target_inst_id());
  1052. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1053. .result = SemIR::ScopeLookupResult::MakeFound(
  1054. ref_id, result.access_kind())});
  1055. }
  1056. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1057. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1058. }
  1059. }
  1060. // Given a block ID for a list of associated entities of a witness, returns a
  1061. // version localized to the current IR.
  1062. static auto AddAssociatedEntities(ImportContext& context,
  1063. SemIR::NameScopeId local_name_scope_id,
  1064. SemIR::InstBlockId associated_entities_id)
  1065. -> SemIR::InstBlockId {
  1066. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1067. return SemIR::InstBlockId::Empty;
  1068. }
  1069. auto associated_entities =
  1070. context.import_inst_blocks().Get(associated_entities_id);
  1071. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1072. new_associated_entities.reserve(associated_entities.size());
  1073. for (auto inst_id : associated_entities) {
  1074. // Determine the name of the associated entity, by switching on its kind.
  1075. SemIR::NameId import_name_id = SemIR::NameId::None;
  1076. if (auto assoc_const_decl =
  1077. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1078. inst_id)) {
  1079. const auto& assoc_const = context.import_associated_constants().Get(
  1080. assoc_const_decl->assoc_const_id);
  1081. import_name_id = assoc_const.name_id;
  1082. } else if (auto function_decl =
  1083. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1084. inst_id)) {
  1085. const auto& function =
  1086. context.import_functions().Get(function_decl->function_id);
  1087. import_name_id = function.name_id;
  1088. } else if (auto import_ref =
  1089. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1090. inst_id)) {
  1091. import_name_id =
  1092. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1093. } else {
  1094. // We don't need `GetWithAttachedType` here because we don't access the
  1095. // type.
  1096. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1097. context.import_insts().Get(inst_id).kind());
  1098. }
  1099. auto name_id = GetLocalNameId(context, import_name_id);
  1100. auto entity_name_id = context.local_entity_names().Add(
  1101. {.name_id = name_id, .parent_scope_id = local_name_scope_id});
  1102. new_associated_entities.push_back(
  1103. AddImportRef(context, inst_id, entity_name_id));
  1104. }
  1105. return context.local_inst_blocks().Add(new_associated_entities);
  1106. }
  1107. // Produces a resolve result that provides the given constant value. Retries
  1108. // instead if work has been added.
  1109. static auto RetryOrDone(ImportRefResolver& resolver, SemIR::ConstantId const_id)
  1110. -> ResolveResult {
  1111. if (resolver.HasNewWork()) {
  1112. return ResolveResult::Retry();
  1113. }
  1114. return ResolveResult::Done(const_id);
  1115. }
  1116. // Internal concept for instruction kinds that produce unique constants.
  1117. template <typename InstT>
  1118. concept HasUniqueConstantKind =
  1119. InstT::Kind.constant_kind() == SemIR::InstConstantKind::AlwaysUnique ||
  1120. InstT::Kind.constant_kind() == SemIR::InstConstantKind::ConditionalUnique;
  1121. // Adds `inst` to the local context as a deduplicated constant and returns a
  1122. // successful `ResolveResult`. Requires that there is no new work.
  1123. //
  1124. // This implements phases 2 and 3 of resolving the inst (as described above) for
  1125. // the common case where those phases are combined. Cases where that isn't
  1126. // applicable should instead use `AddPlaceholderImportedInst` and
  1127. // `ReplacePlaceholderImportedInst`.
  1128. //
  1129. // This should not be used for instructions that represent declarations, or
  1130. // other instructions with `constant_kind == InstConstantKind::Unique`, because
  1131. // they should not be deduplicated.
  1132. template <typename InstT>
  1133. requires(!HasUniqueConstantKind<InstT>)
  1134. static auto ResolveAsDeduplicated(ImportRefResolver& resolver, InstT inst)
  1135. -> ResolveResult {
  1136. CARBON_CHECK(!resolver.HasNewWork());
  1137. // AddImportedConstant produces an unattached constant, so its type must
  1138. // be unattached as well.
  1139. inst.type_id =
  1140. resolver.local_context().types().GetUnattachedType(inst.type_id);
  1141. auto const_id = AddImportedConstant(resolver.local_context(), inst);
  1142. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1143. return ResolveResult::Done(const_id);
  1144. }
  1145. // Adds `inst` to the local context as a unique constant and returns a
  1146. // successful `ResolveResult`. `import_inst_id` is the corresponding inst ID in
  1147. // the local context. Requires that there is no new work.
  1148. //
  1149. // This implements phases 2 and 3 of resolving the inst (as described above) for
  1150. // the common case where those phases are combined. Cases where that isn't
  1151. // applicable should instead use `AddPlaceholderImportedInst` and
  1152. // `ReplacePlaceholderImportedInst`.
  1153. //
  1154. // This should only be used for instructions that represent declarations, or
  1155. // other instructions with `constant_kind == InstConstantKind::Unique`, because
  1156. // it does not perform deduplication.
  1157. template <typename InstT>
  1158. requires HasUniqueConstantKind<InstT>
  1159. static auto ResolveAsUnique(ImportRefResolver& resolver,
  1160. SemIR::InstId import_inst_id, InstT inst)
  1161. -> ResolveResult {
  1162. CARBON_CHECK(!resolver.HasNewWork());
  1163. auto inst_id = AddPlaceholderImportedInst(resolver, import_inst_id, inst);
  1164. auto const_id = SetConstantValue(resolver.local_context(), inst_id, inst);
  1165. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1166. return ResolveResult::Done(const_id, inst_id);
  1167. }
  1168. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1169. SemIR::AdaptDecl inst,
  1170. SemIR::InstId import_inst_id) -> ResolveResult {
  1171. auto adapted_type_const_id = GetLocalConstantId(
  1172. resolver,
  1173. resolver.import_constant_values().GetAttached(inst.adapted_type_inst_id));
  1174. if (resolver.HasNewWork()) {
  1175. return ResolveResult::Retry();
  1176. }
  1177. auto adapted_type_inst_id = resolver.local_ir().types().GetAsTypeInstId(
  1178. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId,
  1179. inst.adapted_type_inst_id, adapted_type_const_id));
  1180. // Create a corresponding instruction to represent the declaration.
  1181. return ResolveAsUnique<SemIR::AdaptDecl>(
  1182. resolver, import_inst_id, {.adapted_type_inst_id = adapted_type_inst_id});
  1183. }
  1184. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1185. SemIR::AddrPattern inst,
  1186. SemIR::InstId import_inst_id) -> ResolveResult {
  1187. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1188. auto inner_id = GetLocalConstantInstId(resolver, inst.inner_id);
  1189. if (resolver.HasNewWork()) {
  1190. return ResolveResult::Retry();
  1191. }
  1192. return ResolveAsUnique<SemIR::AddrPattern>(
  1193. resolver, import_inst_id,
  1194. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1195. type_const_id),
  1196. .inner_id = inner_id});
  1197. }
  1198. template <typename ParamPatternT>
  1199. requires SemIR::Internal::HasInstCategory<SemIR::AnyParamPattern,
  1200. ParamPatternT>
  1201. static auto TryResolveTypedInst(ImportRefResolver& resolver, ParamPatternT inst,
  1202. SemIR::InstId import_inst_id) -> ResolveResult {
  1203. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1204. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  1205. if (resolver.HasNewWork()) {
  1206. return ResolveResult::Retry();
  1207. }
  1208. return ResolveAsUnique<ParamPatternT>(
  1209. resolver, import_inst_id,
  1210. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1211. type_const_id),
  1212. .subpattern_id = subpattern_id,
  1213. .index = inst.index});
  1214. }
  1215. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1216. SemIR::ArrayType inst) -> ResolveResult {
  1217. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1218. auto element_type_inst_id =
  1219. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  1220. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1221. if (resolver.HasNewWork()) {
  1222. return ResolveResult::Retry();
  1223. }
  1224. return ResolveAsDeduplicated<SemIR::ArrayType>(
  1225. resolver, {.type_id = SemIR::TypeType::TypeId,
  1226. .bound_id = bound_id,
  1227. .element_type_inst_id = element_type_inst_id});
  1228. }
  1229. static auto MakeAssociatedConstant(
  1230. ImportContext& context, const SemIR::AssociatedConstant& import_assoc_const,
  1231. SemIR::TypeId type_id)
  1232. -> std::pair<SemIR::AssociatedConstantId, SemIR::ConstantId> {
  1233. SemIR::AssociatedConstantDecl assoc_const_decl = {
  1234. .type_id = type_id,
  1235. .assoc_const_id = SemIR::AssociatedConstantId::None,
  1236. .decl_block_id = SemIR::InstBlockId::Empty};
  1237. auto assoc_const_decl_id = AddPlaceholderImportedInst(
  1238. context, import_assoc_const.decl_id, assoc_const_decl);
  1239. assoc_const_decl.assoc_const_id = context.local_associated_constants().Add({
  1240. .name_id = GetLocalNameId(context, import_assoc_const.name_id),
  1241. .parent_scope_id = SemIR::NameScopeId::None,
  1242. .decl_id = assoc_const_decl_id,
  1243. .generic_id = MakeIncompleteGeneric(context, assoc_const_decl_id,
  1244. import_assoc_const.generic_id),
  1245. .default_value_id =
  1246. import_assoc_const.default_value_id.has_value()
  1247. ? AddImportRef(context, import_assoc_const.default_value_id)
  1248. : SemIR::InstId::None,
  1249. });
  1250. // Write the associated constant ID into the AssociatedConstantDecl.
  1251. auto const_id = ReplacePlaceholderImportedInst(context, assoc_const_decl_id,
  1252. assoc_const_decl);
  1253. return {assoc_const_decl.assoc_const_id, const_id};
  1254. }
  1255. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1256. SemIR::AssociatedConstantDecl inst,
  1257. SemIR::ConstantId const_id) -> ResolveResult {
  1258. const auto& import_assoc_const =
  1259. resolver.import_associated_constants().Get(inst.assoc_const_id);
  1260. SemIR::AssociatedConstantId assoc_const_id =
  1261. SemIR::AssociatedConstantId::None;
  1262. if (!const_id.has_value()) {
  1263. // In the first phase, import the type of the associated constant.
  1264. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1265. if (resolver.HasNewWork()) {
  1266. return ResolveResult::Retry();
  1267. }
  1268. // In the second phase, create the associated constant and its declaration.
  1269. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1270. type_const_id);
  1271. std::tie(assoc_const_id, const_id) =
  1272. MakeAssociatedConstant(resolver, import_assoc_const, type_id);
  1273. } else {
  1274. // In the third phase, compute the associated constant ID from the constant
  1275. // value of the declaration.
  1276. assoc_const_id =
  1277. resolver.local_insts()
  1278. .GetAs<SemIR::AssociatedConstantDecl>(
  1279. resolver.local_constant_values().GetInstId(const_id))
  1280. .assoc_const_id;
  1281. }
  1282. // Load the values to populate the entity with.
  1283. auto parent_scope_id =
  1284. GetLocalNameScopeId(resolver, import_assoc_const.parent_scope_id);
  1285. auto generic_data =
  1286. GetLocalGenericData(resolver, import_assoc_const.generic_id);
  1287. auto& new_assoc_const =
  1288. resolver.local_associated_constants().Get(assoc_const_id);
  1289. if (resolver.HasNewWork()) {
  1290. return ResolveResult::Retry(const_id, new_assoc_const.decl_id);
  1291. }
  1292. // Populate the entity.
  1293. new_assoc_const.parent_scope_id = parent_scope_id;
  1294. SetGenericData(resolver, import_assoc_const.generic_id,
  1295. new_assoc_const.generic_id, generic_data);
  1296. return ResolveResult::Done(const_id, new_assoc_const.decl_id);
  1297. }
  1298. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1299. SemIR::AssociatedEntity inst) -> ResolveResult {
  1300. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1301. if (resolver.HasNewWork()) {
  1302. return ResolveResult::Retry();
  1303. }
  1304. // Add a lazy reference to the target declaration.
  1305. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1306. return ResolveAsDeduplicated<SemIR::AssociatedEntity>(
  1307. resolver,
  1308. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1309. type_const_id),
  1310. .index = inst.index,
  1311. .decl_id = decl_id});
  1312. }
  1313. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1314. SemIR::AssociatedEntityType inst)
  1315. -> ResolveResult {
  1316. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1317. auto data =
  1318. GetLocalSpecificInterfaceData(resolver, inst.GetSpecificInterface());
  1319. if (resolver.HasNewWork()) {
  1320. return ResolveResult::Retry();
  1321. }
  1322. auto specific_interface =
  1323. GetLocalSpecificInterface(resolver, inst.GetSpecificInterface(), data);
  1324. return ResolveAsDeduplicated<SemIR::AssociatedEntityType>(
  1325. resolver, {.type_id = SemIR::TypeType::TypeId,
  1326. .interface_id = specific_interface.interface_id,
  1327. .interface_specific_id = specific_interface.specific_id});
  1328. }
  1329. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1330. SemIR::BaseDecl inst,
  1331. SemIR::InstId import_inst_id) -> ResolveResult {
  1332. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1333. auto base_type_const_id = GetLocalConstantId(
  1334. resolver,
  1335. resolver.import_constant_values().GetAttached(inst.base_type_inst_id));
  1336. if (resolver.HasNewWork()) {
  1337. return ResolveResult::Retry();
  1338. }
  1339. auto base_type_inst_id = resolver.local_ir().types().GetAsTypeInstId(
  1340. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId,
  1341. inst.base_type_inst_id, base_type_const_id));
  1342. // Create a corresponding instruction to represent the declaration.
  1343. return ResolveAsUnique<SemIR::BaseDecl>(
  1344. resolver, import_inst_id,
  1345. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1346. type_const_id),
  1347. .base_type_inst_id = base_type_inst_id,
  1348. .index = inst.index});
  1349. }
  1350. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1351. SemIR::BindAlias inst) -> ResolveResult {
  1352. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1353. return RetryOrDone(resolver, value_id);
  1354. }
  1355. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1356. SemIR::BindSymbolicName inst) -> ResolveResult {
  1357. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1358. if (resolver.HasNewWork()) {
  1359. return ResolveResult::Retry();
  1360. }
  1361. const auto& import_entity_name =
  1362. resolver.import_entity_names().Get(inst.entity_name_id);
  1363. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1364. auto entity_name_id = resolver.local_entity_names().AddSymbolicBindingName(
  1365. name_id, SemIR::NameScopeId::None, import_entity_name.bind_index(),
  1366. import_entity_name.is_template);
  1367. return ResolveAsDeduplicated<SemIR::BindSymbolicName>(
  1368. resolver,
  1369. {.type_id =
  1370. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1371. .entity_name_id = entity_name_id,
  1372. .value_id = SemIR::InstId::None});
  1373. }
  1374. template <typename BindingPatternT>
  1375. requires SemIR::Internal::HasInstCategory<SemIR::AnyBindingPattern,
  1376. BindingPatternT>
  1377. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1378. BindingPatternT inst,
  1379. SemIR::InstId import_inst_id) -> ResolveResult {
  1380. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1381. const auto& import_entity_name =
  1382. resolver.import_entity_names().Get(inst.entity_name_id);
  1383. auto parent_scope_id =
  1384. GetLocalNameScopeId(resolver, import_entity_name.parent_scope_id);
  1385. if (resolver.HasNewWork()) {
  1386. return ResolveResult::Retry();
  1387. }
  1388. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1389. auto entity_name_id = resolver.local_entity_names().Add(
  1390. {.name_id = name_id,
  1391. .parent_scope_id = parent_scope_id,
  1392. .bind_index_value = import_entity_name.bind_index().index,
  1393. .is_template = import_entity_name.is_template});
  1394. return ResolveAsUnique<BindingPatternT>(
  1395. resolver, import_inst_id,
  1396. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1397. type_const_id),
  1398. .entity_name_id = entity_name_id});
  1399. }
  1400. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1401. SemIR::BoolLiteral inst) -> ResolveResult {
  1402. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1403. SemIR::BoolType::TypeInstId);
  1404. CARBON_CHECK(!resolver.HasNewWork());
  1405. return ResolveAsDeduplicated<SemIR::BoolLiteral>(
  1406. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1407. SemIR::BoolType::TypeInstId),
  1408. .value = inst.value});
  1409. }
  1410. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1411. SemIR::BoundMethod inst) -> ResolveResult {
  1412. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1413. SemIR::BoundMethodType::TypeInstId);
  1414. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1415. auto function_decl_id =
  1416. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1417. if (resolver.HasNewWork()) {
  1418. return ResolveResult::Retry();
  1419. }
  1420. return ResolveAsDeduplicated<SemIR::BoundMethod>(
  1421. resolver,
  1422. {.type_id = GetSingletonType(resolver.local_context(),
  1423. SemIR::BoundMethodType::TypeInstId),
  1424. .object_id = object_id,
  1425. .function_decl_id = function_decl_id});
  1426. }
  1427. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1428. -> ResolveResult {
  1429. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1430. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1431. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1432. if (resolver.HasNewWork()) {
  1433. return ResolveResult::Retry();
  1434. }
  1435. return ResolveAsDeduplicated<SemIR::Call>(
  1436. resolver,
  1437. {.type_id =
  1438. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1439. .callee_id = callee_id,
  1440. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1441. }
  1442. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1443. SemIR::CharLiteralValue inst) -> ResolveResult {
  1444. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1445. SemIR::CharLiteralType::TypeInstId);
  1446. CARBON_CHECK(!resolver.HasNewWork());
  1447. return ResolveAsDeduplicated<SemIR::CharLiteralValue>(
  1448. resolver,
  1449. {.type_id = GetSingletonType(resolver.local_context(),
  1450. SemIR::CharLiteralType::TypeInstId),
  1451. .value = inst.value});
  1452. }
  1453. static auto AddPlaceholderNameScope(ImportContext& context)
  1454. -> SemIR::NameScopeId {
  1455. return context.local_name_scopes().Add(
  1456. SemIR::InstId::None, SemIR::NameId::None, SemIR::NameScopeId::None);
  1457. }
  1458. // Makes an incomplete class. This is necessary even with classes with a
  1459. // complete declaration, because things such as `Self` may refer back to the
  1460. // type.
  1461. static auto MakeIncompleteClass(ImportContext& context,
  1462. const SemIR::Class& import_class,
  1463. SemIR::SpecificId enclosing_specific_id)
  1464. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1465. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::TypeId,
  1466. .class_id = SemIR::ClassId::None,
  1467. .decl_block_id = SemIR::InstBlockId::Empty};
  1468. auto class_decl_id = AddPlaceholderImportedInst(
  1469. context, import_class.latest_decl_id(), class_decl);
  1470. // Regardless of whether ClassDecl is a complete type, we first need an
  1471. // incomplete type so that any references have something to point at.
  1472. class_decl.class_id = context.local_classes().Add(
  1473. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1474. {.self_type_id = SemIR::TypeId::None,
  1475. .inheritance_kind = import_class.inheritance_kind,
  1476. .is_dynamic = import_class.is_dynamic,
  1477. .scope_id = import_class.is_complete()
  1478. ? AddPlaceholderNameScope(context)
  1479. : SemIR::NameScopeId::None}});
  1480. if (import_class.has_parameters()) {
  1481. class_decl.type_id = GetGenericClassType(
  1482. context.local_context(), class_decl.class_id, enclosing_specific_id);
  1483. }
  1484. // Write the class ID into the ClassDecl.
  1485. auto self_const_id =
  1486. ReplacePlaceholderImportedInst(context, class_decl_id, class_decl);
  1487. return {class_decl.class_id, self_const_id};
  1488. }
  1489. static auto InitializeNameScopeAndImportRefs(
  1490. ImportContext& context, const SemIR::NameScope& import_scope,
  1491. SemIR::NameScope& new_scope, SemIR::InstId decl_id, SemIR::NameId name_id,
  1492. SemIR::NameScopeId parent_scope_id) {
  1493. new_scope.Set(decl_id, name_id, parent_scope_id);
  1494. AddNameScopeImportRefs(context, import_scope, new_scope);
  1495. }
  1496. // Fills out the class definition for an incomplete class.
  1497. static auto AddClassDefinition(ImportContext& context,
  1498. const SemIR::Class& import_class,
  1499. SemIR::Class& new_class,
  1500. SemIR::InstId complete_type_witness_id,
  1501. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1502. SemIR::InstId vtable_decl_id) -> void {
  1503. new_class.definition_id = new_class.first_owning_decl_id;
  1504. new_class.complete_type_witness_id = complete_type_witness_id;
  1505. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1506. const auto& import_scope =
  1507. context.import_name_scopes().Get(import_class.scope_id);
  1508. // Push a block so that we can add scoped instructions to it.
  1509. context.local_context().inst_block_stack().Push();
  1510. InitializeNameScopeAndImportRefs(
  1511. context, import_scope, new_scope, new_class.first_owning_decl_id,
  1512. SemIR::NameId::None, new_class.parent_scope_id);
  1513. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1514. if (import_class.base_id.has_value()) {
  1515. new_class.base_id = base_id;
  1516. }
  1517. if (import_class.adapt_id.has_value()) {
  1518. new_class.adapt_id = adapt_id;
  1519. }
  1520. if (import_class.vtable_decl_id.has_value()) {
  1521. new_class.vtable_decl_id = vtable_decl_id;
  1522. }
  1523. }
  1524. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1525. SemIR::ClassDecl inst,
  1526. SemIR::ConstantId class_const_id)
  1527. -> ResolveResult {
  1528. // TODO: The handling of interfaces repeats a lot with the handling of
  1529. // classes, and will likely also be repeated for named constraints and
  1530. // choice types. Factor out some of this functionality.
  1531. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1532. SemIR::ClassId class_id = SemIR::ClassId::None;
  1533. if (!class_const_id.has_value()) {
  1534. auto import_specific_id = SemIR::SpecificId::None;
  1535. if (auto import_generic_class_type =
  1536. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1537. inst.type_id)) {
  1538. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1539. }
  1540. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1541. if (resolver.HasNewWork()) {
  1542. // This is the end of the first phase. Don't make a new class yet if
  1543. // we already have new work.
  1544. return ResolveResult::Retry();
  1545. }
  1546. // On the second phase, create a forward declaration of the class for any
  1547. // recursive references.
  1548. auto enclosing_specific_id =
  1549. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1550. std::tie(class_id, class_const_id) =
  1551. MakeIncompleteClass(resolver, import_class, enclosing_specific_id);
  1552. } else {
  1553. // On the third phase, compute the class ID from the constant
  1554. // value of the declaration.
  1555. auto class_const_inst = resolver.local_insts().Get(
  1556. resolver.local_constant_values().GetInstId(class_const_id));
  1557. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1558. class_id = class_type->class_id;
  1559. } else {
  1560. auto generic_class_type =
  1561. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1562. class_const_inst.type_id());
  1563. class_id = generic_class_type.class_id;
  1564. }
  1565. }
  1566. // Load constants for the definition.
  1567. auto parent_scope_id =
  1568. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1569. auto implicit_param_patterns = GetLocalInstBlockContents(
  1570. resolver, import_class.implicit_param_patterns_id);
  1571. auto param_patterns =
  1572. GetLocalInstBlockContents(resolver, import_class.param_patterns_id);
  1573. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1574. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1575. auto complete_type_witness_const_id =
  1576. import_class.complete_type_witness_id.has_value()
  1577. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1578. : SemIR::ConstantId::None;
  1579. auto base_id = import_class.base_id.has_value()
  1580. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1581. : SemIR::InstId::None;
  1582. auto adapt_id = import_class.adapt_id.has_value()
  1583. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1584. : SemIR::InstId::None;
  1585. auto vtable_decl_id =
  1586. import_class.vtable_decl_id.has_value()
  1587. ? AddImportRef(resolver, import_class.vtable_decl_id)
  1588. : SemIR::InstId::None;
  1589. auto& new_class = resolver.local_classes().Get(class_id);
  1590. if (resolver.HasNewWork()) {
  1591. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1592. }
  1593. new_class.parent_scope_id = parent_scope_id;
  1594. new_class.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1595. resolver, import_class.implicit_param_patterns_id,
  1596. implicit_param_patterns);
  1597. new_class.param_patterns_id = GetLocalCanonicalInstBlockId(
  1598. resolver, import_class.param_patterns_id, param_patterns);
  1599. SetGenericData(resolver, import_class.generic_id, new_class.generic_id,
  1600. generic_data);
  1601. new_class.self_type_id =
  1602. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1603. self_const_id);
  1604. if (import_class.is_complete()) {
  1605. auto complete_type_witness_id = AddLoadedImportRef(
  1606. resolver,
  1607. GetSingletonType(resolver.local_context(),
  1608. SemIR::WitnessType::TypeInstId),
  1609. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1610. AddClassDefinition(resolver, import_class, new_class,
  1611. complete_type_witness_id, base_id, adapt_id,
  1612. vtable_decl_id);
  1613. }
  1614. return ResolveResult::Done(class_const_id, new_class.first_decl_id());
  1615. }
  1616. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1617. SemIR::ClassType inst) -> ResolveResult {
  1618. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1619. auto class_const_id = GetLocalConstantId(
  1620. resolver,
  1621. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1622. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1623. if (resolver.HasNewWork()) {
  1624. return ResolveResult::Retry();
  1625. }
  1626. // Find the corresponding class type. For a non-generic class, this is the
  1627. // type of the class declaration. For a generic class, build a class type
  1628. // referencing this specialization of the generic class.
  1629. auto class_const_inst = resolver.local_insts().Get(
  1630. resolver.local_constant_values().GetInstId(class_const_id));
  1631. if (class_const_inst.Is<SemIR::ClassType>()) {
  1632. return ResolveResult::Done(class_const_id);
  1633. } else {
  1634. auto generic_class_type =
  1635. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1636. class_const_inst.type_id());
  1637. auto specific_id =
  1638. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1639. return ResolveAsDeduplicated<SemIR::ClassType>(
  1640. resolver, {.type_id = SemIR::TypeType::TypeId,
  1641. .class_id = generic_class_type.class_id,
  1642. .specific_id = specific_id});
  1643. }
  1644. }
  1645. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1646. SemIR::CompleteTypeWitness inst)
  1647. -> ResolveResult {
  1648. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1649. SemIR::WitnessType::TypeInstId);
  1650. auto object_repr_type_inst_id =
  1651. GetLocalTypeInstId(resolver, inst.object_repr_type_inst_id);
  1652. if (resolver.HasNewWork()) {
  1653. return ResolveResult::Retry();
  1654. }
  1655. return ResolveAsDeduplicated<SemIR::CompleteTypeWitness>(
  1656. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1657. SemIR::WitnessType::TypeInstId),
  1658. .object_repr_type_inst_id = object_repr_type_inst_id});
  1659. }
  1660. template <typename InstT>
  1661. requires SemIR::Internal::HasInstCategory<SemIR::AnyQualifiedType, InstT>
  1662. static auto TryResolveTypedInst(ImportRefResolver& resolver, InstT inst)
  1663. -> ResolveResult {
  1664. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1665. auto inner_id = GetLocalTypeInstId(resolver, inst.inner_id);
  1666. if (resolver.HasNewWork()) {
  1667. return ResolveResult::Retry();
  1668. }
  1669. return ResolveAsDeduplicated<InstT>(
  1670. resolver, {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_id});
  1671. }
  1672. static auto HandleUnsupportedCppOverloadSet(ImportRefResolver& resolver,
  1673. SemIR::CppOverloadSetId id) {
  1674. // Supporting C++ overload resolution of imported functions is a large task,
  1675. // which might require serializing and deserializing AST for using decl ids,
  1676. // using modules and/or linking ASTs.
  1677. resolver.local_context().TODO(
  1678. SemIR::LocId::None,
  1679. llvm::formatv(
  1680. "Unsupported: Importing C++ function `{0}` indirectly",
  1681. resolver.import_ir().names().GetAsStringIfIdentifier(
  1682. resolver.import_ir().cpp_overload_sets().Get(id).name_id)));
  1683. return ResolveResult::Done(SemIR::ErrorInst::ConstantId,
  1684. SemIR::ErrorInst::InstId);
  1685. }
  1686. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1687. SemIR::CppOverloadSetType inst)
  1688. -> ResolveResult {
  1689. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1690. }
  1691. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1692. SemIR::CppOverloadSetValue inst)
  1693. -> ResolveResult {
  1694. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1695. }
  1696. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1697. SemIR::ExportDecl inst) -> ResolveResult {
  1698. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1699. return RetryOrDone(resolver, value_id);
  1700. }
  1701. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1702. SemIR::FieldDecl inst,
  1703. SemIR::InstId import_inst_id) -> ResolveResult {
  1704. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1705. if (resolver.HasNewWork()) {
  1706. return ResolveResult::Retry();
  1707. }
  1708. return ResolveAsUnique<SemIR::FieldDecl>(
  1709. resolver, import_inst_id,
  1710. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1711. const_id),
  1712. .name_id = GetLocalNameId(resolver, inst.name_id),
  1713. .index = inst.index});
  1714. }
  1715. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1716. SemIR::FloatLiteralValue inst)
  1717. -> ResolveResult {
  1718. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1719. SemIR::FloatLiteralType::TypeInstId);
  1720. CARBON_CHECK(!resolver.HasNewWork());
  1721. auto real_id = resolver.local_ir().reals().Add(
  1722. resolver.import_ir().reals().Get(inst.real_id));
  1723. return ResolveAsDeduplicated<SemIR::FloatLiteralValue>(
  1724. resolver,
  1725. {.type_id = GetSingletonType(resolver.local_context(),
  1726. SemIR::FloatLiteralType::TypeInstId),
  1727. .real_id = real_id});
  1728. }
  1729. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1730. SemIR::FloatType inst) -> ResolveResult {
  1731. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1732. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  1733. if (resolver.HasNewWork()) {
  1734. return ResolveResult::Retry();
  1735. }
  1736. return ResolveAsDeduplicated<SemIR::FloatType>(
  1737. resolver, {.type_id = SemIR::TypeType::TypeId,
  1738. .bit_width_id = bit_width_id,
  1739. .float_kind = inst.float_kind});
  1740. }
  1741. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1742. SemIR::FloatValue inst) -> ResolveResult {
  1743. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1744. if (resolver.HasNewWork()) {
  1745. return ResolveResult::Retry();
  1746. }
  1747. auto float_id = resolver.local_ir().floats().Add(
  1748. resolver.import_ir().floats().Get(inst.float_id));
  1749. return ResolveAsDeduplicated<SemIR::FloatValue>(
  1750. resolver,
  1751. {.type_id =
  1752. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1753. .float_id = float_id});
  1754. }
  1755. // Make a declaration of a function. This is done as a separate step from
  1756. // importing the function declaration in order to resolve cycles.
  1757. static auto MakeFunctionDecl(ImportContext& context,
  1758. const SemIR::Function& import_function,
  1759. SemIR::SpecificId specific_id)
  1760. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1761. SemIR::FunctionDecl function_decl = {
  1762. .type_id = SemIR::TypeId::None,
  1763. .function_id = SemIR::FunctionId::None,
  1764. .decl_block_id = SemIR::InstBlockId::Empty};
  1765. auto function_decl_id = AddPlaceholderImportedInst(
  1766. context, import_function.first_decl_id(), function_decl);
  1767. // Start with an incomplete function.
  1768. function_decl.function_id = context.local_functions().Add(
  1769. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  1770. {.call_params_id = SemIR::InstBlockId::None,
  1771. .return_slot_pattern_id = SemIR::InstId::None,
  1772. .virtual_modifier = import_function.virtual_modifier,
  1773. .virtual_index = import_function.virtual_index}});
  1774. // Directly add the function type constant. Don't use `GetFunctionType`
  1775. // because that will evaluate the function type, which we can't do if the
  1776. // specific's value block is still pending.
  1777. auto type_const_id = AddImportedConstant(
  1778. context.local_context(),
  1779. SemIR::FunctionType{.type_id = SemIR::TypeType::TypeId,
  1780. .function_id = function_decl.function_id,
  1781. .specific_id = specific_id});
  1782. function_decl.type_id =
  1783. context.local_types().GetTypeIdForTypeConstantId(type_const_id);
  1784. // Write the function ID and type into the FunctionDecl.
  1785. auto function_const_id =
  1786. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  1787. return {function_decl.function_id, function_const_id};
  1788. }
  1789. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1790. SemIR::FunctionDecl inst,
  1791. SemIR::ConstantId function_const_id)
  1792. -> ResolveResult {
  1793. const auto& import_function =
  1794. resolver.import_functions().Get(inst.function_id);
  1795. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  1796. if (!function_const_id.has_value()) {
  1797. auto import_specific_id = resolver.import_types()
  1798. .GetAs<SemIR::FunctionType>(inst.type_id)
  1799. .specific_id;
  1800. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1801. if (resolver.HasNewWork()) {
  1802. // This is the end of the first phase. Don't make a new function yet if
  1803. // we already have new work.
  1804. return ResolveResult::Retry();
  1805. }
  1806. // On the second phase, create a forward declaration of the interface.
  1807. auto specific_id =
  1808. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1809. std::tie(function_id, function_const_id) =
  1810. MakeFunctionDecl(resolver, import_function, specific_id);
  1811. } else {
  1812. // On the third phase, compute the function ID from the constant value of
  1813. // the declaration.
  1814. auto function_const_inst = resolver.local_insts().Get(
  1815. resolver.local_constant_values().GetInstId(function_const_id));
  1816. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1817. function_const_inst.type_id());
  1818. function_id = function_type.function_id;
  1819. }
  1820. auto return_type_const_id = SemIR::ConstantId::None;
  1821. if (import_function.return_slot_pattern_id.has_value()) {
  1822. return_type_const_id = GetLocalConstantId(
  1823. resolver, resolver.import_insts().GetAttachedType(
  1824. import_function.return_slot_pattern_id));
  1825. }
  1826. auto parent_scope_id =
  1827. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1828. auto implicit_param_patterns = GetLocalInstBlockContents(
  1829. resolver, import_function.implicit_param_patterns_id);
  1830. auto param_patterns =
  1831. GetLocalInstBlockContents(resolver, import_function.param_patterns_id);
  1832. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1833. auto self_param_id =
  1834. GetLocalConstantInstId(resolver, import_function.self_param_id);
  1835. auto return_slot_pattern_id =
  1836. GetLocalConstantInstId(resolver, import_function.return_slot_pattern_id);
  1837. auto& new_function = resolver.local_functions().Get(function_id);
  1838. if (resolver.HasNewWork()) {
  1839. return ResolveResult::Retry(function_const_id,
  1840. new_function.first_decl_id());
  1841. }
  1842. // Add the function declaration.
  1843. new_function.parent_scope_id = parent_scope_id;
  1844. new_function.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1845. resolver, import_function.implicit_param_patterns_id,
  1846. implicit_param_patterns);
  1847. new_function.self_param_id = self_param_id;
  1848. new_function.param_patterns_id = GetLocalCanonicalInstBlockId(
  1849. resolver, import_function.param_patterns_id, param_patterns);
  1850. new_function.return_slot_pattern_id = return_slot_pattern_id;
  1851. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1852. generic_data);
  1853. if (import_function.definition_id.has_value()) {
  1854. new_function.definition_id = new_function.first_owning_decl_id;
  1855. }
  1856. switch (import_function.special_function_kind) {
  1857. case SemIR::Function::SpecialFunctionKind::None: {
  1858. break;
  1859. }
  1860. case SemIR::Function::SpecialFunctionKind::Builtin: {
  1861. new_function.SetBuiltinFunction(import_function.builtin_function_kind());
  1862. break;
  1863. }
  1864. case SemIR::Function::SpecialFunctionKind::Thunk: {
  1865. auto entity_name_id = resolver.local_entity_names().AddCanonical(
  1866. {.name_id = new_function.name_id,
  1867. .parent_scope_id = new_function.parent_scope_id});
  1868. new_function.SetThunk(AddImportRef(
  1869. resolver, import_function.thunk_decl_id(), entity_name_id));
  1870. break;
  1871. }
  1872. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  1873. resolver.local_context().TODO(SemIR::LocId::None,
  1874. "Unsupported: Importing C++ functions that "
  1875. "require thunks indirectly");
  1876. }
  1877. }
  1878. return ResolveResult::Done(function_const_id, new_function.first_decl_id());
  1879. }
  1880. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1881. SemIR::VtableDecl inst) -> ResolveResult {
  1882. const auto& import_vtable = resolver.import_vtables().Get(inst.vtable_id);
  1883. auto class_const_id =
  1884. GetLocalConstantId(resolver, resolver.import_classes()
  1885. .Get(import_vtable.class_id)
  1886. .first_owning_decl_id);
  1887. auto class_const_inst = resolver.local_insts().Get(
  1888. resolver.local_constant_values().GetInstId(class_const_id));
  1889. // TODO: Ensure the vtable is only imported once, in eg: if there's distinct
  1890. // vtable constants (imported from multiple libraries using the vtable) that
  1891. // refer to the same vtable, the vtable should still be singular.
  1892. auto virtual_functions =
  1893. resolver.import_inst_blocks().Get(import_vtable.virtual_functions_id);
  1894. llvm::SmallVector<SemIR::InstId> lazy_virtual_functions;
  1895. lazy_virtual_functions.reserve(virtual_functions.size());
  1896. for (auto vtable_entry_id : virtual_functions) {
  1897. auto local_attached_constant_id = GetLocalConstantId(
  1898. resolver,
  1899. resolver.import_constant_values().GetAttached(vtable_entry_id));
  1900. lazy_virtual_functions.push_back(
  1901. resolver.local_constant_values().GetInstIdIfValid(
  1902. local_attached_constant_id));
  1903. }
  1904. if (resolver.HasNewWork()) {
  1905. return ResolveResult::Retry();
  1906. }
  1907. for (auto [import_vtable_entry_inst_id, local_vtable_entry_inst_id] :
  1908. llvm::zip(virtual_functions, lazy_virtual_functions)) {
  1909. // Use LoadedImportRef for imported symbolic constant vtable entries so they
  1910. // can carry attached constants necessary for applying specifics to these
  1911. // constants when they are used.
  1912. auto local_attached_constant_id =
  1913. resolver.local_constant_values().GetAttached(
  1914. local_vtable_entry_inst_id);
  1915. if (local_attached_constant_id.is_symbolic()) {
  1916. local_vtable_entry_inst_id = AddLoadedImportRef(
  1917. resolver,
  1918. GetSingletonType(resolver.local_context(),
  1919. SemIR::SpecificFunctionType::TypeInstId),
  1920. import_vtable_entry_inst_id, local_attached_constant_id);
  1921. }
  1922. }
  1923. auto class_id = SemIR::ClassId::None;
  1924. if (class_const_inst.Is<SemIR::ClassType>()) {
  1925. class_id = class_const_inst.As<SemIR::ClassType>().class_id;
  1926. } else {
  1927. auto generic_class_type =
  1928. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1929. class_const_inst.type_id());
  1930. class_id = generic_class_type.class_id;
  1931. }
  1932. auto new_vtable_id = resolver.local_vtables().Add(
  1933. {{.class_id = class_id,
  1934. .virtual_functions_id =
  1935. resolver.local_inst_blocks().Add(lazy_virtual_functions)}});
  1936. return ResolveAsDeduplicated<SemIR::VtableDecl>(
  1937. resolver, {.type_id = GetPointerType(resolver.local_context(),
  1938. SemIR::VtableType::TypeInstId),
  1939. .vtable_id = new_vtable_id});
  1940. }
  1941. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1942. SemIR::VtablePtr inst) -> ResolveResult {
  1943. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1944. auto vtable_const_id = GetLocalConstantId(
  1945. resolver, resolver.import_classes()
  1946. .Get(resolver.import_vtables().Get(inst.vtable_id).class_id)
  1947. .vtable_decl_id);
  1948. auto vtable_const_inst = resolver.local_insts().Get(
  1949. resolver.local_constant_values().GetInstId(vtable_const_id));
  1950. if (resolver.HasNewWork()) {
  1951. return ResolveResult::Retry();
  1952. }
  1953. return ResolveAsDeduplicated<SemIR::VtablePtr>(
  1954. resolver,
  1955. {.type_id = GetPointerType(resolver.local_context(),
  1956. SemIR::VtableType::TypeInstId),
  1957. .vtable_id = vtable_const_inst.As<SemIR::VtableDecl>().vtable_id,
  1958. .specific_id =
  1959. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data)});
  1960. }
  1961. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1962. SemIR::FunctionType inst) -> ResolveResult {
  1963. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1964. auto fn_val_id = GetLocalConstantInstId(
  1965. resolver,
  1966. resolver.import_functions().Get(inst.function_id).first_decl_id());
  1967. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1968. if (resolver.HasNewWork()) {
  1969. return ResolveResult::Retry();
  1970. }
  1971. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  1972. return ResolveAsDeduplicated<SemIR::FunctionType>(
  1973. resolver, {.type_id = SemIR::TypeType::TypeId,
  1974. .function_id = resolver.local_types()
  1975. .GetAs<SemIR::FunctionType>(fn_type_id)
  1976. .function_id,
  1977. .specific_id = GetOrAddLocalSpecific(
  1978. resolver, inst.specific_id, specific_data)});
  1979. }
  1980. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1981. SemIR::FunctionTypeWithSelfType inst)
  1982. -> ResolveResult {
  1983. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1984. auto interface_function_type_id =
  1985. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  1986. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  1987. if (resolver.HasNewWork()) {
  1988. return ResolveResult::Retry();
  1989. }
  1990. return ResolveAsDeduplicated<SemIR::FunctionTypeWithSelfType>(
  1991. resolver, {.type_id = SemIR::TypeType::TypeId,
  1992. .interface_function_type_id = interface_function_type_id,
  1993. .self_id = self_id});
  1994. }
  1995. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1996. SemIR::GenericClassType inst) -> ResolveResult {
  1997. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1998. auto class_val_id = GetLocalConstantInstId(
  1999. resolver,
  2000. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  2001. if (resolver.HasNewWork()) {
  2002. return ResolveResult::Retry();
  2003. }
  2004. auto class_val = resolver.local_insts().Get(class_val_id);
  2005. CARBON_CHECK(
  2006. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  2007. return ResolveResult::Done(
  2008. resolver.local_types().GetConstantId(class_val.type_id()));
  2009. }
  2010. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2011. SemIR::GenericInterfaceType inst)
  2012. -> ResolveResult {
  2013. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2014. auto interface_val_id = GetLocalConstantInstId(
  2015. resolver,
  2016. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2017. if (resolver.HasNewWork()) {
  2018. return ResolveResult::Retry();
  2019. }
  2020. auto interface_val = resolver.local_insts().Get(interface_val_id);
  2021. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  2022. interface_val.type_id()));
  2023. return ResolveResult::Done(
  2024. resolver.local_types().GetConstantId(interface_val.type_id()));
  2025. }
  2026. // Make a declaration of an impl. This is done as a separate step from
  2027. // importing the impl definition in order to resolve cycles.
  2028. static auto MakeImplDeclaration(ImportContext& context,
  2029. const SemIR::Impl& import_impl,
  2030. SemIR::InstId witness_id)
  2031. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  2032. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  2033. .decl_block_id = SemIR::InstBlockId::Empty};
  2034. auto impl_decl_id = AddPlaceholderImportedInst(
  2035. context, import_impl.latest_decl_id(), impl_decl);
  2036. impl_decl.impl_id = context.local_impls().Add(
  2037. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  2038. {.self_id = SemIR::TypeInstId::None,
  2039. .constraint_id = SemIR::TypeInstId::None,
  2040. .interface = SemIR::SpecificInterface::None,
  2041. .witness_id = witness_id,
  2042. .scope_id = import_impl.is_complete() ? AddPlaceholderNameScope(context)
  2043. : SemIR::NameScopeId::None,
  2044. .is_final = import_impl.is_final}});
  2045. // Write the impl ID into the ImplDecl.
  2046. auto impl_const_id =
  2047. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  2048. return {impl_decl.impl_id, impl_const_id};
  2049. }
  2050. // Imports the definition of an impl.
  2051. static auto AddImplDefinition(ImportContext& context,
  2052. const SemIR::Impl& import_impl,
  2053. SemIR::Impl& new_impl) -> void {
  2054. new_impl.definition_id = new_impl.first_owning_decl_id;
  2055. new_impl.defined = true;
  2056. if (import_impl.scope_id.has_value()) {
  2057. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  2058. new_scope.Set(new_impl.first_owning_decl_id, SemIR::NameId::None,
  2059. new_impl.parent_scope_id);
  2060. // Import the contents of the definition scope, if we might need it. Name
  2061. // lookup is never performed into this scope by a user of the impl, so
  2062. // this is only necessary in the same library that defined the impl, in
  2063. // order to support defining members of the impl out of line in the impl
  2064. // file when the impl is defined in the API file.
  2065. // TODO: Check to see if this impl is owned by the API file, rather than
  2066. // merely being imported into it.
  2067. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2068. const auto& import_scope =
  2069. context.import_name_scopes().Get(import_impl.scope_id);
  2070. // Push a block so that we can add scoped instructions to it.
  2071. context.local_context().inst_block_stack().Push();
  2072. AddNameScopeImportRefs(context, import_scope, new_scope);
  2073. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  2074. }
  2075. }
  2076. }
  2077. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2078. SemIR::ImplDecl inst,
  2079. SemIR::ConstantId impl_const_id)
  2080. -> ResolveResult {
  2081. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  2082. // functions. Factor out the commonality.
  2083. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2084. auto specific_interface_data =
  2085. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  2086. SemIR::ImplId impl_id = SemIR::ImplId::None;
  2087. if (!impl_const_id.has_value()) {
  2088. if (resolver.HasNewWork()) {
  2089. // This is the end of the first phase. Don't make a new impl yet if we
  2090. // already have new work.
  2091. return ResolveResult::Retry();
  2092. }
  2093. // On the second phase, create a forward declaration of the impl for any
  2094. // recursive references.
  2095. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  2096. std::tie(impl_id, impl_const_id) =
  2097. MakeImplDeclaration(resolver, import_impl, witness_id);
  2098. } else {
  2099. // On the third phase, compute the impl ID from the "constant value" of
  2100. // the declaration, which is a reference to the created ImplDecl.
  2101. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  2102. resolver.local_constant_values().GetInstId(impl_const_id));
  2103. impl_id = impl_const_inst.impl_id;
  2104. }
  2105. // Load constants for the definition.
  2106. auto parent_scope_id =
  2107. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  2108. auto implicit_param_patterns = GetLocalInstBlockContents(
  2109. resolver, import_impl.implicit_param_patterns_id);
  2110. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  2111. auto self_const_id = GetLocalConstantId(
  2112. resolver,
  2113. resolver.import_constant_values().GetAttached(import_impl.self_id));
  2114. auto constraint_const_id = GetLocalConstantId(
  2115. resolver,
  2116. resolver.import_constant_values().GetAttached(import_impl.constraint_id));
  2117. auto& new_impl = resolver.local_impls().Get(impl_id);
  2118. if (resolver.HasNewWork()) {
  2119. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2120. }
  2121. new_impl.parent_scope_id = parent_scope_id;
  2122. new_impl.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2123. resolver, import_impl.implicit_param_patterns_id,
  2124. implicit_param_patterns);
  2125. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  2126. generic_data);
  2127. // Create instructions for self and constraint to hold the symbolic constant
  2128. // value for a generic impl.
  2129. new_impl.self_id = resolver.local_ir().types().GetAsTypeInstId(
  2130. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId, import_impl.self_id,
  2131. self_const_id));
  2132. new_impl.constraint_id = resolver.local_ir().types().GetAsTypeInstId(
  2133. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId,
  2134. import_impl.constraint_id, constraint_const_id));
  2135. new_impl.interface = GetLocalSpecificInterface(
  2136. resolver, import_impl.interface, specific_interface_data);
  2137. if (import_impl.is_complete()) {
  2138. AddImplDefinition(resolver, import_impl, new_impl);
  2139. }
  2140. // If the `impl` is declared in the API file corresponding to the current
  2141. // file, add this to impl lookup so that it can be found by redeclarations
  2142. // in the current file.
  2143. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2144. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2145. }
  2146. return ResolveResult::Done(impl_const_id, new_impl.first_decl_id());
  2147. }
  2148. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2149. SemIR::ImportRefLoaded /*inst*/,
  2150. SemIR::InstId inst_id) -> ResolveResult {
  2151. // Return the constant for the instruction of the imported constant.
  2152. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2153. CARBON_CHECK(constant_id.has_value(),
  2154. "Loaded import ref has no constant value");
  2155. if (!constant_id.is_constant()) {
  2156. resolver.local_context().TODO(
  2157. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2158. return ResolveResult::Done(constant_id);
  2159. }
  2160. auto new_constant_id = GetLocalConstantId(
  2161. resolver, resolver.import_constant_values().GetInstId(constant_id));
  2162. return RetryOrDone(resolver, new_constant_id);
  2163. }
  2164. // Make a declaration of an interface. This is done as a separate step from
  2165. // importing the interface definition in order to resolve cycles.
  2166. static auto MakeInterfaceDecl(ImportContext& context,
  2167. const SemIR::Interface& import_interface,
  2168. SemIR::SpecificId enclosing_specific_id)
  2169. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2170. SemIR::InterfaceDecl interface_decl = {
  2171. .type_id = SemIR::TypeType::TypeId,
  2172. .interface_id = SemIR::InterfaceId::None,
  2173. .decl_block_id = SemIR::InstBlockId::Empty};
  2174. auto interface_decl_id = AddPlaceholderImportedInst(
  2175. context, import_interface.first_owning_decl_id, interface_decl);
  2176. // Start with an incomplete interface.
  2177. interface_decl.interface_id = context.local_interfaces().Add(
  2178. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2179. import_interface),
  2180. {.scope_id = import_interface.is_complete()
  2181. ? AddPlaceholderNameScope(context)
  2182. : SemIR::NameScopeId::None}});
  2183. if (import_interface.has_parameters()) {
  2184. interface_decl.type_id = GetGenericInterfaceType(
  2185. context.local_context(), interface_decl.interface_id,
  2186. enclosing_specific_id);
  2187. }
  2188. // Write the interface ID into the InterfaceDecl.
  2189. auto interface_const_id = ReplacePlaceholderImportedInst(
  2190. context, interface_decl_id, interface_decl);
  2191. return {interface_decl.interface_id, interface_const_id};
  2192. }
  2193. // Imports the definition for an interface that has been imported as a forward
  2194. // declaration.
  2195. static auto AddInterfaceDefinition(ImportContext& context,
  2196. const SemIR::Interface& import_interface,
  2197. SemIR::Interface& new_interface,
  2198. SemIR::InstId self_param_id) -> void {
  2199. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  2200. const auto& import_scope =
  2201. context.import_name_scopes().Get(import_interface.scope_id);
  2202. // Push a block so that we can add scoped instructions to it.
  2203. context.local_context().inst_block_stack().Push();
  2204. InitializeNameScopeAndImportRefs(
  2205. context, import_scope, new_scope, new_interface.first_owning_decl_id,
  2206. SemIR::NameId::None, new_interface.parent_scope_id);
  2207. new_scope.set_is_interface_definition();
  2208. new_interface.associated_entities_id = AddAssociatedEntities(
  2209. context, new_interface.scope_id, import_interface.associated_entities_id);
  2210. new_interface.body_block_id =
  2211. context.local_context().inst_block_stack().Pop();
  2212. new_interface.self_param_id = self_param_id;
  2213. CARBON_CHECK(import_scope.extended_scopes().empty(),
  2214. "Interfaces don't currently have extended scopes to support.");
  2215. }
  2216. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2217. SemIR::InterfaceDecl inst,
  2218. SemIR::ConstantId interface_const_id)
  2219. -> ResolveResult {
  2220. const auto& import_interface =
  2221. resolver.import_interfaces().Get(inst.interface_id);
  2222. SemIR::InterfaceId interface_id = SemIR::InterfaceId::None;
  2223. if (!interface_const_id.has_value()) {
  2224. auto import_specific_id = SemIR::SpecificId::None;
  2225. if (auto import_generic_interface_type =
  2226. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2227. inst.type_id)) {
  2228. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2229. }
  2230. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2231. if (resolver.HasNewWork()) {
  2232. // This is the end of the first phase. Don't make a new interface yet if
  2233. // we already have new work.
  2234. return ResolveResult::Retry();
  2235. }
  2236. // On the second phase, create a forward declaration of the interface.
  2237. auto enclosing_specific_id =
  2238. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2239. std::tie(interface_id, interface_const_id) =
  2240. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2241. } else {
  2242. // On the third phase, compute the interface ID from the constant value of
  2243. // the declaration.
  2244. auto interface_const_inst = resolver.local_insts().Get(
  2245. resolver.local_constant_values().GetInstId(interface_const_id));
  2246. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2247. const SemIR::FacetTypeInfo& facet_type_info =
  2248. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2249. auto interface_type = facet_type_info.TryAsSingleInterface();
  2250. CARBON_CHECK(interface_type);
  2251. interface_id = interface_type->interface_id;
  2252. } else {
  2253. auto generic_interface_type =
  2254. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2255. interface_const_inst.type_id());
  2256. interface_id = generic_interface_type.interface_id;
  2257. }
  2258. }
  2259. auto parent_scope_id =
  2260. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2261. auto implicit_param_patterns = GetLocalInstBlockContents(
  2262. resolver, import_interface.implicit_param_patterns_id);
  2263. auto param_patterns =
  2264. GetLocalInstBlockContents(resolver, import_interface.param_patterns_id);
  2265. auto generic_data =
  2266. GetLocalGenericData(resolver, import_interface.generic_id);
  2267. std::optional<SemIR::InstId> self_param_id;
  2268. if (import_interface.is_complete()) {
  2269. self_param_id =
  2270. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2271. }
  2272. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2273. if (resolver.HasNewWork()) {
  2274. return ResolveResult::Retry(interface_const_id,
  2275. new_interface.first_decl_id());
  2276. }
  2277. new_interface.parent_scope_id = parent_scope_id;
  2278. new_interface.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2279. resolver, import_interface.implicit_param_patterns_id,
  2280. implicit_param_patterns);
  2281. new_interface.param_patterns_id = GetLocalCanonicalInstBlockId(
  2282. resolver, import_interface.param_patterns_id, param_patterns);
  2283. SetGenericData(resolver, import_interface.generic_id,
  2284. new_interface.generic_id, generic_data);
  2285. if (import_interface.is_complete()) {
  2286. CARBON_CHECK(self_param_id);
  2287. AddInterfaceDefinition(resolver, import_interface, new_interface,
  2288. *self_param_id);
  2289. }
  2290. return ResolveResult::Done(interface_const_id, new_interface.first_decl_id());
  2291. }
  2292. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2293. SemIR::FacetAccessType inst) -> ResolveResult {
  2294. auto facet_value_inst_id =
  2295. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2296. if (resolver.HasNewWork()) {
  2297. return ResolveResult::Retry();
  2298. }
  2299. return ResolveAsDeduplicated<SemIR::FacetAccessType>(
  2300. resolver, {.type_id = SemIR::TypeType::TypeId,
  2301. .facet_value_inst_id = facet_value_inst_id});
  2302. }
  2303. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2304. SemIR::FacetType inst) -> ResolveResult {
  2305. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2306. const SemIR::FacetTypeInfo& import_facet_type_info =
  2307. resolver.import_facet_types().Get(inst.facet_type_id);
  2308. for (auto interface : import_facet_type_info.extend_constraints) {
  2309. // We discard this here and recompute it below instead of saving it to avoid
  2310. // allocations.
  2311. GetLocalSpecificInterfaceData(resolver, interface);
  2312. }
  2313. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2314. // We discard this here and recompute it below instead of saving it to avoid
  2315. // allocations.
  2316. GetLocalSpecificInterfaceData(resolver, interface);
  2317. }
  2318. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2319. GetLocalConstantInstId(resolver, rewrite.lhs_id);
  2320. GetLocalConstantInstId(resolver, rewrite.rhs_id);
  2321. }
  2322. if (resolver.HasNewWork()) {
  2323. return ResolveResult::Retry();
  2324. }
  2325. SemIR::FacetTypeInfo local_facet_type_info = {
  2326. .builtin_constraint_mask = import_facet_type_info.builtin_constraint_mask,
  2327. .other_requirements = import_facet_type_info.other_requirements};
  2328. local_facet_type_info.extend_constraints.reserve(
  2329. import_facet_type_info.extend_constraints.size());
  2330. for (auto interface : import_facet_type_info.extend_constraints) {
  2331. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2332. local_facet_type_info.extend_constraints.push_back(
  2333. GetLocalSpecificInterface(resolver, interface, data));
  2334. }
  2335. local_facet_type_info.self_impls_constraints.reserve(
  2336. import_facet_type_info.self_impls_constraints.size());
  2337. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2338. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2339. local_facet_type_info.self_impls_constraints.push_back(
  2340. GetLocalSpecificInterface(resolver, interface, data));
  2341. }
  2342. local_facet_type_info.rewrite_constraints.reserve(
  2343. import_facet_type_info.rewrite_constraints.size());
  2344. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2345. local_facet_type_info.rewrite_constraints.push_back(
  2346. {.lhs_id = GetLocalConstantInstId(resolver, rewrite.lhs_id),
  2347. .rhs_id = GetLocalConstantInstId(resolver, rewrite.rhs_id)});
  2348. }
  2349. // TODO: Also process the other requirements.
  2350. SemIR::FacetTypeId facet_type_id =
  2351. resolver.local_facet_types().Add(std::move(local_facet_type_info));
  2352. return ResolveAsDeduplicated<SemIR::FacetType>(
  2353. resolver,
  2354. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  2355. }
  2356. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2357. SemIR::FacetValue inst) -> ResolveResult {
  2358. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2359. auto type_inst_id = GetLocalTypeInstId(resolver, inst.type_inst_id);
  2360. auto witnesses = GetLocalInstBlockContents(resolver, inst.witnesses_block_id);
  2361. if (resolver.HasNewWork()) {
  2362. return ResolveResult::Retry();
  2363. }
  2364. return ResolveAsDeduplicated<SemIR::FacetValue>(
  2365. resolver,
  2366. {.type_id =
  2367. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2368. .type_inst_id = type_inst_id,
  2369. .witnesses_block_id = GetLocalCanonicalInstBlockId(
  2370. resolver, inst.witnesses_block_id, witnesses)});
  2371. }
  2372. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2373. SemIR::LookupImplWitness inst)
  2374. -> ResolveResult {
  2375. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2376. SemIR::WitnessType::TypeInstId);
  2377. auto query_self_inst_id =
  2378. GetLocalConstantInstId(resolver, inst.query_self_inst_id);
  2379. const auto& import_specific_interface =
  2380. resolver.import_specific_interfaces().Get(
  2381. inst.query_specific_interface_id);
  2382. auto data =
  2383. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  2384. if (resolver.HasNewWork()) {
  2385. return ResolveResult::Retry();
  2386. }
  2387. auto specific_interface =
  2388. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  2389. auto query_specific_interface_id =
  2390. resolver.local_specific_interfaces().Add(specific_interface);
  2391. return ResolveAsDeduplicated<SemIR::LookupImplWitness>(
  2392. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2393. SemIR::WitnessType::TypeInstId),
  2394. .query_self_inst_id = query_self_inst_id,
  2395. .query_specific_interface_id = query_specific_interface_id});
  2396. }
  2397. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2398. SemIR::ImplWitness inst) -> ResolveResult {
  2399. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2400. SemIR::WitnessType::TypeInstId);
  2401. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2402. auto witness_table_id =
  2403. GetLocalConstantInstId(resolver, inst.witness_table_id);
  2404. if (resolver.HasNewWork()) {
  2405. return ResolveResult::Retry();
  2406. }
  2407. auto specific_id =
  2408. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2409. return ResolveAsDeduplicated<SemIR::ImplWitness>(
  2410. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2411. SemIR::WitnessType::TypeInstId),
  2412. .witness_table_id = witness_table_id,
  2413. .specific_id = specific_id});
  2414. }
  2415. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2416. SemIR::ImplWitnessAccess inst)
  2417. -> ResolveResult {
  2418. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2419. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2420. if (resolver.HasNewWork()) {
  2421. return ResolveResult::Retry();
  2422. }
  2423. return ResolveAsDeduplicated<SemIR::ImplWitnessAccess>(
  2424. resolver,
  2425. {.type_id =
  2426. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2427. .witness_id = witness_id,
  2428. .index = inst.index});
  2429. }
  2430. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2431. SemIR::ImplWitnessTable inst,
  2432. SemIR::InstId import_inst_id) -> ResolveResult {
  2433. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2434. auto import_decl_inst_id = import_impl.first_decl_id();
  2435. auto local_decl_inst_id =
  2436. GetLocalConstantInstId(resolver, import_decl_inst_id);
  2437. if (resolver.HasNewWork()) {
  2438. return ResolveResult::Retry();
  2439. }
  2440. auto impl_decl =
  2441. resolver.local_insts().GetAs<SemIR::ImplDecl>(local_decl_inst_id);
  2442. auto impl_id = impl_decl.impl_id;
  2443. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  2444. // Create a corresponding instruction to represent the table.
  2445. return ResolveAsUnique<SemIR::ImplWitnessTable>(
  2446. resolver, import_inst_id,
  2447. {.elements_id = elements_id, .impl_id = impl_id});
  2448. }
  2449. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2450. SemIR::IntValue inst) -> ResolveResult {
  2451. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2452. if (resolver.HasNewWork()) {
  2453. return ResolveResult::Retry();
  2454. }
  2455. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2456. // to add a new canonical int in this IR.
  2457. auto int_id = inst.int_id.is_embedded_value()
  2458. ? inst.int_id
  2459. : resolver.local_ints().AddSigned(
  2460. resolver.import_ints().Get(inst.int_id));
  2461. return ResolveAsDeduplicated<SemIR::IntValue>(
  2462. resolver,
  2463. {.type_id =
  2464. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2465. .int_id = int_id});
  2466. }
  2467. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2468. SemIR::IntType inst) -> ResolveResult {
  2469. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2470. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2471. if (resolver.HasNewWork()) {
  2472. return ResolveResult::Retry();
  2473. }
  2474. return ResolveAsDeduplicated<SemIR::IntType>(
  2475. resolver, {.type_id = SemIR::TypeType::TypeId,
  2476. .int_kind = inst.int_kind,
  2477. .bit_width_id = bit_width_id});
  2478. }
  2479. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2480. SemIR::Namespace inst,
  2481. SemIR::InstId import_inst_id) -> ResolveResult {
  2482. const auto& name_scope =
  2483. resolver.import_name_scopes().Get(inst.name_scope_id);
  2484. // A package from a different file becomes a child of the package here, as it
  2485. // would be if it were imported.
  2486. auto parent_scope_id =
  2487. inst.name_scope_id == SemIR::NameScopeId::Package
  2488. ? SemIR::NameScopeId::Package
  2489. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2490. if (resolver.HasNewWork()) {
  2491. return ResolveResult::Retry();
  2492. }
  2493. auto namespace_type_id = GetSingletonType(resolver.local_context(),
  2494. SemIR::NamespaceType::TypeInstId);
  2495. auto namespace_decl =
  2496. SemIR::Namespace{.type_id = namespace_type_id,
  2497. .name_scope_id = SemIR::NameScopeId::None,
  2498. .import_id = SemIR::AbsoluteInstId::None};
  2499. auto inst_id =
  2500. AddPlaceholderImportedInst(resolver, import_inst_id, namespace_decl);
  2501. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2502. namespace_decl.name_scope_id =
  2503. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2504. // Namespaces from this package are eagerly imported, so anything we load here
  2505. // must be a closed import.
  2506. resolver.local_name_scopes()
  2507. .Get(namespace_decl.name_scope_id)
  2508. .set_is_closed_import(true);
  2509. auto namespace_const_id =
  2510. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  2511. return {.const_id = namespace_const_id};
  2512. }
  2513. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2514. SemIR::PatternType inst) -> ResolveResult {
  2515. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2516. auto scrutinee_type_inst_id =
  2517. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  2518. if (resolver.HasNewWork()) {
  2519. return ResolveResult::Retry();
  2520. }
  2521. return ResolveAsDeduplicated<SemIR::PatternType>(
  2522. resolver, {.type_id = SemIR::TypeType::TypeId,
  2523. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  2524. }
  2525. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2526. SemIR::PointerType inst) -> ResolveResult {
  2527. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2528. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  2529. if (resolver.HasNewWork()) {
  2530. return ResolveResult::Retry();
  2531. }
  2532. return ResolveAsDeduplicated<SemIR::PointerType>(
  2533. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  2534. }
  2535. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2536. SemIR::RequireCompleteType inst)
  2537. -> ResolveResult {
  2538. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2539. SemIR::WitnessType::TypeInstId);
  2540. auto complete_type_inst_id =
  2541. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  2542. if (resolver.HasNewWork()) {
  2543. return ResolveResult::Retry();
  2544. }
  2545. return ResolveAsDeduplicated<SemIR::RequireCompleteType>(
  2546. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2547. SemIR::WitnessType::TypeInstId),
  2548. .complete_type_inst_id = complete_type_inst_id});
  2549. }
  2550. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2551. SemIR::ReturnSlotPattern inst,
  2552. SemIR::InstId import_inst_id) -> ResolveResult {
  2553. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2554. if (resolver.HasNewWork()) {
  2555. return ResolveResult::Retry();
  2556. }
  2557. return ResolveAsUnique<SemIR::ReturnSlotPattern>(
  2558. resolver, import_inst_id,
  2559. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2560. type_const_id),
  2561. .type_inst_id = SemIR::TypeInstId::None});
  2562. }
  2563. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2564. SemIR::SpecificFunction inst) -> ResolveResult {
  2565. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2566. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2567. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2568. if (resolver.HasNewWork()) {
  2569. return ResolveResult::Retry();
  2570. }
  2571. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2572. type_const_id);
  2573. auto specific_id =
  2574. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2575. return ResolveAsDeduplicated<SemIR::SpecificFunction>(
  2576. resolver,
  2577. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2578. }
  2579. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2580. SemIR::SpecificImplFunction inst)
  2581. -> ResolveResult {
  2582. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2583. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2584. if (resolver.HasNewWork()) {
  2585. return ResolveResult::Retry();
  2586. }
  2587. auto type_id = GetSingletonType(resolver.local_context(),
  2588. SemIR::SpecificFunctionType::TypeInstId);
  2589. auto specific_id =
  2590. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2591. return ResolveAsDeduplicated<SemIR::SpecificImplFunction>(
  2592. resolver,
  2593. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2594. }
  2595. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2596. SemIR::StructAccess inst) -> ResolveResult {
  2597. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2598. auto struct_id = GetLocalConstantInstId(resolver, inst.struct_id);
  2599. if (resolver.HasNewWork()) {
  2600. return ResolveResult::Retry();
  2601. }
  2602. // A `struct_access` constant requires its struct operand to have a complete
  2603. // type.
  2604. CompleteTypeOrCheckFail(resolver.local_context(),
  2605. resolver.local_insts().Get(struct_id).type_id());
  2606. return ResolveAsDeduplicated<SemIR::StructAccess>(
  2607. resolver,
  2608. {.type_id =
  2609. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2610. .struct_id = struct_id,
  2611. .index = inst.index});
  2612. }
  2613. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2614. SemIR::StructType inst) -> ResolveResult {
  2615. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2616. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2617. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  2618. field_type_inst_ids.reserve(orig_fields.size());
  2619. for (auto field : orig_fields) {
  2620. field_type_inst_ids.push_back(
  2621. GetLocalTypeInstId(resolver, field.type_inst_id));
  2622. }
  2623. if (resolver.HasNewWork()) {
  2624. return ResolveResult::Retry();
  2625. }
  2626. // Prepare a vector of fields for GetStructType.
  2627. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2628. new_fields.reserve(orig_fields.size());
  2629. for (auto [orig_field, field_type_inst_id] :
  2630. llvm::zip(orig_fields, field_type_inst_ids)) {
  2631. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2632. new_fields.push_back(
  2633. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  2634. }
  2635. return ResolveAsDeduplicated<SemIR::StructType>(
  2636. resolver, {.type_id = SemIR::TypeType::TypeId,
  2637. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2638. new_fields)});
  2639. }
  2640. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2641. SemIR::StructValue inst) -> ResolveResult {
  2642. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2643. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2644. if (resolver.HasNewWork()) {
  2645. return ResolveResult::Retry();
  2646. }
  2647. return ResolveAsDeduplicated<SemIR::StructValue>(
  2648. resolver,
  2649. {.type_id =
  2650. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2651. .elements_id =
  2652. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2653. }
  2654. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2655. SemIR::TupleAccess inst) -> ResolveResult {
  2656. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2657. auto tuple_id = GetLocalConstantInstId(resolver, inst.tuple_id);
  2658. if (resolver.HasNewWork()) {
  2659. return ResolveResult::Retry();
  2660. }
  2661. // A `tuple_access` constant requires its struct operand to have a complete
  2662. // type.
  2663. CompleteTypeOrCheckFail(resolver.local_context(),
  2664. resolver.local_insts().Get(tuple_id).type_id());
  2665. return ResolveAsDeduplicated<SemIR::TupleAccess>(
  2666. resolver,
  2667. {.type_id =
  2668. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2669. .tuple_id = tuple_id,
  2670. .index = inst.index});
  2671. }
  2672. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2673. SemIR::TuplePattern inst,
  2674. SemIR::InstId import_inst_id) -> ResolveResult {
  2675. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2676. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  2677. if (resolver.HasNewWork()) {
  2678. return ResolveResult::Retry();
  2679. }
  2680. return ResolveAsUnique<SemIR::TuplePattern>(
  2681. resolver, import_inst_id,
  2682. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2683. type_const_id),
  2684. .elements_id =
  2685. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements)});
  2686. }
  2687. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2688. SemIR::TupleType inst) -> ResolveResult {
  2689. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2690. auto orig_type_inst_ids =
  2691. resolver.import_inst_blocks().Get(inst.type_elements_id);
  2692. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  2693. // type system that its holding `TypeInstId` elements.
  2694. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  2695. type_inst_ids.reserve(orig_type_inst_ids.size());
  2696. for (auto elem_type_inst_id :
  2697. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  2698. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  2699. }
  2700. if (resolver.HasNewWork()) {
  2701. return ResolveResult::Retry();
  2702. }
  2703. return ResolveAsDeduplicated<SemIR::TupleType>(
  2704. resolver, {.type_id = SemIR::TypeType::TypeId,
  2705. .type_elements_id = GetLocalCanonicalInstBlockId(
  2706. resolver, inst.type_elements_id, type_inst_ids)});
  2707. }
  2708. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2709. SemIR::TupleValue inst) -> ResolveResult {
  2710. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2711. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2712. if (resolver.HasNewWork()) {
  2713. return ResolveResult::Retry();
  2714. }
  2715. return ResolveAsDeduplicated<SemIR::TupleValue>(
  2716. resolver,
  2717. {.type_id =
  2718. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2719. .elements_id =
  2720. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2721. }
  2722. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2723. SemIR::UnboundElementType inst)
  2724. -> ResolveResult {
  2725. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2726. auto class_const_inst_id =
  2727. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  2728. auto elem_const_inst_id =
  2729. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  2730. if (resolver.HasNewWork()) {
  2731. return ResolveResult::Retry();
  2732. }
  2733. return ResolveAsDeduplicated<SemIR::UnboundElementType>(
  2734. resolver, {.type_id = SemIR::TypeType::TypeId,
  2735. .class_type_inst_id = class_const_inst_id,
  2736. .element_type_inst_id = elem_const_inst_id});
  2737. }
  2738. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2739. SemIR::VarPattern inst,
  2740. SemIR::InstId import_inst_id) -> ResolveResult {
  2741. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2742. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  2743. if (resolver.HasNewWork()) {
  2744. return ResolveResult::Retry();
  2745. }
  2746. return ResolveAsUnique<SemIR::VarPattern>(
  2747. resolver, import_inst_id,
  2748. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2749. type_const_id),
  2750. .subpattern_id = subpattern_id});
  2751. }
  2752. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2753. SemIR::VarStorage inst,
  2754. SemIR::InstId import_inst_id) -> ResolveResult {
  2755. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2756. auto pattern_id = GetLocalConstantInstId(resolver, inst.pattern_id);
  2757. if (resolver.HasNewWork()) {
  2758. return ResolveResult::Retry();
  2759. }
  2760. return ResolveAsUnique<SemIR::VarStorage>(
  2761. resolver, import_inst_id,
  2762. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2763. type_const_id),
  2764. .pattern_id = pattern_id});
  2765. }
  2766. // Tries to resolve the InstId, returning a canonical constant when ready, or
  2767. // `None` if more has been added to the stack. This is the same as
  2768. // TryResolveInst, except that it may resolve symbolic constants as canonical
  2769. // constants instead of as constants associated with a particular generic.
  2770. //
  2771. // TODO: Consider refactoring the body to a helper in order to eliminate
  2772. // recursion.
  2773. // NOLINTNEXTLINE(misc-no-recursion)
  2774. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  2775. SemIR::InstId inst_id,
  2776. SemIR::ConstantId const_id)
  2777. -> ResolveResult {
  2778. // These instruction types are imported across multiple phases to arrive at
  2779. // their constant value. We can't just import their constant value instruction
  2780. // directly.
  2781. auto untyped_inst = resolver.import_insts().GetWithAttachedType(inst_id);
  2782. CARBON_KIND_SWITCH(untyped_inst) {
  2783. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  2784. return TryResolveTypedInst(resolver, inst, const_id);
  2785. }
  2786. case CARBON_KIND(SemIR::ClassDecl inst): {
  2787. return TryResolveTypedInst(resolver, inst, const_id);
  2788. }
  2789. case CARBON_KIND(SemIR::FunctionDecl inst): {
  2790. return TryResolveTypedInst(resolver, inst, const_id);
  2791. }
  2792. case CARBON_KIND(SemIR::ImplDecl inst): {
  2793. return TryResolveTypedInst(resolver, inst, const_id);
  2794. }
  2795. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  2796. return TryResolveTypedInst(resolver, inst, const_id);
  2797. }
  2798. default:
  2799. break;
  2800. }
  2801. // Other instructions are imported in a single phase (once their dependencies
  2802. // are all imported).
  2803. CARBON_CHECK(!const_id.has_value());
  2804. auto inst_constant_id = resolver.import_constant_values().Get(inst_id);
  2805. if (!inst_constant_id.is_constant()) {
  2806. // TODO: Import of non-constant BindNames happens when importing `let`
  2807. // declarations.
  2808. CARBON_CHECK(resolver.import_insts().Is<SemIR::BindName>(inst_id),
  2809. "TryResolveInst on non-constant instruction {0}", inst_id);
  2810. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  2811. }
  2812. // Import the canonical constant value instruction for `inst_id` directly. We
  2813. // don't try to import the non-canonical `inst_id`.
  2814. auto constant_inst_id =
  2815. resolver.import_constant_values().GetInstId(inst_constant_id);
  2816. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  2817. constant_inst_id) == constant_inst_id,
  2818. "Constant value of constant instruction should refer to "
  2819. "the same instruction");
  2820. if (SemIR::IsSingletonInstId(constant_inst_id)) {
  2821. // Constants for builtins can be directly copied.
  2822. return ResolveResult::Done(
  2823. resolver.local_constant_values().Get(constant_inst_id));
  2824. }
  2825. auto untyped_constant_inst =
  2826. resolver.import_insts().GetWithAttachedType(constant_inst_id);
  2827. CARBON_KIND_SWITCH(untyped_constant_inst) {
  2828. case CARBON_KIND(SemIR::AdaptDecl inst): {
  2829. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2830. }
  2831. case CARBON_KIND(SemIR::AddrPattern inst): {
  2832. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2833. }
  2834. case CARBON_KIND(SemIR::ArrayType inst): {
  2835. return TryResolveTypedInst(resolver, inst);
  2836. }
  2837. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  2838. return TryResolveTypedInst(resolver, inst);
  2839. }
  2840. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  2841. return TryResolveTypedInst(resolver, inst);
  2842. }
  2843. case CARBON_KIND(SemIR::BaseDecl inst): {
  2844. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2845. }
  2846. case CARBON_KIND(SemIR::BindAlias inst): {
  2847. return TryResolveTypedInst(resolver, inst);
  2848. }
  2849. case CARBON_KIND(SemIR::BindingPattern inst): {
  2850. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2851. }
  2852. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  2853. return TryResolveTypedInst(resolver, inst);
  2854. }
  2855. case CARBON_KIND(SemIR::BoolLiteral inst): {
  2856. return TryResolveTypedInst(resolver, inst);
  2857. }
  2858. case CARBON_KIND(SemIR::BoundMethod inst): {
  2859. return TryResolveTypedInst(resolver, inst);
  2860. }
  2861. case CARBON_KIND(SemIR::Call inst): {
  2862. return TryResolveTypedInst(resolver, inst);
  2863. }
  2864. case CARBON_KIND(SemIR::CharLiteralValue inst): {
  2865. return TryResolveTypedInst(resolver, inst);
  2866. }
  2867. case CARBON_KIND(SemIR::ClassType inst): {
  2868. return TryResolveTypedInst(resolver, inst);
  2869. }
  2870. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  2871. return TryResolveTypedInst(resolver, inst);
  2872. }
  2873. case CARBON_KIND(SemIR::ConstType inst): {
  2874. return TryResolveTypedInst(resolver, inst);
  2875. }
  2876. case CARBON_KIND(SemIR::CppOverloadSetType inst): {
  2877. return TryResolveTypedInst(resolver, inst);
  2878. }
  2879. case CARBON_KIND(SemIR::CppOverloadSetValue inst): {
  2880. return TryResolveTypedInst(resolver, inst);
  2881. }
  2882. case CARBON_KIND(SemIR::ExportDecl inst): {
  2883. return TryResolveTypedInst(resolver, inst);
  2884. }
  2885. case CARBON_KIND(SemIR::FacetAccessType inst): {
  2886. return TryResolveTypedInst(resolver, inst);
  2887. }
  2888. case CARBON_KIND(SemIR::FacetType inst): {
  2889. return TryResolveTypedInst(resolver, inst);
  2890. }
  2891. case CARBON_KIND(SemIR::FacetValue inst): {
  2892. return TryResolveTypedInst(resolver, inst);
  2893. }
  2894. case CARBON_KIND(SemIR::FieldDecl inst): {
  2895. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2896. }
  2897. case CARBON_KIND(SemIR::FloatLiteralValue inst): {
  2898. return TryResolveTypedInst(resolver, inst);
  2899. }
  2900. case CARBON_KIND(SemIR::FloatType inst): {
  2901. return TryResolveTypedInst(resolver, inst);
  2902. }
  2903. case CARBON_KIND(SemIR::FloatValue inst): {
  2904. return TryResolveTypedInst(resolver, inst);
  2905. }
  2906. case CARBON_KIND(SemIR::FunctionType inst): {
  2907. return TryResolveTypedInst(resolver, inst);
  2908. }
  2909. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  2910. return TryResolveTypedInst(resolver, inst);
  2911. }
  2912. case CARBON_KIND(SemIR::GenericClassType inst): {
  2913. return TryResolveTypedInst(resolver, inst);
  2914. }
  2915. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  2916. return TryResolveTypedInst(resolver, inst);
  2917. }
  2918. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  2919. return TryResolveTypedInst(resolver, inst);
  2920. }
  2921. case CARBON_KIND(SemIR::ImplWitness inst): {
  2922. return TryResolveTypedInst(resolver, inst);
  2923. }
  2924. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  2925. return TryResolveTypedInst(resolver, inst);
  2926. }
  2927. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  2928. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2929. }
  2930. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  2931. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2932. }
  2933. case CARBON_KIND(SemIR::IntValue inst): {
  2934. return TryResolveTypedInst(resolver, inst);
  2935. }
  2936. case CARBON_KIND(SemIR::IntType inst): {
  2937. return TryResolveTypedInst(resolver, inst);
  2938. }
  2939. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  2940. return TryResolveTypedInst(resolver, inst);
  2941. }
  2942. case CARBON_KIND(SemIR::Namespace inst): {
  2943. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2944. }
  2945. case CARBON_KIND(SemIR::OutParamPattern inst): {
  2946. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2947. }
  2948. case CARBON_KIND(SemIR::PartialType inst): {
  2949. return TryResolveTypedInst(resolver, inst);
  2950. }
  2951. case CARBON_KIND(SemIR::PatternType inst): {
  2952. return TryResolveTypedInst(resolver, inst);
  2953. }
  2954. case CARBON_KIND(SemIR::PointerType inst): {
  2955. return TryResolveTypedInst(resolver, inst);
  2956. }
  2957. case CARBON_KIND(SemIR::RefParamPattern inst): {
  2958. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2959. }
  2960. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  2961. return TryResolveTypedInst(resolver, inst);
  2962. }
  2963. case CARBON_KIND(SemIR::ReturnSlotPattern inst): {
  2964. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2965. }
  2966. case CARBON_KIND(SemIR::SpecificFunction inst): {
  2967. return TryResolveTypedInst(resolver, inst);
  2968. }
  2969. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  2970. return TryResolveTypedInst(resolver, inst);
  2971. }
  2972. case CARBON_KIND(SemIR::StructAccess inst): {
  2973. return TryResolveTypedInst(resolver, inst);
  2974. }
  2975. case CARBON_KIND(SemIR::StructType inst): {
  2976. return TryResolveTypedInst(resolver, inst);
  2977. }
  2978. case CARBON_KIND(SemIR::StructValue inst): {
  2979. return TryResolveTypedInst(resolver, inst);
  2980. }
  2981. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  2982. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2983. }
  2984. case CARBON_KIND(SemIR::TupleAccess inst): {
  2985. return TryResolveTypedInst(resolver, inst);
  2986. }
  2987. case CARBON_KIND(SemIR::TuplePattern inst): {
  2988. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  2989. }
  2990. case CARBON_KIND(SemIR::TupleType inst): {
  2991. return TryResolveTypedInst(resolver, inst);
  2992. }
  2993. case CARBON_KIND(SemIR::TupleValue inst): {
  2994. return TryResolveTypedInst(resolver, inst);
  2995. }
  2996. case CARBON_KIND(SemIR::UnboundElementType inst): {
  2997. return TryResolveTypedInst(resolver, inst);
  2998. }
  2999. case CARBON_KIND(SemIR::ValueParamPattern inst): {
  3000. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3001. }
  3002. case CARBON_KIND(SemIR::VarPattern inst): {
  3003. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3004. }
  3005. case CARBON_KIND(SemIR::VarStorage inst): {
  3006. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3007. }
  3008. case CARBON_KIND(SemIR::VtableDecl inst): {
  3009. return TryResolveTypedInst(resolver, inst);
  3010. }
  3011. case CARBON_KIND(SemIR::VtablePtr inst): {
  3012. return TryResolveTypedInst(resolver, inst);
  3013. }
  3014. default:
  3015. // Found a canonical instruction which needs to be resolved, but which is
  3016. // not yet handled.
  3017. //
  3018. // TODO: Could we turn this into a compile-time error?
  3019. CARBON_FATAL(
  3020. "Missing case in TryResolveInstCanonical for instruction kind {0}",
  3021. untyped_constant_inst.kind());
  3022. }
  3023. }
  3024. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  3025. // more has been added to the stack. A similar API is followed for all
  3026. // following TryResolveTypedInst helper functions.
  3027. //
  3028. // `const_id` is `None` unless we've tried to resolve this instruction
  3029. // before, in which case it's the previous result.
  3030. //
  3031. // TODO: Error is returned when support is missing, but that should go away.
  3032. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  3033. SemIR::ConstantId const_id) -> ResolveResult {
  3034. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  3035. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  3036. return TryResolveInstCanonical(resolver, inst_id, const_id);
  3037. }
  3038. // Try to import the generic. This might add new work.
  3039. const auto& symbolic_const =
  3040. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  3041. auto generic_const_id =
  3042. GetLocalConstantId(resolver, symbolic_const.generic_id);
  3043. auto inner_const_id = SemIR::ConstantId::None;
  3044. if (const_id.has_value()) {
  3045. // For the third phase, extract the constant value that
  3046. // TryResolveInstCanonical produced previously.
  3047. inner_const_id = resolver.local_constant_values().GetAttached(
  3048. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  3049. }
  3050. // Import the constant and rebuild the symbolic constant data.
  3051. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  3052. if (!result.const_id.has_value()) {
  3053. // First phase: TryResolveInstCanoncial needs a retry.
  3054. return result;
  3055. }
  3056. if (!const_id.has_value()) {
  3057. // Second phase: we have created an unattached constant. Create a
  3058. // corresponding attached constant.
  3059. if (symbolic_const.generic_id.has_value()) {
  3060. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  3061. {.inst_id =
  3062. resolver.local_constant_values().GetInstId(result.const_id),
  3063. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  3064. .index = symbolic_const.index,
  3065. .dependence = symbolic_const.dependence});
  3066. if (result.decl_id.has_value()) {
  3067. // Overwrite the unattached symbolic constant given initially to the
  3068. // declaration with its final attached symbolic value.
  3069. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  3070. }
  3071. }
  3072. } else {
  3073. // Third phase: perform a consistency check and produce the constant we
  3074. // created in the second phase.
  3075. CARBON_CHECK(result.const_id == inner_const_id,
  3076. "Constant value changed in third phase.");
  3077. result.const_id = const_id;
  3078. }
  3079. return result;
  3080. }
  3081. // Resolves and returns the local contents for an imported instruction block
  3082. // of constant instructions.
  3083. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  3084. SemIR::InstBlockId import_block_id)
  3085. -> llvm::SmallVector<SemIR::InstId> {
  3086. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  3087. llvm::SmallVector<SemIR::InstId> inst_ids;
  3088. inst_ids.reserve(import_block.size());
  3089. for (auto import_inst_id : import_block) {
  3090. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  3091. resolver.ResolveOneInst(import_inst_id)));
  3092. }
  3093. return inst_ids;
  3094. }
  3095. // Resolves and returns a local eval block for a region of an imported
  3096. // generic.
  3097. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  3098. const SemIR::Generic& import_generic,
  3099. SemIR::GenericId generic_id,
  3100. SemIR::GenericInstIndex::Region region)
  3101. -> SemIR::InstBlockId {
  3102. auto import_block_id = import_generic.GetEvalBlock(region);
  3103. if (!import_block_id.has_value()) {
  3104. return SemIR::InstBlockId::None;
  3105. }
  3106. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  3107. auto eval_block_id = RebuildGenericEvalBlock(resolver.local_context(),
  3108. generic_id, region, inst_ids);
  3109. // Set the locations of the instructions in the inst block to match those of
  3110. // the imported instructions.
  3111. for (auto [import_inst_id, local_inst_id] :
  3112. llvm::zip(resolver.import_inst_blocks().Get(import_block_id),
  3113. resolver.local_inst_blocks().Get(eval_block_id))) {
  3114. auto import_ir_inst_id = AddImportIRInst(resolver, import_inst_id);
  3115. resolver.local_insts().SetLocId(local_inst_id, import_ir_inst_id);
  3116. }
  3117. return eval_block_id;
  3118. }
  3119. // Fills in the remaining information in a partially-imported generic.
  3120. // NOLINTNEXTLINE(misc-no-recursion)
  3121. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  3122. ImportContext::PendingGeneric pending)
  3123. -> void {
  3124. const auto& import_generic =
  3125. resolver.import_generics().Get(pending.import_id);
  3126. // Load the bindings for the generic eagerly; they're used to form the self
  3127. // specific.
  3128. // TODO: Avoid recursion.
  3129. for (auto binding_id : resolver.local_inst_blocks().Get(
  3130. resolver.local_generics().Get(pending.local_id).bindings_id)) {
  3131. LoadImportRef(resolver.local_context(), binding_id);
  3132. }
  3133. // Don't store the local generic between calls: the generics list can be
  3134. // reallocated by ResolveLocalEvalBlock importing more specifics.
  3135. auto decl_block_id =
  3136. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  3137. SemIR::GenericInstIndex::Region::Declaration);
  3138. resolver.local_generics().Get(pending.local_id).decl_block_id = decl_block_id;
  3139. auto local_decl_id = resolver.local_generics().Get(pending.local_id).decl_id;
  3140. auto self_specific_id = MakeSelfSpecific(
  3141. resolver.local_context(), SemIR::LocId(local_decl_id), pending.local_id);
  3142. resolver.local_generics().Get(pending.local_id).self_specific_id =
  3143. self_specific_id;
  3144. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  3145. .local_id = self_specific_id});
  3146. auto definition_block_id =
  3147. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  3148. SemIR::GenericInstIndex::Region::Definition);
  3149. resolver.local_generics().Get(pending.local_id).definition_block_id =
  3150. definition_block_id;
  3151. }
  3152. // Resolves and returns a local inst block of constant instructions
  3153. // corresponding to an imported inst block.
  3154. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  3155. SemIR::InstBlockId import_block_id)
  3156. -> SemIR::InstBlockId {
  3157. if (!import_block_id.has_value()) {
  3158. return SemIR::InstBlockId::None;
  3159. }
  3160. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  3161. return resolver.local_inst_blocks().Add(inst_ids);
  3162. }
  3163. // Fills in the remaining information in a partially-imported specific.
  3164. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  3165. ImportContext::PendingSpecific pending)
  3166. -> void {
  3167. const auto& import_specific =
  3168. resolver.import_specifics().Get(pending.import_id);
  3169. // Don't store the local specific between calls: the specifics list can be
  3170. // reallocated by ResolveLocalInstBlock importing more specifics.
  3171. if (!resolver.local_specifics()
  3172. .Get(pending.local_id)
  3173. .decl_block_id.has_value()) {
  3174. auto decl_block_id =
  3175. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  3176. resolver.local_specifics().Get(pending.local_id).decl_block_id =
  3177. decl_block_id;
  3178. }
  3179. if (!resolver.local_specifics()
  3180. .Get(pending.local_id)
  3181. .definition_block_id.has_value() &&
  3182. import_specific.definition_block_id.has_value()) {
  3183. auto definition_block_id =
  3184. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  3185. resolver.local_specifics().Get(pending.local_id).definition_block_id =
  3186. definition_block_id;
  3187. }
  3188. }
  3189. // Perform any work that we deferred until the end of the main Resolve loop.
  3190. // NOLINTNEXTLINE(misc-no-recursion)
  3191. auto ImportRefResolver::PerformPendingWork() -> void {
  3192. // Note that the individual Finish steps can add new pending work, so keep
  3193. // going until we have no more work to do.
  3194. while (!pending_generics().empty() || !pending_specifics().empty()) {
  3195. // Process generics in the order that we added them because a later
  3196. // generic might refer to an earlier one, and the calls to
  3197. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  3198. // state.
  3199. // TODO: Import the generic eval block rather than calling
  3200. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  3201. for (auto generic_id : GrowingRange(pending_generics())) {
  3202. FinishPendingGeneric(*this, generic_id);
  3203. }
  3204. pending_generics().clear();
  3205. while (!pending_specifics().empty()) {
  3206. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  3207. }
  3208. }
  3209. }
  3210. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  3211. // loaded (including the one pointed at directly by the ImportRef), and the
  3212. // final instruction's type ID.
  3213. //
  3214. // This addresses cases where an ImportRefUnloaded may point at another
  3215. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  3216. // constant-evaluated version of the instruction to work with.
  3217. static auto GetInstForLoad(Context& context,
  3218. SemIR::ImportIRInstId import_ir_inst_id)
  3219. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  3220. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  3221. {}, SemIR::TypeId::None};
  3222. auto& [import_ir_insts, type_id] = result;
  3223. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  3224. // The first ImportIRInst is added directly because the IR doesn't need to be
  3225. // localized.
  3226. import_ir_insts.push_back(import_ir_inst);
  3227. const auto* cursor_ir =
  3228. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3229. while (true) {
  3230. auto cursor_inst =
  3231. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  3232. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  3233. if (!import_ref) {
  3234. type_id = cursor_inst.type_id();
  3235. return result;
  3236. }
  3237. import_ir_inst =
  3238. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  3239. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3240. import_ir_insts.push_back(SemIR::ImportIRInst(
  3241. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  3242. .is_export = false,
  3243. .sem_ir = cursor_ir}),
  3244. import_ir_inst.inst_id()));
  3245. }
  3246. }
  3247. // NOLINTNEXTLINE(misc-no-recursion)
  3248. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  3249. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  3250. if (!inst) {
  3251. return;
  3252. }
  3253. auto [indirect_insts, load_type_id] =
  3254. GetInstForLoad(context, inst->import_ir_inst_id);
  3255. // The last indirect instruction is the one to resolve. Pop it here because
  3256. // Resolve will assign the constant.
  3257. auto load_ir_inst = indirect_insts.pop_back_val();
  3258. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  3259. auto type_id = resolver.ResolveType(load_type_id);
  3260. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  3261. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  3262. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  3263. // TryEvalInst, which we want to avoid with ImportRefs.
  3264. context.sem_ir().insts().Set(
  3265. inst_id,
  3266. SemIR::ImportRefLoaded{.type_id = type_id,
  3267. .import_ir_inst_id = inst->import_ir_inst_id,
  3268. .entity_name_id = inst->entity_name_id});
  3269. // Store the constant for both the ImportRefLoaded and indirect instructions.
  3270. context.constant_values().Set(inst_id, constant_id);
  3271. for (const auto& import_ir_inst : indirect_insts) {
  3272. context.import_ir_constant_values()[import_ir_inst.ir_id().index].Set(
  3273. import_ir_inst.inst_id(), constant_id);
  3274. }
  3275. }
  3276. auto ImportImplsFromApiFile(Context& context) -> void {
  3277. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  3278. auto& import_ir = context.import_irs().Get(import_ir_id);
  3279. if (!import_ir.sem_ir) {
  3280. return;
  3281. }
  3282. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  3283. // Resolve the imported impl to a local impl ID.
  3284. ImportImpl(context, import_ir_id, impl_id);
  3285. }
  3286. }
  3287. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  3288. SemIR::ImplId impl_id) -> void {
  3289. ImportRefResolver resolver(&context, import_ir_id);
  3290. resolver.Resolve(context.import_irs()
  3291. .Get(import_ir_id)
  3292. .sem_ir->impls()
  3293. .Get(impl_id)
  3294. .first_decl_id());
  3295. }
  3296. auto ImportInterface(Context& context, SemIR::ImportIRId import_ir_id,
  3297. SemIR::InterfaceId interface_id) -> SemIR::InterfaceId {
  3298. ImportRefResolver resolver(&context, import_ir_id);
  3299. auto local_id = resolver.Resolve(context.import_irs()
  3300. .Get(import_ir_id)
  3301. .sem_ir->interfaces()
  3302. .Get(interface_id)
  3303. .first_decl_id());
  3304. auto local_inst =
  3305. context.insts().Get(context.constant_values().GetInstId(local_id));
  3306. // A non-generic interface will import as a facet type for that single
  3307. // interface.
  3308. if (auto facet_type = local_inst.TryAs<SemIR::FacetType>()) {
  3309. auto interface = context.facet_types()
  3310. .Get(facet_type->facet_type_id)
  3311. .TryAsSingleInterface();
  3312. CARBON_CHECK(interface,
  3313. "Importing an interface didn't produce a single interface");
  3314. return interface->interface_id;
  3315. }
  3316. // A generic interface will import as a constant of generic interface type.
  3317. auto generic_interface_type =
  3318. context.types().GetAs<SemIR::GenericInterfaceType>(local_inst.type_id());
  3319. return generic_interface_type.interface_id;
  3320. }
  3321. } // namespace Carbon::Check