import_ref.cpp 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647
  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 <array>
  6. #include <optional>
  7. #include <tuple>
  8. #include <type_traits>
  9. #include <utility>
  10. #include "common/check.h"
  11. #include "common/growing_range.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/check/context.h"
  15. #include "toolchain/check/eval.h"
  16. #include "toolchain/check/facet_type.h"
  17. #include "toolchain/check/generic.h"
  18. #include "toolchain/check/import.h"
  19. #include "toolchain/check/inst.h"
  20. #include "toolchain/check/name_lookup.h"
  21. #include "toolchain/check/type.h"
  22. #include "toolchain/check/type_completion.h"
  23. #include "toolchain/parse/node_ids.h"
  24. #include "toolchain/sem_ir/constant.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/ids.h"
  27. #include "toolchain/sem_ir/impl.h"
  28. #include "toolchain/sem_ir/import_ir.h"
  29. #include "toolchain/sem_ir/inst.h"
  30. #include "toolchain/sem_ir/inst_categories.h"
  31. #include "toolchain/sem_ir/inst_kind.h"
  32. #include "toolchain/sem_ir/name_scope.h"
  33. #include "toolchain/sem_ir/specific_interface.h"
  34. #include "toolchain/sem_ir/specific_named_constraint.h"
  35. #include "toolchain/sem_ir/type_info.h"
  36. #include "toolchain/sem_ir/typed_insts.h"
  37. namespace Carbon::Check {
  38. // Adds the ImportIR, excluding the update to the check_ir_map.
  39. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  40. -> SemIR::ImportIRId {
  41. context.import_ir_constant_values().push_back(SemIR::ConstantValueStore(
  42. SemIR::ConstantId::None,
  43. import_ir.sem_ir ? &import_ir.sem_ir->insts() : nullptr));
  44. return context.import_irs().Add(import_ir);
  45. }
  46. // Adds a special-cased IR and verifies it received the correct ID.
  47. static auto SetSpecialImportIR(Context& context, SemIR::ImportIR import_ir,
  48. SemIR::ImportIRId expected_import_ir_id)
  49. -> void {
  50. auto ir_id = SemIR::ImportIRId::None;
  51. if (import_ir.sem_ir != nullptr) {
  52. ir_id = AddImportIR(context, import_ir);
  53. } else {
  54. // We don't have a check_ir_id, so add without touching check_ir_map.
  55. context.import_ir_constant_values().push_back(
  56. SemIR::ConstantValueStore(SemIR::ConstantValueStore::Unusable));
  57. ir_id = context.import_irs().Add(import_ir);
  58. }
  59. CARBON_CHECK(ir_id == expected_import_ir_id,
  60. "Actual ImportIRId ({0}) != Expected ImportIRId ({1})", ir_id,
  61. expected_import_ir_id);
  62. }
  63. auto SetSpecialImportIRs(Context& context, SemIR::ImportIR import_ir) -> void {
  64. SetSpecialImportIR(context, import_ir, SemIR::ImportIRId::ApiForImpl);
  65. SetSpecialImportIR(context,
  66. {.decl_id = SemIR::InstId::None, .is_export = false},
  67. SemIR::ImportIRId::Cpp);
  68. }
  69. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  70. -> SemIR::ImportIRId {
  71. auto& ir_id = context.check_ir_map().Get(import_ir.sem_ir->check_ir_id());
  72. if (!ir_id.has_value()) {
  73. // Note this updates check_ir_map.
  74. ir_id = InternalAddImportIR(context, import_ir);
  75. } else if (import_ir.is_export) {
  76. // We're processing an `export import`. In case the IR was indirectly added
  77. // as a non-export, mark it as an export.
  78. context.import_irs().Get(ir_id).is_export = true;
  79. }
  80. return ir_id;
  81. }
  82. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  83. SemIR::EntityNameId entity_name_id =
  84. SemIR::EntityNameId::None) -> SemIR::InstId {
  85. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  86. auto import_ref_id = AddPlaceholderImportedInstInNoBlock(
  87. context,
  88. MakeImportedLocIdAndInst(
  89. context, import_ir_inst_id,
  90. SemIR::ImportRefUnloaded{.import_ir_inst_id = import_ir_inst_id,
  91. .entity_name_id = entity_name_id}));
  92. return import_ref_id;
  93. }
  94. static auto GetCanonicalImportIRInst(Context& context,
  95. const SemIR::File* target_ir,
  96. SemIR::InstId target_inst_id)
  97. -> SemIR::ImportIRInst {
  98. auto [canonical_ir, canonical_inst_id] =
  99. GetCanonicalFileAndInstId(target_ir, target_inst_id);
  100. auto ir_id = SemIR::ImportIRId::None;
  101. if (canonical_ir != &context.sem_ir()) {
  102. // This uses AddImportIR in case it was indirectly found, which can
  103. // happen with two or more steps of exports.
  104. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::None,
  105. .is_export = false,
  106. .sem_ir = canonical_ir});
  107. }
  108. return SemIR::ImportIRInst(ir_id, canonical_inst_id);
  109. }
  110. auto GetCanonicalImportIRInst(Context& context, SemIR::InstId inst_id)
  111. -> SemIR::ImportIRInst {
  112. return GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  113. }
  114. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::NameId name_id,
  115. SemIR::InstId prev_id,
  116. SemIR::ImportIRInst prev_import_ir_inst,
  117. SemIR::ImportIRId new_ir_id,
  118. const SemIR::File* new_import_ir,
  119. SemIR::InstId new_inst_id) -> void {
  120. auto new_import_ir_inst =
  121. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  122. if (new_import_ir_inst == prev_import_ir_inst) {
  123. return;
  124. }
  125. auto conflict_id =
  126. AddImportRef(context, SemIR::ImportIRInst(new_ir_id, new_inst_id));
  127. // TODO: Pass the imported name location instead of the conflict id.
  128. DiagnoseDuplicateName(context, name_id, SemIR::LocId(conflict_id),
  129. SemIR::LocId(prev_id));
  130. }
  131. namespace {
  132. // A context within which we are performing an import. Tracks information about
  133. // the source and destination. This provides a restricted interface compared to
  134. // ImportResolver: in particular, it does not have access to a work list.
  135. // Therefore code that accepts an ImportContext is unable to enqueue new work.
  136. class ImportContext {
  137. public:
  138. // `context` must not be null.
  139. explicit ImportContext(Context* context, SemIR::ImportIRId import_ir_id)
  140. : context_(context),
  141. import_ir_id_(import_ir_id),
  142. import_ir_(*context_->import_irs().Get(import_ir_id).sem_ir) {}
  143. // Returns the file we are importing from.
  144. auto import_ir() -> const SemIR::File& { return import_ir_; }
  145. // Accessors into value stores of the file we are importing from.
  146. auto import_associated_constants() -> const SemIR::AssociatedConstantStore& {
  147. return import_ir().associated_constants();
  148. }
  149. auto import_classes() -> const SemIR::ClassStore& {
  150. return import_ir().classes();
  151. }
  152. auto import_vtables() -> const SemIR::VtableStore& {
  153. return import_ir().vtables();
  154. }
  155. auto import_constant_values() -> const SemIR::ConstantValueStore& {
  156. return import_ir().constant_values();
  157. }
  158. auto import_entity_names() -> const SemIR::EntityNameStore& {
  159. return import_ir().entity_names();
  160. }
  161. auto import_facet_types() -> const SemIR::FacetTypeInfoStore& {
  162. return import_ir().facet_types();
  163. }
  164. auto import_functions() -> const SemIR::FunctionStore& {
  165. return import_ir().functions();
  166. }
  167. auto import_generics() -> const SemIR::GenericStore& {
  168. return import_ir().generics();
  169. }
  170. auto import_identifiers() -> const SharedValueStores::IdentifierStore& {
  171. return import_ir().identifiers();
  172. }
  173. auto import_impls() -> const SemIR::ImplStore& { return import_ir().impls(); }
  174. auto import_inst_blocks() -> const SemIR::InstBlockStore& {
  175. return import_ir().inst_blocks();
  176. }
  177. auto import_insts() -> const SemIR::InstStore& { return import_ir().insts(); }
  178. auto import_interfaces() -> const SemIR::InterfaceStore& {
  179. return import_ir().interfaces();
  180. }
  181. auto import_named_constraints() -> const SemIR::NamedConstraintStore& {
  182. return import_ir().named_constraints();
  183. }
  184. auto import_ints() -> const SharedValueStores::IntStore& {
  185. return import_ir().ints();
  186. }
  187. auto import_name_scopes() -> const SemIR::NameScopeStore& {
  188. return import_ir().name_scopes();
  189. }
  190. auto import_require_impls() -> const SemIR::RequireImplsStore& {
  191. return import_ir().require_impls();
  192. }
  193. auto import_require_impls_blocks() -> const SemIR::RequireImplsBlockStore& {
  194. return import_ir().require_impls_blocks();
  195. }
  196. auto import_specifics() -> const SemIR::SpecificStore& {
  197. return import_ir().specifics();
  198. }
  199. auto import_specific_interfaces() -> const SemIR::SpecificInterfaceStore& {
  200. return import_ir().specific_interfaces();
  201. }
  202. auto import_string_literal_values()
  203. -> const SharedValueStores::StringLiteralStore& {
  204. return import_ir().string_literal_values();
  205. }
  206. auto import_struct_type_fields() -> const SemIR::StructTypeFieldsStore& {
  207. return import_ir().struct_type_fields();
  208. }
  209. auto import_types() -> const SemIR::TypeStore& { return import_ir().types(); }
  210. // Returns the local file's import ID for the IR we are importing from.
  211. auto import_ir_id() -> SemIR::ImportIRId { return import_ir_id_; }
  212. // A value store for local constant values of imported instructions. This maps
  213. // from `InstId`s in the import IR to corresponding `ConstantId`s in the local
  214. // IR.
  215. auto local_constant_values_for_import_insts() -> SemIR::ConstantValueStore& {
  216. auto index = local_ir().import_irs().GetRawIndex(import_ir_id_);
  217. return local_context().import_ir_constant_values()[index];
  218. }
  219. // Returns the file we are importing into.
  220. auto local_ir() -> SemIR::File& { return context_->sem_ir(); }
  221. // Returns the type-checking context we are importing into.
  222. auto local_context() -> Context& { return *context_; }
  223. // Accessors into value stores of the file we are importing into.
  224. auto local_associated_constants() -> SemIR::AssociatedConstantStore& {
  225. return local_ir().associated_constants();
  226. }
  227. auto local_classes() -> SemIR::ClassStore& { return local_ir().classes(); }
  228. auto local_vtables() -> SemIR::VtableStore& { return local_ir().vtables(); }
  229. auto local_constant_values() -> SemIR::ConstantValueStore& {
  230. return local_ir().constant_values();
  231. }
  232. auto local_entity_names() -> SemIR::EntityNameStore& {
  233. return local_ir().entity_names();
  234. }
  235. auto local_facet_types() -> SemIR::FacetTypeInfoStore& {
  236. return local_ir().facet_types();
  237. }
  238. auto local_functions() -> SemIR::FunctionStore& {
  239. return local_ir().functions();
  240. }
  241. auto local_generics() -> SemIR::GenericStore& {
  242. return local_ir().generics();
  243. }
  244. auto local_identifiers() -> SharedValueStores::IdentifierStore& {
  245. return local_ir().identifiers();
  246. }
  247. auto local_impls() -> SemIR::ImplStore& { return local_ir().impls(); }
  248. auto local_import_ir_insts() -> SemIR::ImportIRInstStore& {
  249. return local_ir().import_ir_insts();
  250. }
  251. auto local_inst_blocks() -> SemIR::InstBlockStore& {
  252. return local_ir().inst_blocks();
  253. }
  254. auto local_insts() -> SemIR::InstStore& { return local_ir().insts(); }
  255. auto local_interfaces() -> SemIR::InterfaceStore& {
  256. return local_ir().interfaces();
  257. }
  258. auto local_named_constraints() -> SemIR::NamedConstraintStore& {
  259. return local_ir().named_constraints();
  260. }
  261. auto local_ints() -> SharedValueStores::IntStore& {
  262. return local_ir().ints();
  263. }
  264. auto local_name_scopes() -> SemIR::NameScopeStore& {
  265. return local_ir().name_scopes();
  266. }
  267. auto local_require_impls() -> SemIR::RequireImplsStore& {
  268. return local_ir().require_impls();
  269. }
  270. auto local_require_impls_blocks() -> SemIR::RequireImplsBlockStore& {
  271. return local_ir().require_impls_blocks();
  272. }
  273. auto local_specifics() -> SemIR::SpecificStore& {
  274. return local_ir().specifics();
  275. }
  276. auto local_specific_interfaces() -> SemIR::SpecificInterfaceStore& {
  277. return local_ir().specific_interfaces();
  278. }
  279. auto local_string_literal_values() -> SharedValueStores::StringLiteralStore& {
  280. return local_ir().string_literal_values();
  281. }
  282. auto local_struct_type_fields() -> SemIR::StructTypeFieldsStore& {
  283. return local_ir().struct_type_fields();
  284. }
  285. auto local_types() -> SemIR::TypeStore& { return local_ir().types(); }
  286. private:
  287. Context* context_;
  288. SemIR::ImportIRId import_ir_id_;
  289. const SemIR::File& import_ir_;
  290. };
  291. // Resolves an instruction from an imported IR into a constant referring to the
  292. // current IR.
  293. //
  294. // Calling Resolve on an instruction operates in an iterative manner, tracking
  295. // Work items on work_stack_. At a high level, the loop is:
  296. //
  297. // 1. If a constant value is already known for the work item and was not set by
  298. // this work item, it's considered resolved.
  299. // - The constant check avoids performance costs of deduplication on add.
  300. // - If we've processed this work item before, then we now process it again.
  301. // It didn't complete last time, even though we have a constant value
  302. // already.
  303. //
  304. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  305. // in three phases. The first and second phases can add work to the worklist
  306. // and end in a retry, in which case those phases will be rerun once the
  307. // added work is done. The rerun cannot also end in a retry, so this results
  308. // in at most three calls, but in practice one or two calls is almost always
  309. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  310. // it's important to only perform expensive work once, even when the same
  311. // phase is rerun.
  312. //
  313. // - First phase:
  314. // - Gather all input constants necessary to form the constant value of the
  315. // instruction. Gathering constants directly adds unresolved values to
  316. // work_stack_.
  317. // - If HasNewWork() reports that any work was added, then return Retry():
  318. // this instruction needs another call to complete. Gather the
  319. // now-resolved constants and continue to the next step once the retry
  320. // happens.
  321. //
  322. // - Second phase:
  323. // - Build the constant value of the instruction.
  324. // - Gather all input constants necessary to finish importing the
  325. // instruction. This is only necessary for instructions like classes that
  326. // can be forward-declared. For these instructions, we first import the
  327. // constant value and then later import the rest of the declaration in
  328. // order to break cycles.
  329. // - If HasNewWork() reports that any work was added, then return
  330. // Retry(constant_value): this instruction needs another call to
  331. // complete. Gather the now-resolved constants and continue to the next
  332. // step once the retry happens.
  333. //
  334. // - Third phase:
  335. // - After the second phase, the constant value for the instruction is
  336. // already set, and will be passed back into TryResolve*Inst on retry. It
  337. // should not be created again.
  338. // - Fill in any remaining information to complete the import of the
  339. // instruction. For example, when importing a class declaration, build
  340. // the class scope and information about the definition.
  341. // - Return Done() to finish the resolution process. This will cause the
  342. // Resolve loop to set a constant value if we didn't retry at the end of
  343. // the second phase.
  344. //
  345. // In the common case where the second phase cannot add new work (because the
  346. // inst doesn't represent a declaration of an entity that can be forward
  347. // declared), the second and third phases are usually expressed as a call to
  348. // ResolveResult::Deduplicated or ResolveResult::Unique.
  349. //
  350. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  351. // remain, and may no longer be at the top of the stack; update the state of
  352. // the work item to track what work still needs to be done.
  353. //
  354. // The same instruction can be enqueued for resolution multiple times. However,
  355. // we will only reach the second phase once: once a constant value is set, only
  356. // the resolution step that set it will retry.
  357. //
  358. // TODO: Fix class `extern` handling and merging, rewrite tests.
  359. // - check/testdata/class/cross_package_import.carbon
  360. // - check/testdata/class/extern.carbon
  361. // TODO: Fix function `extern` handling and merging, rewrite tests.
  362. // - check/testdata/function/declaration/import.carbon
  363. // - check/testdata/packages/cross_package_import.carbon
  364. class ImportRefResolver : public ImportContext {
  365. public:
  366. // `context` must not be null.
  367. explicit ImportRefResolver(Context* context, SemIR::ImportIRId import_ir_id)
  368. : ImportContext(context, import_ir_id) {}
  369. // Iteratively resolves an imported instruction's inner references until a
  370. // constant ID referencing the current IR is produced. See the class comment
  371. // for more details.
  372. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId;
  373. // Wraps constant evaluation with logic to handle constants.
  374. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId;
  375. // Wraps constant evaluation with logic to handle types.
  376. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId;
  377. // Returns true if new unresolved constants were found as part of this
  378. // `Resolve` step.
  379. auto HasNewWork() -> bool;
  380. // Pushes a specific onto the work stack. This will only process when the
  381. // current instruction is done, and does not count towards `HasNewWork`. We
  382. // add specifics this way because some instructions (e.g. `FacetTypeInfo`) can
  383. // add multiple specifics.
  384. //
  385. // The insert may do extra work moving already-added work on the work stack,
  386. // but that is expected to be okay because the common cases are 0 or 1
  387. // specifics being added. If this ends up showing up in profiles, potentially
  388. // due to vector growth, it may be worth revisiting.
  389. auto PushSpecific(SemIR::SpecificId import_id, SemIR::SpecificId local_id)
  390. -> void;
  391. // Returns the ConstantId for an InstId. Adds unresolved constants to
  392. // work_stack_.
  393. auto GetLocalConstantValueOrPush(SemIR::InstId inst_id) -> SemIR::ConstantId;
  394. private:
  395. // An instruction to import.
  396. struct InstWork {
  397. // The instruction to work on.
  398. SemIR::InstId inst_id;
  399. // Whether this work item set the constant value for the instruction and
  400. // requested a retry.
  401. bool retry_with_constant_value = false;
  402. };
  403. // A generic to import.
  404. struct GenericWork {
  405. SemIR::GenericId import_id;
  406. SemIR::GenericId local_id;
  407. };
  408. // A specific to import.
  409. struct SpecificWork {
  410. SemIR::SpecificId import_id;
  411. SemIR::SpecificId local_id;
  412. };
  413. // The constant found by FindResolvedConstId.
  414. struct ResolvedConstId {
  415. // The constant for the instruction. `None` if not yet resolved.
  416. SemIR::ConstantId const_id = SemIR::ConstantId::None;
  417. // Instructions which are indirect but equivalent to the current instruction
  418. // being resolved, and should have their constant set to the same. Empty
  419. // when `const_id` has a value.
  420. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  421. };
  422. // Looks to see if an instruction has been resolved. If a constant is only
  423. // found indirectly, sets the constant for any indirect steps that don't
  424. // already have the constant. If a constant isn't found, returns the indirect
  425. // instructions so that they can have the resolved constant assigned later.
  426. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId;
  427. // Sets a resolved constant into the current and indirect instructions.
  428. auto SetResolvedConstId(SemIR::InstId inst_id,
  429. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  430. SemIR::ConstantId const_id) -> void;
  431. llvm::SmallVector<std::variant<InstWork, GenericWork, SpecificWork>>
  432. work_stack_;
  433. // The size of work_stack_ at the start of resolving the current instruction.
  434. size_t initial_work_ = 0;
  435. };
  436. } // namespace
  437. // Wrapper for `AddImportRef` that provides the `import_ir_id`.
  438. static auto AddImportRef(ImportContext& context, SemIR::InstId inst_id,
  439. SemIR::EntityNameId entity_name_id =
  440. SemIR::EntityNameId::None) -> SemIR::InstId {
  441. if (!inst_id.has_value()) {
  442. return SemIR::InstId::None;
  443. }
  444. return AddImportRef(context.local_context(),
  445. SemIR::ImportIRInst(context.import_ir_id(), inst_id),
  446. entity_name_id);
  447. }
  448. // Handles setting a constant on instructions related to an import.
  449. static auto SetIndirectConstantValues(
  450. Context& context, llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  451. SemIR::ConstantId constant_id) -> void {
  452. for (const auto& import_ir_inst : indirect_insts) {
  453. auto ir_index =
  454. context.sem_ir().import_irs().GetRawIndex(import_ir_inst.ir_id());
  455. context.import_ir_constant_values()[ir_index].Set(import_ir_inst.inst_id(),
  456. constant_id);
  457. }
  458. }
  459. // Adds an import_ref instruction for an instruction that we have already loaded
  460. // from an imported IR, with a known constant value. This is useful when the
  461. // instruction has a symbolic constant value, in order to produce an instruction
  462. // that holds that symbolic constant.
  463. static auto AddLoadedImportRef(ImportContext& context,
  464. SemIR::TypeId local_type_id,
  465. SemIR::InstId import_inst_id,
  466. SemIR::ConstantId local_const_id)
  467. -> SemIR::InstId {
  468. auto import_ir_inst_id = context.local_import_ir_insts().Add(
  469. SemIR::ImportIRInst(context.import_ir_id(), import_inst_id));
  470. SemIR::ImportRefLoaded inst = {.type_id = local_type_id,
  471. .import_ir_inst_id = import_ir_inst_id,
  472. .entity_name_id = SemIR::EntityNameId::None};
  473. auto inst_id = AddPlaceholderImportedInstInNoBlock(
  474. context.local_context(),
  475. MakeImportedLocIdAndInst(context.local_context(), import_ir_inst_id,
  476. inst));
  477. context.local_constant_values().Set(inst_id, local_const_id);
  478. context.local_constant_values_for_import_insts().Set(import_inst_id,
  479. local_const_id);
  480. return inst_id;
  481. }
  482. // Like `AddLoadedImportRef`, but only for types, and returns a `TypeInstId`.
  483. static auto AddLoadedImportRefForType(ImportContext& context,
  484. SemIR::TypeInstId import_inst_id,
  485. SemIR::ConstantId local_const_id)
  486. -> SemIR::TypeInstId {
  487. return context.local_types().GetAsTypeInstId(AddLoadedImportRef(
  488. context, SemIR::TypeType::TypeId, import_inst_id, local_const_id));
  489. }
  490. static auto AddImportIRInst(ImportContext& context, SemIR::InstId inst_id)
  491. -> SemIR::ImportIRInstId {
  492. return context.local_import_ir_insts().Add(
  493. SemIR::ImportIRInst(context.import_ir_id(), inst_id));
  494. }
  495. // Computes, sets, and returns the constant value for an instruction.
  496. static auto SetConstantValue(Context& context, SemIR::InstId inst_id,
  497. SemIR::Inst inst) -> SemIR::ConstantId {
  498. auto const_id = TryEvalInstUnsafe(context, inst_id, inst);
  499. if (const_id.is_constant()) {
  500. CARBON_VLOG_TO(context.vlog_stream(), "Constant: {0} -> {1}\n", inst,
  501. context.constant_values().GetInstId(const_id));
  502. }
  503. context.constant_values().Set(inst_id, const_id);
  504. return const_id;
  505. }
  506. // Adds an imported instruction without setting its constant value. The
  507. // instruction should later be updated by either `SetConstantValue` or
  508. // `ReplacePlaceholderImportedInst`.
  509. template <typename InstT>
  510. static auto AddPlaceholderImportedInst(ImportContext& context,
  511. SemIR::InstId import_inst_id, InstT inst)
  512. -> SemIR::InstId {
  513. auto import_ir_inst_id = AddImportIRInst(context, import_inst_id);
  514. return AddPlaceholderImportedInstInNoBlock(
  515. context.local_context(),
  516. MakeImportedLocIdAndInst(context.local_context(), import_ir_inst_id,
  517. inst));
  518. }
  519. // Replace an imported instruction that was added by
  520. // `AddPlaceholderImportedInst` with a new instruction. Computes, sets, and
  521. // returns the new constant value.
  522. static auto ReplacePlaceholderImportedInst(ImportContext& context,
  523. SemIR::InstId inst_id,
  524. SemIR::Inst inst)
  525. -> SemIR::ConstantId {
  526. CARBON_VLOG_TO(context.local_context().vlog_stream(),
  527. "ReplaceImportedInst: {0} -> {1}\n", inst_id, inst);
  528. context.local_insts().Set(inst_id, inst);
  529. CARBON_CHECK(context.local_constant_values().Get(inst_id) ==
  530. SemIR::ConstantId::None);
  531. return SetConstantValue(context.local_context(), inst_id, inst);
  532. }
  533. // Returns the ConstantId for an InstId. Adds unresolved constants to
  534. // the resolver's work stack.
  535. static auto GetLocalConstantId(ImportRefResolver& resolver,
  536. SemIR::InstId inst_id) -> SemIR::ConstantId {
  537. return resolver.GetLocalConstantValueOrPush(inst_id);
  538. }
  539. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  540. // constants to the resolver's work stack.
  541. static auto GetLocalConstantId(ImportRefResolver& resolver,
  542. SemIR::ConstantId const_id)
  543. -> SemIR::ConstantId {
  544. return GetLocalConstantId(
  545. resolver, GetInstWithConstantValue(resolver.import_ir(), const_id));
  546. }
  547. // Returns the local constant InstId for an imported InstId.
  548. static auto GetLocalConstantInstId(ImportRefResolver& resolver,
  549. SemIR::InstId inst_id) -> SemIR::InstId {
  550. auto const_id = GetLocalConstantId(resolver, inst_id);
  551. return resolver.local_constant_values().GetInstIdIfValid(const_id);
  552. }
  553. // Returns the local constant InstId for an imported InstId.
  554. static auto GetLocalTypeInstId(ImportRefResolver& resolver,
  555. SemIR::TypeInstId inst_id) -> SemIR::TypeInstId {
  556. // The input instruction is a TypeInstId, and import does not change the type
  557. // of instructions, so the result is also a valid TypeInstId.
  558. return SemIR::TypeInstId::UnsafeMake(
  559. GetLocalConstantInstId(resolver, inst_id));
  560. }
  561. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  562. // work_stack_.
  563. static auto GetLocalConstantId(ImportRefResolver& resolver,
  564. SemIR::TypeId type_id) -> SemIR::ConstantId {
  565. return GetLocalConstantId(resolver,
  566. resolver.import_types().GetConstantId(type_id));
  567. }
  568. // Translates a NameId from the import IR to a local NameId.
  569. //
  570. // No new work is generated by calling this function.
  571. static auto GetLocalNameId(ImportContext& context, SemIR::NameId import_name_id)
  572. -> SemIR::NameId {
  573. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.has_value()) {
  574. return SemIR::NameId::ForIdentifier(context.local_identifiers().Add(
  575. context.import_identifiers().Get(ident_id)));
  576. }
  577. return import_name_id;
  578. }
  579. // Returns the id for a local symbolic EntityName from an imported one,
  580. // preserving only the `NameId`, the `CompileTimeBindIndex`, and whether it is a
  581. // template. Other parts of the EntityName are not kept and are not considered
  582. // part of the canonical EntityName (even if they are present there).
  583. //
  584. // No new work is generated by calling this function.
  585. static auto GetLocalSymbolicEntityNameId(
  586. ImportContext& context, SemIR::EntityNameId import_entity_name_id)
  587. -> SemIR::EntityNameId {
  588. const auto& import_entity_name =
  589. context.import_entity_names().Get(import_entity_name_id);
  590. auto name_id = GetLocalNameId(context, import_entity_name.name_id);
  591. return context.local_entity_names().AddSymbolicBindingName(
  592. name_id, SemIR::NameScopeId::None, import_entity_name.bind_index(),
  593. import_entity_name.is_template, import_entity_name.is_unused);
  594. }
  595. // Gets the local constant values corresponding to an imported inst block.
  596. static auto GetLocalInstBlockContents(ImportRefResolver& resolver,
  597. SemIR::InstBlockId import_block_id)
  598. -> llvm::SmallVector<SemIR::InstId> {
  599. llvm::SmallVector<SemIR::InstId> inst_ids;
  600. if (!import_block_id.has_value() ||
  601. import_block_id == SemIR::InstBlockId::Empty) {
  602. return inst_ids;
  603. }
  604. // Import all the values in the block.
  605. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  606. inst_ids.reserve(import_block.size());
  607. for (auto import_inst_id : import_block) {
  608. inst_ids.push_back(GetLocalConstantInstId(resolver, import_inst_id));
  609. }
  610. return inst_ids;
  611. }
  612. // Gets a local canonical instruction block ID corresponding to an imported inst
  613. // block whose contents were already imported, for example by
  614. // GetLocalInstBlockContents.
  615. static auto GetLocalCanonicalInstBlockId(ImportContext& context,
  616. SemIR::InstBlockId import_block_id,
  617. llvm::ArrayRef<SemIR::InstId> contents)
  618. -> SemIR::InstBlockId {
  619. if (!import_block_id.has_value()) {
  620. return SemIR::InstBlockId::None;
  621. }
  622. return context.local_inst_blocks().AddCanonical(contents);
  623. }
  624. // Imports the RequireImplsDecl instructions for each RequireImplsId in the
  625. // block, and gets the local RequireImplsIds from them. The returned vector is
  626. // only complete if there is no more work to do in the resolver on return.
  627. static auto GetLocalRequireImplsBlockContents(
  628. ImportRefResolver& resolver, SemIR::RequireImplsBlockId import_block_id)
  629. -> llvm::SmallVector<SemIR::RequireImplsId> {
  630. llvm::SmallVector<SemIR::RequireImplsId> require_decl_ids;
  631. if (!import_block_id.has_value() ||
  632. import_block_id == SemIR::RequireImplsBlockId::Empty) {
  633. return require_decl_ids;
  634. }
  635. // Import the RequireImplsDecl for each RequireImpls in the block.
  636. auto import_block =
  637. resolver.import_require_impls_blocks().Get(import_block_id);
  638. require_decl_ids.reserve(import_block.size());
  639. for (auto import_require_impls_id : import_block) {
  640. const auto& import_require =
  641. resolver.import_require_impls().Get(import_require_impls_id);
  642. auto local_decl_id =
  643. GetLocalConstantInstId(resolver, import_require.decl_id);
  644. // If `local_decl_id` is None, the resolver will have more work to do, and
  645. // we will call this function to try get all the decl instructions again.
  646. if (local_decl_id.has_value()) {
  647. // Importing the RequireImplsDecl instruction in `local_decl_id` also
  648. // imported the RequireImpls structure that it points to through the
  649. // RequireImplsId.
  650. require_decl_ids.push_back(
  651. resolver.local_insts()
  652. .GetAs<SemIR::RequireImplsDecl>(local_decl_id)
  653. .require_impls_id);
  654. }
  655. }
  656. return require_decl_ids;
  657. }
  658. // Gets the local block of RequireImplsIds from the imported block. Only valid
  659. // to call once there is no more work to do after the call to
  660. // GetLocalRequireImplsBlockContents().
  661. static auto GetLocalCanonicalRequireImplsBlockId(
  662. ImportContext& context, SemIR::RequireImplsBlockId import_block_id,
  663. llvm::ArrayRef<SemIR::RequireImplsId> contents)
  664. -> SemIR::RequireImplsBlockId {
  665. if (!import_block_id.has_value()) {
  666. return SemIR::RequireImplsBlockId::None;
  667. }
  668. return context.local_require_impls_blocks().Add(contents);
  669. }
  670. // Gets a local instruction block containing ImportRefs referring to the
  671. // instructions in the specified imported instruction block.
  672. static auto GetLocalImportRefInstBlock(ImportContext& context,
  673. SemIR::InstBlockId import_inst_block_id)
  674. -> SemIR::InstBlockId {
  675. llvm::SmallVector<SemIR::InstId> elements;
  676. auto import_elements = context.import_inst_blocks().Get(import_inst_block_id);
  677. elements.reserve(import_elements.size());
  678. for (auto element : import_elements) {
  679. elements.push_back(AddImportRef(context, element));
  680. }
  681. return context.local_inst_blocks().Add(elements);
  682. }
  683. // Gets an incomplete local version of an imported generic. Most fields are
  684. // set in the third phase.
  685. static auto ImportIncompleteGeneric(ImportContext& context,
  686. SemIR::InstId decl_id,
  687. SemIR::GenericId generic_id)
  688. -> SemIR::GenericId {
  689. if (!generic_id.has_value()) {
  690. return SemIR::GenericId::None;
  691. }
  692. return context.local_generics().Add(
  693. {.decl_id = decl_id,
  694. .bindings_id = SemIR::InstBlockId::None,
  695. .self_specific_id = SemIR::SpecificId::None});
  696. }
  697. namespace {
  698. // Local information associated with an imported generic.
  699. struct GenericData {
  700. struct Binding {
  701. // The attached type's constant, which may differ from the type on the
  702. // constant. This needs to be preserved for the ImportRef.
  703. SemIR::ConstantId type_constant_id;
  704. SemIR::ConstantId inst_constant_id;
  705. };
  706. llvm::SmallVector<Binding> bindings;
  707. llvm::SmallVector<SemIR::InstId> decl_block;
  708. };
  709. } // namespace
  710. // Gets a local version of the data associated with a generic. This is processed
  711. // through `ResolveResult::FinishGenericOrDone`.
  712. static auto GetLocalGenericData(ImportRefResolver& resolver,
  713. SemIR::GenericId import_generic_id)
  714. -> GenericData {
  715. GenericData generic_data;
  716. if (import_generic_id.has_value()) {
  717. const auto& import_generic =
  718. resolver.import_generics().Get(import_generic_id);
  719. if (import_generic.bindings_id.has_value()) {
  720. auto import_bindings =
  721. resolver.import_inst_blocks().Get(import_generic.bindings_id);
  722. generic_data.bindings.reserve(import_bindings.size());
  723. for (auto import_inst_id : import_bindings) {
  724. generic_data.bindings.push_back(
  725. {.type_constant_id = GetLocalConstantId(
  726. resolver,
  727. resolver.import_insts().GetAttachedType(import_inst_id)),
  728. .inst_constant_id = GetLocalConstantId(resolver, import_inst_id)});
  729. }
  730. }
  731. generic_data.decl_block =
  732. GetLocalInstBlockContents(resolver, import_generic.decl_block_id);
  733. }
  734. return generic_data;
  735. }
  736. // Rebuilds an eval block and sets locations.
  737. // TODO: Import the generic eval block rather than calling
  738. // RebuildGenericEvalBlock to rebuild it.
  739. static auto ResolveLocalEvalBlock(ImportContext& context,
  740. SemIR::InstBlockId import_block_id,
  741. llvm::ArrayRef<SemIR::InstId> local_block,
  742. SemIR::GenericId generic_id,
  743. SemIR::GenericInstIndex::Region region)
  744. -> SemIR::InstBlockId {
  745. auto eval_block_id = RebuildGenericEvalBlock(context.local_context(),
  746. generic_id, region, local_block);
  747. // Set the locations of the instructions in the inst block to match those of
  748. // the imported instructions.
  749. for (auto [import_inst_id, local_inst_id] :
  750. llvm::zip_equal(context.import_inst_blocks().Get(import_block_id),
  751. context.local_inst_blocks().Get(eval_block_id))) {
  752. auto import_ir_inst_id = AddImportIRInst(context, import_inst_id);
  753. context.local_insts().SetLocId(local_inst_id, import_ir_inst_id);
  754. }
  755. return eval_block_id;
  756. }
  757. // Adds the given local generic data to the given generic. This should only be
  758. // called by `ResolveResult`.
  759. static auto SetGenericDataForResolveResult(ImportContext& context,
  760. SemIR::GenericId import_generic_id,
  761. SemIR::GenericId new_generic_id,
  762. const GenericData& generic_data)
  763. -> void {
  764. if (!import_generic_id.has_value()) {
  765. return;
  766. }
  767. const auto& import_generic = context.import_generics().Get(import_generic_id);
  768. auto& new_generic = context.local_generics().Get(new_generic_id);
  769. auto import_bindings =
  770. context.import_inst_blocks().Get(import_generic.bindings_id);
  771. llvm::SmallVector<SemIR::InstId> new_bindings;
  772. new_bindings.reserve(import_bindings.size());
  773. for (auto [import_binding_id, binding] :
  774. llvm::zip_equal(import_bindings, generic_data.bindings)) {
  775. auto local_type_id = context.local_types().GetTypeIdForTypeConstantId(
  776. binding.type_constant_id);
  777. new_bindings.push_back(AddLoadedImportRef(
  778. context, local_type_id, import_binding_id, binding.inst_constant_id));
  779. }
  780. new_generic.bindings_id = context.local_inst_blocks().Add(new_bindings);
  781. new_generic.decl_block_id = ResolveLocalEvalBlock(
  782. context, import_generic.decl_block_id, generic_data.decl_block,
  783. new_generic_id, SemIR::GenericInstIndex::Region::Declaration);
  784. }
  785. // Gets a local constant value corresponding to an imported generic ID. May
  786. // add work to the work stack and return `None`.
  787. static auto GetLocalConstantId(ImportRefResolver& resolver,
  788. SemIR::GenericId generic_id)
  789. -> SemIR::ConstantId {
  790. if (!generic_id.has_value()) {
  791. return SemIR::ConstantId::None;
  792. }
  793. auto import_decl_inst_id = resolver.import_generics().Get(generic_id).decl_id;
  794. auto import_decl_inst =
  795. resolver.import_insts().GetWithAttachedType(import_decl_inst_id);
  796. if (import_decl_inst.IsOneOf<SemIR::ImplDecl, SemIR::InterfaceWithSelfDecl,
  797. SemIR::NamedConstraintWithSelfDecl,
  798. SemIR::RequireImplsDecl>()) {
  799. // For these decl types, the imported entity can be found via the
  800. // declaration's operands.
  801. return GetLocalConstantId(resolver, import_decl_inst_id);
  802. }
  803. // For all other kinds of declaration, the imported entity can be found via
  804. // the type of the declaration.
  805. CARBON_CHECK(import_decl_inst.type_id().has_value());
  806. return GetLocalConstantId(resolver, import_decl_inst.type_id());
  807. }
  808. // Gets a local generic ID given the corresponding local constant ID returned
  809. // by GetLocalConstantId for the imported generic. Does not add any new work.
  810. static auto GetLocalGenericId(ImportContext& context,
  811. SemIR::ConstantId local_const_id)
  812. -> SemIR::GenericId {
  813. if (!local_const_id.has_value()) {
  814. return SemIR::GenericId::None;
  815. }
  816. auto inst = context.local_insts().Get(
  817. context.local_constant_values().GetInstId(local_const_id));
  818. CARBON_KIND_SWITCH(inst) {
  819. case CARBON_KIND(SemIR::FunctionType fn_type): {
  820. return context.local_functions().Get(fn_type.function_id).generic_id;
  821. }
  822. case CARBON_KIND(SemIR::GenericClassType class_type): {
  823. return context.local_classes().Get(class_type.class_id).generic_id;
  824. }
  825. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  826. return context.local_interfaces()
  827. .Get(interface_type.interface_id)
  828. .generic_id;
  829. }
  830. case CARBON_KIND(SemIR::GenericNamedConstraintType constraint_type): {
  831. return context.local_named_constraints()
  832. .Get(constraint_type.named_constraint_id)
  833. .generic_id;
  834. }
  835. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  836. return context.local_impls().Get(impl_decl.impl_id).generic_id;
  837. }
  838. case CARBON_KIND(SemIR::InterfaceWithSelfDecl interface_with_self_decl): {
  839. return context.local_interfaces()
  840. .Get(interface_with_self_decl.interface_id)
  841. .generic_with_self_id;
  842. }
  843. case CARBON_KIND(
  844. SemIR::NamedConstraintWithSelfDecl constraint_with_self_decl): {
  845. return context.local_named_constraints()
  846. .Get(constraint_with_self_decl.named_constraint_id)
  847. .generic_with_self_id;
  848. }
  849. case CARBON_KIND(SemIR::RequireImplsDecl require_decl): {
  850. return context.local_require_impls()
  851. .Get(require_decl.require_impls_id)
  852. .generic_id;
  853. }
  854. default: {
  855. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  856. }
  857. }
  858. }
  859. namespace {
  860. // Local information associated with an imported specific.
  861. struct SpecificData {
  862. SemIR::ConstantId generic_const_id;
  863. llvm::SmallVector<SemIR::InstId> args;
  864. };
  865. } // namespace
  866. // Gets local information about an imported specific.
  867. static auto GetLocalSpecificData(ImportRefResolver& resolver,
  868. SemIR::SpecificId specific_id)
  869. -> SpecificData {
  870. if (!specific_id.has_value()) {
  871. return {.generic_const_id = SemIR::ConstantId::None, .args = {}};
  872. }
  873. const auto& specific = resolver.import_specifics().Get(specific_id);
  874. return {
  875. .generic_const_id = GetLocalConstantId(resolver, specific.generic_id),
  876. .args = GetLocalInstBlockContents(resolver, specific.args_id),
  877. };
  878. }
  879. // True for an already-imported specific.
  880. static auto IsSpecificImported(const SemIR::Specific& import_specific,
  881. const SemIR::Specific& local_specific) -> bool {
  882. return local_specific.decl_block_id.has_value() &&
  883. (local_specific.definition_block_id.has_value() ||
  884. !import_specific.definition_block_id.has_value());
  885. }
  886. // Gets a local specific whose data was already imported by
  887. // GetLocalSpecificData. This can add work through `PushSpecific`, but callers
  888. // shouldn't need to consider that because specifics are processed after the
  889. // current instruction.
  890. //
  891. // `local_generic_id` is provided when this is used for a generic's `self`
  892. // specific, where `GetLocalGenericId` won't work because `generic_const_id` can
  893. // be `TypeType`.
  894. static auto GetOrAddLocalSpecific(
  895. ImportRefResolver& resolver, SemIR::SpecificId import_specific_id,
  896. const SpecificData& data,
  897. SemIR::GenericId local_generic_id = SemIR::GenericId::None)
  898. -> SemIR::SpecificId {
  899. if (!import_specific_id.has_value()) {
  900. return SemIR::SpecificId::None;
  901. }
  902. // Form a corresponding local specific ID.
  903. const auto& import_specific =
  904. resolver.import_specifics().Get(import_specific_id);
  905. if (!local_generic_id.has_value()) {
  906. local_generic_id = GetLocalGenericId(resolver, data.generic_const_id);
  907. }
  908. auto args_id = GetLocalCanonicalInstBlockId(resolver, import_specific.args_id,
  909. data.args);
  910. // Get the specific.
  911. auto local_specific_id =
  912. resolver.local_specifics().GetOrAdd(local_generic_id, args_id);
  913. if (!IsSpecificImported(import_specific,
  914. resolver.local_specifics().Get(local_specific_id))) {
  915. // Enqueue the specific to fill in remaining fields.
  916. resolver.PushSpecific(import_specific_id, local_specific_id);
  917. }
  918. return local_specific_id;
  919. }
  920. // Given a generic that's gone through the initial setup with `GenericData`,
  921. // finish the import.
  922. static auto TryFinishGeneric(ImportRefResolver& resolver,
  923. SemIR::GenericId import_generic_id,
  924. SemIR::GenericId local_generic_id) -> bool {
  925. const auto& import_generic =
  926. resolver.import_generics().Get(import_generic_id);
  927. auto specific_data =
  928. GetLocalSpecificData(resolver, import_generic.self_specific_id);
  929. llvm::SmallVector<SemIR::InstId> definition_block;
  930. if (import_generic.definition_block_id.has_value()) {
  931. definition_block =
  932. GetLocalInstBlockContents(resolver, import_generic.definition_block_id);
  933. }
  934. if (resolver.HasNewWork()) {
  935. return false;
  936. }
  937. auto& local_generic = resolver.local_generics().Get(local_generic_id);
  938. CARBON_CHECK(!local_generic.self_specific_id.has_value(),
  939. "Currently assuming we can't find a GenericId multiple ways");
  940. local_generic.self_specific_id =
  941. GetOrAddLocalSpecific(resolver, import_generic.self_specific_id,
  942. specific_data, local_generic_id);
  943. if (import_generic.definition_block_id.has_value()) {
  944. local_generic.definition_block_id = ResolveLocalEvalBlock(
  945. resolver, import_generic.definition_block_id, definition_block,
  946. local_generic_id, SemIR::GenericInstIndex::Region::Definition);
  947. }
  948. return true;
  949. }
  950. // Given a specific that's gone through the initial setup with `SpecificData`,
  951. // finish the import.
  952. static auto TryFinishSpecific(ImportRefResolver& resolver,
  953. SemIR::SpecificId import_specific_id,
  954. SemIR::SpecificId local_specific_id) -> bool {
  955. const auto& import_specific =
  956. resolver.import_specifics().Get(import_specific_id);
  957. auto& local_specific = resolver.local_specifics().Get(local_specific_id);
  958. if (IsSpecificImported(import_specific, local_specific)) {
  959. return true;
  960. }
  961. llvm::SmallVector<SemIR::InstId> decl_block;
  962. if (!local_specific.decl_block_id.has_value()) {
  963. decl_block =
  964. GetLocalInstBlockContents(resolver, import_specific.decl_block_id);
  965. }
  966. auto definition_block =
  967. GetLocalInstBlockContents(resolver, import_specific.definition_block_id);
  968. if (resolver.HasNewWork()) {
  969. return false;
  970. }
  971. if (!local_specific.decl_block_id.has_value()) {
  972. local_specific.decl_block_id = GetLocalCanonicalInstBlockId(
  973. resolver, import_specific.decl_block_id, decl_block);
  974. }
  975. local_specific.definition_block_id = GetLocalCanonicalInstBlockId(
  976. resolver, import_specific.definition_block_id, definition_block);
  977. return true;
  978. }
  979. namespace {
  980. struct SpecificInterfaceData {
  981. SemIR::ConstantId interface_const_id;
  982. SpecificData specific_data;
  983. };
  984. } // namespace
  985. static auto GetLocalSpecificInterfaceData(
  986. ImportRefResolver& resolver, SemIR::SpecificInterface import_interface)
  987. -> SpecificInterfaceData {
  988. SemIR::ConstantId interface_const_id = SemIR::ConstantId::None;
  989. if (import_interface.interface_id.has_value()) {
  990. interface_const_id =
  991. GetLocalConstantId(resolver, resolver.import_interfaces()
  992. .Get(import_interface.interface_id)
  993. .first_owning_decl_id);
  994. }
  995. return {.interface_const_id = interface_const_id,
  996. .specific_data =
  997. GetLocalSpecificData(resolver, import_interface.specific_id)};
  998. }
  999. static auto GetLocalSpecificInterface(
  1000. ImportRefResolver& resolver,
  1001. SemIR::SpecificInterface import_specific_interface,
  1002. SpecificInterfaceData interface_data) -> SemIR::SpecificInterface {
  1003. if (!interface_data.interface_const_id.has_value()) {
  1004. return SemIR::SpecificInterface::None;
  1005. }
  1006. // Find the corresponding interface type. For a non-generic interface,
  1007. // this is the type of the interface declaration. For a generic interface,
  1008. // build a interface type referencing this specialization of the generic
  1009. // interface.
  1010. auto interface_const_inst =
  1011. resolver.local_insts().Get(resolver.local_constant_values().GetInstId(
  1012. interface_data.interface_const_id));
  1013. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  1014. const SemIR::FacetTypeInfo& new_facet_type_info =
  1015. resolver.local_facet_types().Get(facet_type->facet_type_id);
  1016. return std::get<SemIR::SpecificInterface>(
  1017. *new_facet_type_info.TryAsSingleExtend());
  1018. } else {
  1019. auto generic_interface_type =
  1020. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  1021. interface_const_inst.type_id());
  1022. auto specific_id =
  1023. GetOrAddLocalSpecific(resolver, import_specific_interface.specific_id,
  1024. interface_data.specific_data);
  1025. return {generic_interface_type.interface_id, specific_id};
  1026. }
  1027. }
  1028. namespace {
  1029. struct SpecificNamedConstraintData {
  1030. SemIR::ConstantId constraint_const_id;
  1031. SpecificData specific_data;
  1032. };
  1033. } // namespace
  1034. static auto GetLocalSpecificNamedConstraintData(
  1035. ImportRefResolver& resolver,
  1036. SemIR::SpecificNamedConstraint import_constraint)
  1037. -> SpecificNamedConstraintData {
  1038. SemIR::ConstantId constraint_const_id = SemIR::ConstantId::None;
  1039. if (import_constraint.named_constraint_id.has_value()) {
  1040. constraint_const_id = GetLocalConstantId(
  1041. resolver, resolver.import_named_constraints()
  1042. .Get(import_constraint.named_constraint_id)
  1043. .first_owning_decl_id);
  1044. }
  1045. return {.constraint_const_id = constraint_const_id,
  1046. .specific_data =
  1047. GetLocalSpecificData(resolver, import_constraint.specific_id)};
  1048. }
  1049. static auto GetLocalSpecificNamedConstraint(
  1050. ImportRefResolver& resolver,
  1051. SemIR::SpecificNamedConstraint import_specific_constraint,
  1052. SpecificNamedConstraintData constraint_data)
  1053. -> SemIR::SpecificNamedConstraint {
  1054. if (!constraint_data.constraint_const_id.has_value()) {
  1055. return SemIR::SpecificNamedConstraint::None;
  1056. }
  1057. // Find the corresponding named constraint type. For a non-generic constraint,
  1058. // this is the type of the named constraint declaration. For a generic
  1059. // constraint, build a named constraint type referencing this specialization
  1060. // of the generic named constraint.
  1061. auto constraint_const_inst =
  1062. resolver.local_insts().Get(resolver.local_constant_values().GetInstId(
  1063. constraint_data.constraint_const_id));
  1064. if (auto facet_type = constraint_const_inst.TryAs<SemIR::FacetType>()) {
  1065. const SemIR::FacetTypeInfo& new_facet_type_info =
  1066. resolver.local_facet_types().Get(facet_type->facet_type_id);
  1067. return std::get<SemIR::SpecificNamedConstraint>(
  1068. *new_facet_type_info.TryAsSingleExtend());
  1069. } else {
  1070. auto generic_constraint_type =
  1071. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  1072. constraint_const_inst.type_id());
  1073. auto specific_id =
  1074. GetOrAddLocalSpecific(resolver, import_specific_constraint.specific_id,
  1075. constraint_data.specific_data);
  1076. return {generic_constraint_type.named_constraint_id, specific_id};
  1077. }
  1078. }
  1079. static auto GetLocalNameScopeIdImpl(ImportRefResolver& resolver,
  1080. SemIR::ConstantId const_id)
  1081. -> SemIR::NameScopeId {
  1082. if (!const_id.has_value()) {
  1083. return SemIR::NameScopeId::None;
  1084. }
  1085. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  1086. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  1087. CARBON_KIND_SWITCH(name_scope_inst) {
  1088. case CARBON_KIND(SemIR::Namespace inst): {
  1089. return inst.name_scope_id;
  1090. }
  1091. case CARBON_KIND(SemIR::ClassType inst): {
  1092. return resolver.local_classes().Get(inst.class_id).scope_id;
  1093. }
  1094. case CARBON_KIND(SemIR::FacetType inst): {
  1095. const SemIR::FacetTypeInfo& facet_type_info =
  1096. resolver.local_facet_types().Get(inst.facet_type_id);
  1097. if (auto single = facet_type_info.TryAsSingleExtend()) {
  1098. // This is the facet type produced by an interface or named constraint
  1099. // declaration.
  1100. CARBON_KIND_SWITCH(*single) {
  1101. case CARBON_KIND(SemIR::SpecificInterface interface): {
  1102. return resolver.local_interfaces()
  1103. .Get(interface.interface_id)
  1104. .scope_without_self_id;
  1105. }
  1106. case CARBON_KIND(SemIR::SpecificNamedConstraint constraint): {
  1107. return resolver.local_named_constraints()
  1108. .Get(constraint.named_constraint_id)
  1109. .scope_without_self_id;
  1110. }
  1111. }
  1112. }
  1113. break;
  1114. }
  1115. case CARBON_KIND(SemIR::ImplDecl inst): {
  1116. return resolver.local_impls().Get(inst.impl_id).scope_id;
  1117. }
  1118. case CARBON_KIND(SemIR::InterfaceWithSelfDecl interface_with_self): {
  1119. return resolver.local_interfaces()
  1120. .Get(interface_with_self.interface_id)
  1121. .scope_with_self_id;
  1122. }
  1123. case CARBON_KIND(SemIR::NamedConstraintWithSelfDecl constraint_with_self): {
  1124. return resolver.local_named_constraints()
  1125. .Get(constraint_with_self.named_constraint_id)
  1126. .scope_with_self_id;
  1127. }
  1128. case SemIR::StructValue::Kind: {
  1129. auto type_inst =
  1130. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  1131. CARBON_KIND_SWITCH(type_inst) {
  1132. case CARBON_KIND(SemIR::GenericClassType inst): {
  1133. return resolver.local_classes().Get(inst.class_id).scope_id;
  1134. }
  1135. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  1136. return resolver.local_interfaces()
  1137. .Get(inst.interface_id)
  1138. .scope_without_self_id;
  1139. }
  1140. case CARBON_KIND(SemIR::GenericNamedConstraintType inst): {
  1141. return resolver.local_named_constraints()
  1142. .Get(inst.named_constraint_id)
  1143. .scope_without_self_id;
  1144. }
  1145. default: {
  1146. break;
  1147. }
  1148. }
  1149. break;
  1150. }
  1151. default: {
  1152. if (const_inst_id == SemIR::ErrorInst::InstId) {
  1153. return SemIR::NameScopeId::None;
  1154. }
  1155. break;
  1156. }
  1157. }
  1158. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  1159. name_scope_inst);
  1160. }
  1161. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  1162. // unresolved constants to the resolver's work stack.
  1163. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  1164. SemIR::NameScopeId name_scope_id)
  1165. -> SemIR::NameScopeId {
  1166. // Get the instruction that created the scope.
  1167. auto [inst_id, inst] =
  1168. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  1169. if (!inst) {
  1170. // Map scopes that aren't associated with an instruction to `None`. For now,
  1171. // such scopes aren't used, and we don't have a good way to remap them.
  1172. return SemIR::NameScopeId::None;
  1173. }
  1174. // Get the constant value for the scope.
  1175. auto const_id = GetLocalConstantId(resolver, inst_id);
  1176. if (!const_id.has_value()) {
  1177. return SemIR::NameScopeId::None;
  1178. }
  1179. auto result = GetLocalNameScopeIdImpl(resolver, const_id);
  1180. CARBON_CHECK(result.has_value());
  1181. return result;
  1182. }
  1183. // Given an imported entity base, returns an incomplete, local version of it.
  1184. //
  1185. // Most fields are set in the third phase once they're imported. Import enough
  1186. // of the parameter lists that we know whether this interface is a generic
  1187. // interface and can build the right constant value for it.
  1188. //
  1189. // TODO: Support extern.
  1190. static auto GetIncompleteLocalEntityBase(
  1191. ImportContext& context, SemIR::InstId decl_id,
  1192. const SemIR::EntityWithParamsBase& import_base)
  1193. -> SemIR::EntityWithParamsBase {
  1194. // Translate the extern_library_id if present.
  1195. auto extern_library_id = SemIR::LibraryNameId::None;
  1196. if (import_base.extern_library_id.has_value()) {
  1197. if (import_base.extern_library_id.index >= 0) {
  1198. auto val = context.import_string_literal_values().Get(
  1199. import_base.extern_library_id.AsStringLiteralValueId());
  1200. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  1201. context.local_string_literal_values().Add(val));
  1202. } else {
  1203. extern_library_id = import_base.extern_library_id;
  1204. }
  1205. }
  1206. return {
  1207. .name_id = GetLocalNameId(context, import_base.name_id),
  1208. .parent_scope_id = SemIR::NameScopeId::None,
  1209. .generic_id =
  1210. ImportIncompleteGeneric(context, decl_id, import_base.generic_id),
  1211. .first_param_node_id = Parse::NodeId::None,
  1212. .last_param_node_id = Parse::NodeId::None,
  1213. .pattern_block_id = SemIR::InstBlockId::None,
  1214. .implicit_param_patterns_id =
  1215. import_base.implicit_param_patterns_id.has_value()
  1216. ? SemIR::InstBlockId::Empty
  1217. : SemIR::InstBlockId::None,
  1218. .param_patterns_id = import_base.param_patterns_id.has_value()
  1219. ? SemIR::InstBlockId::Empty
  1220. : SemIR::InstBlockId::None,
  1221. .is_extern = import_base.is_extern,
  1222. .extern_library_id = extern_library_id,
  1223. .non_owning_decl_id = import_base.non_owning_decl_id.has_value()
  1224. ? decl_id
  1225. : SemIR::InstId::None,
  1226. .first_owning_decl_id = import_base.first_owning_decl_id.has_value()
  1227. ? decl_id
  1228. : SemIR::InstId::None,
  1229. };
  1230. }
  1231. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1232. // lookup.
  1233. static auto AddNameScopeImportRefs(ImportContext& context,
  1234. const SemIR::NameScope& import_scope,
  1235. SemIR::NameScope& new_scope) -> void {
  1236. for (auto entry : import_scope.entries()) {
  1237. SemIR::ScopeLookupResult result = entry.result;
  1238. if (result.is_poisoned()) {
  1239. continue;
  1240. }
  1241. auto ref_id = AddImportRef(context, result.target_inst_id());
  1242. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1243. .result = SemIR::ScopeLookupResult::MakeFound(
  1244. ref_id, result.access_kind())});
  1245. }
  1246. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1247. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1248. }
  1249. }
  1250. // Given a block ID for a list of associated entities of a witness, returns a
  1251. // version localized to the current IR.
  1252. static auto AddAssociatedEntities(ImportContext& context,
  1253. SemIR::NameScopeId local_name_scope_id,
  1254. SemIR::InstBlockId associated_entities_id)
  1255. -> SemIR::InstBlockId {
  1256. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1257. return SemIR::InstBlockId::Empty;
  1258. }
  1259. auto associated_entities =
  1260. context.import_inst_blocks().Get(associated_entities_id);
  1261. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1262. new_associated_entities.reserve(associated_entities.size());
  1263. for (auto inst_id : associated_entities) {
  1264. // Determine the name of the associated entity, by switching on its kind.
  1265. SemIR::NameId import_name_id = SemIR::NameId::None;
  1266. if (auto assoc_const_decl =
  1267. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1268. inst_id)) {
  1269. const auto& assoc_const = context.import_associated_constants().Get(
  1270. assoc_const_decl->assoc_const_id);
  1271. import_name_id = assoc_const.name_id;
  1272. } else if (auto function_decl =
  1273. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1274. inst_id)) {
  1275. const auto& function =
  1276. context.import_functions().Get(function_decl->function_id);
  1277. import_name_id = function.name_id;
  1278. } else if (auto import_ref =
  1279. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1280. inst_id)) {
  1281. import_name_id =
  1282. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1283. } else {
  1284. // We don't need `GetWithAttachedType` here because we don't access the
  1285. // type.
  1286. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1287. context.import_insts().Get(inst_id).kind());
  1288. }
  1289. auto name_id = GetLocalNameId(context, import_name_id);
  1290. auto entity_name_id = context.local_entity_names().Add(
  1291. {.name_id = name_id, .parent_scope_id = local_name_scope_id});
  1292. new_associated_entities.push_back(
  1293. AddImportRef(context, inst_id, entity_name_id));
  1294. }
  1295. return context.local_inst_blocks().Add(new_associated_entities);
  1296. }
  1297. namespace {
  1298. namespace Internal {
  1299. // Internal concept for instruction kinds that produce unique constants.
  1300. template <typename InstT>
  1301. concept HasUniqueConstantKind =
  1302. InstT::Kind.constant_kind() == SemIR::InstConstantKind::AlwaysUnique ||
  1303. InstT::Kind.constant_kind() == SemIR::InstConstantKind::ConditionalUnique;
  1304. } // namespace Internal
  1305. // The result of attempting to resolve an imported instruction to a constant.
  1306. struct ResolveResult {
  1307. // The new constant value, if known.
  1308. SemIR::ConstantId const_id;
  1309. // Newly created declaration whose value is being resolved, if any.
  1310. SemIR::InstId decl_id = SemIR::InstId::None;
  1311. // Whether resolution has been attempted once and needs to be retried.
  1312. bool retry = false;
  1313. // If a generic needs to be resolved, the generic information.
  1314. struct ResolveGeneric {
  1315. SemIR::GenericId import_generic_id = SemIR::GenericId::None;
  1316. SemIR::GenericId local_generic_id = SemIR::GenericId::None;
  1317. };
  1318. std::array<ResolveGeneric, 2> resolve_generic;
  1319. // Produces a resolve result that tries resolving this instruction again. If
  1320. // `const_id` is specified, then this is the end of the second phase, and the
  1321. // constant value will be passed to the next resolution attempt. Otherwise,
  1322. // this is the end of the first phase.
  1323. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::None,
  1324. SemIR::InstId decl_id = SemIR::InstId::None)
  1325. -> ResolveResult {
  1326. return {.const_id = const_id, .decl_id = decl_id, .retry = true};
  1327. }
  1328. // Produces a resolve result that provides the given constant value. Requires
  1329. // that there is no new work.
  1330. static auto Done(SemIR::ConstantId const_id,
  1331. SemIR::InstId decl_id = SemIR::InstId::None)
  1332. -> ResolveResult {
  1333. return {.const_id = const_id, .decl_id = decl_id};
  1334. }
  1335. // Produces a resolve result that provides the given constant value. Retries
  1336. // instead if work has been added.
  1337. static auto RetryOrDone(ImportRefResolver& resolver,
  1338. SemIR::ConstantId const_id) -> ResolveResult {
  1339. if (resolver.HasNewWork()) {
  1340. return Retry();
  1341. }
  1342. return Done(const_id);
  1343. }
  1344. // If there's no generic, this is equivalent to `Done`. If there is a generic,
  1345. // it's still done, but the fetched generic data is processed and the generic
  1346. // is enqueued for further work.
  1347. //
  1348. // It's not valid to have a generic-with-self but no base generic.
  1349. static auto FinishGenericOrDone(ImportRefResolver& resolver,
  1350. SemIR::ConstantId const_id,
  1351. SemIR::InstId decl_id,
  1352. SemIR::GenericId import_generic_id,
  1353. SemIR::GenericId local_generic_id,
  1354. GenericData generic_data) -> ResolveResult {
  1355. auto result = Done(const_id, decl_id);
  1356. if (import_generic_id.has_value()) {
  1357. SetGenericDataForResolveResult(resolver, import_generic_id,
  1358. local_generic_id, generic_data);
  1359. result.resolve_generic[0].import_generic_id = import_generic_id;
  1360. result.resolve_generic[0].local_generic_id = local_generic_id;
  1361. }
  1362. return result;
  1363. }
  1364. // Adds `inst` to the local context as a deduplicated constant and returns a
  1365. // successful `ResolveResult`. Requires that there is no new work.
  1366. //
  1367. // This implements phases 2 and 3 of resolving the inst (as described on
  1368. // `ImportRefResolver`) for the common case where those phases are combined.
  1369. // Cases where that isn't applicable should instead use
  1370. // `AddPlaceholderImportedInst` and `ReplacePlaceholderImportedInst`.
  1371. //
  1372. // This should not be used for instructions that represent declarations, or
  1373. // other instructions with `constant_kind == InstConstantKind::Unique`,
  1374. // because they should not be deduplicated.
  1375. template <typename InstT>
  1376. requires(!Internal::HasUniqueConstantKind<InstT>)
  1377. static auto Deduplicated(ImportRefResolver& resolver, InstT inst)
  1378. -> ResolveResult {
  1379. CARBON_CHECK(!resolver.HasNewWork());
  1380. // AddImportedConstant produces an unattached constant, so its type must
  1381. // be unattached as well.
  1382. inst.type_id = resolver.local_types().GetUnattachedType(inst.type_id);
  1383. auto const_id = AddImportedConstant(resolver.local_context(), inst);
  1384. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1385. return Done(const_id);
  1386. }
  1387. // Adds `inst` to the local context as a unique constant and returns a
  1388. // successful `ResolveResult`. `import_inst_id` is the corresponding inst ID
  1389. // in the local context. Requires that there is no new work.
  1390. //
  1391. // This implements phases 2 and 3 of resolving the inst (as described on
  1392. // `ImportRefResolver`) for the common case where those phases are combined.
  1393. // Cases where that isn't applicable should instead use
  1394. // `AddPlaceholderImportedInst` and `ReplacePlaceholderImportedInst`.
  1395. //
  1396. // This should only be used for instructions that represent declarations, or
  1397. // other instructions with `constant_kind == InstConstantKind::Unique`,
  1398. // because it does not perform deduplication.
  1399. template <typename InstT>
  1400. requires Internal::HasUniqueConstantKind<InstT>
  1401. static auto Unique(ImportRefResolver& resolver, SemIR::InstId import_inst_id,
  1402. InstT inst) -> ResolveResult {
  1403. CARBON_CHECK(!resolver.HasNewWork());
  1404. auto inst_id = AddPlaceholderImportedInst(resolver, import_inst_id, inst);
  1405. auto const_id = SetConstantValue(resolver.local_context(), inst_id, inst);
  1406. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1407. return Done(const_id, inst_id);
  1408. }
  1409. };
  1410. } // namespace
  1411. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1412. SemIR::AdaptDecl inst,
  1413. SemIR::InstId import_inst_id) -> ResolveResult {
  1414. auto adapted_type_const_id =
  1415. GetLocalConstantId(resolver, inst.adapted_type_inst_id);
  1416. if (resolver.HasNewWork()) {
  1417. return ResolveResult::Retry();
  1418. }
  1419. auto adapted_type_inst_id = AddLoadedImportRefForType(
  1420. resolver, inst.adapted_type_inst_id, adapted_type_const_id);
  1421. // Create a corresponding instruction to represent the declaration.
  1422. return ResolveResult::Unique<SemIR::AdaptDecl>(
  1423. resolver, import_inst_id, {.adapted_type_inst_id = adapted_type_inst_id});
  1424. }
  1425. template <typename ParamPatternT>
  1426. requires SemIR::Internal::HasInstCategory<SemIR::AnyParamPattern,
  1427. ParamPatternT>
  1428. static auto TryResolveTypedInst(ImportRefResolver& resolver, ParamPatternT inst,
  1429. SemIR::InstId import_inst_id) -> ResolveResult {
  1430. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1431. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  1432. if (resolver.HasNewWork()) {
  1433. return ResolveResult::Retry();
  1434. }
  1435. return ResolveResult::Unique<ParamPatternT>(
  1436. resolver, import_inst_id,
  1437. {.type_id =
  1438. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1439. .subpattern_id = subpattern_id,
  1440. .index = inst.index});
  1441. }
  1442. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1443. SemIR::ArrayType inst) -> ResolveResult {
  1444. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1445. auto element_type_inst_id =
  1446. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  1447. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1448. if (resolver.HasNewWork()) {
  1449. return ResolveResult::Retry();
  1450. }
  1451. return ResolveResult::Deduplicated<SemIR::ArrayType>(
  1452. resolver, {.type_id = SemIR::TypeType::TypeId,
  1453. .bound_id = bound_id,
  1454. .element_type_inst_id = element_type_inst_id});
  1455. }
  1456. static auto ImportAssociatedConstant(
  1457. ImportContext& context, const SemIR::AssociatedConstant& import_assoc_const,
  1458. SemIR::TypeId type_id)
  1459. -> std::pair<SemIR::AssociatedConstantId, SemIR::ConstantId> {
  1460. SemIR::AssociatedConstantDecl assoc_const_decl = {
  1461. .type_id = type_id,
  1462. .assoc_const_id = SemIR::AssociatedConstantId::None,
  1463. .decl_block_id = SemIR::InstBlockId::Empty};
  1464. auto assoc_const_decl_id = AddPlaceholderImportedInst(
  1465. context, import_assoc_const.decl_id, assoc_const_decl);
  1466. assoc_const_decl.assoc_const_id = context.local_associated_constants().Add({
  1467. .name_id = GetLocalNameId(context, import_assoc_const.name_id),
  1468. .parent_scope_id = SemIR::NameScopeId::None,
  1469. .decl_id = assoc_const_decl_id,
  1470. .default_value_id =
  1471. import_assoc_const.default_value_id.has_value()
  1472. ? AddImportRef(context, import_assoc_const.default_value_id)
  1473. : SemIR::InstId::None,
  1474. });
  1475. // Write the associated constant ID into the AssociatedConstantDecl.
  1476. auto const_id = ReplacePlaceholderImportedInst(context, assoc_const_decl_id,
  1477. assoc_const_decl);
  1478. return {assoc_const_decl.assoc_const_id, const_id};
  1479. }
  1480. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1481. SemIR::AssociatedConstantDecl inst,
  1482. SemIR::ConstantId const_id) -> ResolveResult {
  1483. const auto& import_assoc_const =
  1484. resolver.import_associated_constants().Get(inst.assoc_const_id);
  1485. SemIR::AssociatedConstantId assoc_const_id =
  1486. SemIR::AssociatedConstantId::None;
  1487. if (!const_id.has_value()) {
  1488. // In the first phase, import the type of the associated constant.
  1489. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1490. if (resolver.HasNewWork()) {
  1491. return ResolveResult::Retry();
  1492. }
  1493. // In the second phase, create the associated constant and its declaration.
  1494. auto type_id =
  1495. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id);
  1496. std::tie(assoc_const_id, const_id) =
  1497. ImportAssociatedConstant(resolver, import_assoc_const, type_id);
  1498. } else {
  1499. // In the third phase, compute the associated constant ID from the constant
  1500. // value of the declaration.
  1501. assoc_const_id =
  1502. resolver.local_insts()
  1503. .GetAs<SemIR::AssociatedConstantDecl>(
  1504. resolver.local_constant_values().GetInstId(const_id))
  1505. .assoc_const_id;
  1506. }
  1507. // Load the values to populate the entity with.
  1508. auto parent_scope_id =
  1509. GetLocalNameScopeId(resolver, import_assoc_const.parent_scope_id);
  1510. auto& new_assoc_const =
  1511. resolver.local_associated_constants().Get(assoc_const_id);
  1512. if (resolver.HasNewWork()) {
  1513. return ResolveResult::Retry(const_id, new_assoc_const.decl_id);
  1514. }
  1515. // Populate the entity.
  1516. new_assoc_const.parent_scope_id = parent_scope_id;
  1517. return ResolveResult::Done(const_id, new_assoc_const.decl_id);
  1518. }
  1519. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1520. SemIR::AssociatedEntity inst) -> ResolveResult {
  1521. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1522. if (resolver.HasNewWork()) {
  1523. return ResolveResult::Retry();
  1524. }
  1525. // Add a lazy reference to the target declaration.
  1526. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1527. return ResolveResult::Deduplicated<SemIR::AssociatedEntity>(
  1528. resolver, {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(
  1529. type_const_id),
  1530. .index = inst.index,
  1531. .decl_id = decl_id});
  1532. }
  1533. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1534. SemIR::AssociatedEntityType inst)
  1535. -> ResolveResult {
  1536. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1537. auto data =
  1538. GetLocalSpecificInterfaceData(resolver, inst.GetSpecificInterface());
  1539. if (resolver.HasNewWork()) {
  1540. return ResolveResult::Retry();
  1541. }
  1542. auto specific_interface =
  1543. GetLocalSpecificInterface(resolver, inst.GetSpecificInterface(), data);
  1544. return ResolveResult::Deduplicated<SemIR::AssociatedEntityType>(
  1545. resolver,
  1546. {.type_id = SemIR::TypeType::TypeId,
  1547. .interface_id = specific_interface.interface_id,
  1548. .interface_without_self_specific_id = specific_interface.specific_id});
  1549. }
  1550. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1551. SemIR::BaseDecl inst,
  1552. SemIR::InstId import_inst_id) -> ResolveResult {
  1553. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1554. auto base_type_const_id =
  1555. GetLocalConstantId(resolver, inst.base_type_inst_id);
  1556. if (resolver.HasNewWork()) {
  1557. return ResolveResult::Retry();
  1558. }
  1559. auto base_type_inst_id = AddLoadedImportRefForType(
  1560. resolver, inst.base_type_inst_id, base_type_const_id);
  1561. // Create a corresponding instruction to represent the declaration.
  1562. return ResolveResult::Unique<SemIR::BaseDecl>(
  1563. resolver, import_inst_id,
  1564. {.type_id =
  1565. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1566. .base_type_inst_id = base_type_inst_id,
  1567. .index = inst.index});
  1568. }
  1569. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1570. SemIR::AliasBinding inst) -> ResolveResult {
  1571. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1572. return ResolveResult::RetryOrDone(resolver, value_id);
  1573. }
  1574. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1575. SemIR::SymbolicBinding inst) -> ResolveResult {
  1576. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1577. if (resolver.HasNewWork()) {
  1578. return ResolveResult::Retry();
  1579. }
  1580. auto entity_name_id =
  1581. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  1582. return ResolveResult::Deduplicated<SemIR::SymbolicBinding>(
  1583. resolver,
  1584. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  1585. .entity_name_id = entity_name_id,
  1586. .value_id = SemIR::InstId::None});
  1587. }
  1588. template <typename BindingPatternT>
  1589. requires SemIR::Internal::HasInstCategory<SemIR::AnyBindingPattern,
  1590. BindingPatternT>
  1591. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1592. BindingPatternT inst,
  1593. SemIR::InstId import_inst_id) -> ResolveResult {
  1594. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1595. const auto& import_entity_name =
  1596. resolver.import_entity_names().Get(inst.entity_name_id);
  1597. auto parent_scope_id =
  1598. GetLocalNameScopeId(resolver, import_entity_name.parent_scope_id);
  1599. if (resolver.HasNewWork()) {
  1600. return ResolveResult::Retry();
  1601. }
  1602. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1603. auto entity_name_id = resolver.local_entity_names().Add(
  1604. {.name_id = name_id,
  1605. .parent_scope_id = parent_scope_id,
  1606. .bind_index_value = import_entity_name.bind_index().index,
  1607. .is_template = import_entity_name.is_template});
  1608. return ResolveResult::Unique<BindingPatternT>(
  1609. resolver, import_inst_id,
  1610. {.type_id =
  1611. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1612. .entity_name_id = entity_name_id});
  1613. }
  1614. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1615. SemIR::BoolLiteral inst) -> ResolveResult {
  1616. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1617. SemIR::BoolType::TypeInstId);
  1618. CARBON_CHECK(!resolver.HasNewWork());
  1619. return ResolveResult::Deduplicated<SemIR::BoolLiteral>(
  1620. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1621. SemIR::BoolType::TypeInstId),
  1622. .value = inst.value});
  1623. }
  1624. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1625. SemIR::BoundMethod inst) -> ResolveResult {
  1626. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1627. SemIR::BoundMethodType::TypeInstId);
  1628. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1629. auto function_decl_id =
  1630. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1631. if (resolver.HasNewWork()) {
  1632. return ResolveResult::Retry();
  1633. }
  1634. return ResolveResult::Deduplicated<SemIR::BoundMethod>(
  1635. resolver,
  1636. {.type_id = GetSingletonType(resolver.local_context(),
  1637. SemIR::BoundMethodType::TypeInstId),
  1638. .object_id = object_id,
  1639. .function_decl_id = function_decl_id});
  1640. }
  1641. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1642. -> ResolveResult {
  1643. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1644. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1645. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1646. if (resolver.HasNewWork()) {
  1647. return ResolveResult::Retry();
  1648. }
  1649. return ResolveResult::Deduplicated<SemIR::Call>(
  1650. resolver,
  1651. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  1652. .callee_id = callee_id,
  1653. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1654. }
  1655. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1656. SemIR::CharLiteralValue inst) -> ResolveResult {
  1657. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1658. SemIR::CharLiteralType::TypeInstId);
  1659. CARBON_CHECK(!resolver.HasNewWork());
  1660. return ResolveResult::Deduplicated<SemIR::CharLiteralValue>(
  1661. resolver,
  1662. {.type_id = GetSingletonType(resolver.local_context(),
  1663. SemIR::CharLiteralType::TypeInstId),
  1664. .value = inst.value});
  1665. }
  1666. static auto AddPlaceholderNameScope(ImportContext& context)
  1667. -> SemIR::NameScopeId {
  1668. return context.local_name_scopes().Add(
  1669. SemIR::InstId::None, SemIR::NameId::None, SemIR::NameScopeId::None);
  1670. }
  1671. // Makes an incomplete class. This is necessary even with classes with a
  1672. // complete declaration, because things such as `Self` may refer back to the
  1673. // type.
  1674. static auto ImportIncompleteClass(ImportContext& context,
  1675. const SemIR::Class& import_class,
  1676. SemIR::SpecificId enclosing_specific_id)
  1677. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1678. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::TypeId,
  1679. .class_id = SemIR::ClassId::None,
  1680. .decl_block_id = SemIR::InstBlockId::Empty};
  1681. auto class_decl_id = AddPlaceholderImportedInst(
  1682. context, import_class.latest_decl_id(), class_decl);
  1683. // Regardless of whether ClassDecl is a complete type, we first need an
  1684. // incomplete type so that any references have something to point at.
  1685. class_decl.class_id = context.local_classes().Add(
  1686. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1687. {.self_type_id = SemIR::TypeId::None,
  1688. .inheritance_kind = import_class.inheritance_kind,
  1689. .is_dynamic = import_class.is_dynamic,
  1690. .scope_id = import_class.is_complete()
  1691. ? AddPlaceholderNameScope(context)
  1692. : SemIR::NameScopeId::None}});
  1693. if (import_class.has_parameters()) {
  1694. class_decl.type_id = GetGenericClassType(
  1695. context.local_context(), class_decl.class_id, enclosing_specific_id);
  1696. }
  1697. // Write the class ID into the ClassDecl.
  1698. auto self_const_id =
  1699. ReplacePlaceholderImportedInst(context, class_decl_id, class_decl);
  1700. return {class_decl.class_id, self_const_id};
  1701. }
  1702. static auto InitializeNameScopeAndImportRefs(
  1703. ImportContext& context, const SemIR::NameScope& import_scope,
  1704. SemIR::NameScope& new_scope, SemIR::InstId decl_id, SemIR::NameId name_id,
  1705. SemIR::NameScopeId parent_scope_id) {
  1706. new_scope.Set(decl_id, name_id, parent_scope_id);
  1707. AddNameScopeImportRefs(context, import_scope, new_scope);
  1708. }
  1709. // Fills out the class definition for an incomplete class.
  1710. static auto ImportClassDefinition(ImportContext& context,
  1711. const SemIR::Class& import_class,
  1712. SemIR::Class& new_class,
  1713. SemIR::InstId complete_type_witness_id,
  1714. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1715. SemIR::InstId vtable_decl_id) -> void {
  1716. new_class.definition_id = new_class.first_owning_decl_id;
  1717. new_class.complete_type_witness_id = complete_type_witness_id;
  1718. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1719. const auto& import_scope =
  1720. context.import_name_scopes().Get(import_class.scope_id);
  1721. // Push a block so that we can add scoped instructions to it.
  1722. context.local_context().inst_block_stack().Push();
  1723. InitializeNameScopeAndImportRefs(
  1724. context, import_scope, new_scope, new_class.first_owning_decl_id,
  1725. SemIR::NameId::None, new_class.parent_scope_id);
  1726. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1727. if (import_class.base_id.has_value()) {
  1728. new_class.base_id = base_id;
  1729. }
  1730. if (import_class.adapt_id.has_value()) {
  1731. new_class.adapt_id = adapt_id;
  1732. }
  1733. if (import_class.vtable_decl_id.has_value()) {
  1734. new_class.vtable_decl_id = vtable_decl_id;
  1735. }
  1736. }
  1737. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1738. SemIR::ClassDecl inst,
  1739. SemIR::ConstantId class_const_id)
  1740. -> ResolveResult {
  1741. // TODO: The handling of interfaces repeats a lot with the handling of
  1742. // classes, and will likely also be repeated for named constraints and
  1743. // choice types. Factor out some of this functionality.
  1744. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1745. SemIR::ClassId class_id = SemIR::ClassId::None;
  1746. if (!class_const_id.has_value()) {
  1747. auto import_specific_id = SemIR::SpecificId::None;
  1748. if (auto import_generic_class_type =
  1749. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1750. inst.type_id)) {
  1751. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1752. }
  1753. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1754. if (resolver.HasNewWork()) {
  1755. // This is the end of the first phase. Don't make a new class yet if
  1756. // we already have new work.
  1757. return ResolveResult::Retry();
  1758. }
  1759. // On the second phase, create a forward declaration of the class for any
  1760. // recursive references.
  1761. auto enclosing_specific_id =
  1762. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1763. std::tie(class_id, class_const_id) =
  1764. ImportIncompleteClass(resolver, import_class, enclosing_specific_id);
  1765. } else {
  1766. // On the third phase, compute the class ID from the constant
  1767. // value of the declaration.
  1768. auto class_const_inst = resolver.local_insts().Get(
  1769. resolver.local_constant_values().GetInstId(class_const_id));
  1770. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1771. class_id = class_type->class_id;
  1772. } else {
  1773. auto generic_class_type =
  1774. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1775. class_const_inst.type_id());
  1776. class_id = generic_class_type.class_id;
  1777. }
  1778. }
  1779. // Load constants for the definition.
  1780. auto parent_scope_id =
  1781. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1782. auto implicit_param_patterns = GetLocalInstBlockContents(
  1783. resolver, import_class.implicit_param_patterns_id);
  1784. auto param_patterns =
  1785. GetLocalInstBlockContents(resolver, import_class.param_patterns_id);
  1786. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1787. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1788. auto complete_type_witness_const_id =
  1789. import_class.complete_type_witness_id.has_value()
  1790. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1791. : SemIR::ConstantId::None;
  1792. auto base_id = import_class.base_id.has_value()
  1793. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1794. : SemIR::InstId::None;
  1795. auto adapt_id = import_class.adapt_id.has_value()
  1796. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1797. : SemIR::InstId::None;
  1798. auto vtable_decl_id =
  1799. import_class.vtable_decl_id.has_value()
  1800. ? AddImportRef(resolver, import_class.vtable_decl_id)
  1801. : SemIR::InstId::None;
  1802. auto& new_class = resolver.local_classes().Get(class_id);
  1803. if (resolver.HasNewWork()) {
  1804. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1805. }
  1806. new_class.parent_scope_id = parent_scope_id;
  1807. new_class.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1808. resolver, import_class.implicit_param_patterns_id,
  1809. implicit_param_patterns);
  1810. new_class.param_patterns_id = GetLocalCanonicalInstBlockId(
  1811. resolver, import_class.param_patterns_id, param_patterns);
  1812. new_class.self_type_id =
  1813. resolver.local_types().GetTypeIdForTypeConstantId(self_const_id);
  1814. if (import_class.is_complete()) {
  1815. auto complete_type_witness_id = AddLoadedImportRef(
  1816. resolver,
  1817. GetSingletonType(resolver.local_context(),
  1818. SemIR::WitnessType::TypeInstId),
  1819. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1820. ImportClassDefinition(resolver, import_class, new_class,
  1821. complete_type_witness_id, base_id, adapt_id,
  1822. vtable_decl_id);
  1823. }
  1824. return ResolveResult::FinishGenericOrDone(
  1825. resolver, class_const_id, new_class.first_decl_id(),
  1826. import_class.generic_id, new_class.generic_id, generic_data);
  1827. }
  1828. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1829. SemIR::ClassType inst) -> ResolveResult {
  1830. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1831. auto class_const_id = GetLocalConstantId(
  1832. resolver,
  1833. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1834. if (class_const_id == SemIR::ErrorInst::ConstantId) {
  1835. // TODO: It should be possible to remove this once C++ imports work.
  1836. return ResolveResult::Done(class_const_id);
  1837. }
  1838. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1839. if (resolver.HasNewWork()) {
  1840. return ResolveResult::Retry();
  1841. }
  1842. // Find the corresponding class type. For a non-generic class, this is the
  1843. // type of the class declaration. For a generic class, build a class type
  1844. // referencing this specialization of the generic class.
  1845. auto class_const_inst = resolver.local_insts().Get(
  1846. resolver.local_constant_values().GetInstId(class_const_id));
  1847. if (class_const_inst.Is<SemIR::ClassType>()) {
  1848. return ResolveResult::Done(class_const_id);
  1849. } else {
  1850. auto generic_class_type =
  1851. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1852. class_const_inst.type_id());
  1853. auto specific_id =
  1854. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1855. return ResolveResult::Deduplicated<SemIR::ClassType>(
  1856. resolver, {.type_id = SemIR::TypeType::TypeId,
  1857. .class_id = generic_class_type.class_id,
  1858. .specific_id = specific_id});
  1859. }
  1860. }
  1861. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1862. SemIR::CompleteTypeWitness inst)
  1863. -> ResolveResult {
  1864. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1865. SemIR::WitnessType::TypeInstId);
  1866. auto object_repr_type_inst_id =
  1867. GetLocalTypeInstId(resolver, inst.object_repr_type_inst_id);
  1868. if (resolver.HasNewWork()) {
  1869. return ResolveResult::Retry();
  1870. }
  1871. return ResolveResult::Deduplicated<SemIR::CompleteTypeWitness>(
  1872. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1873. SemIR::WitnessType::TypeInstId),
  1874. .object_repr_type_inst_id = object_repr_type_inst_id});
  1875. }
  1876. template <typename InstT>
  1877. requires SemIR::Internal::HasInstCategory<SemIR::AnyQualifiedType, InstT>
  1878. static auto TryResolveTypedInst(ImportRefResolver& resolver, InstT inst)
  1879. -> ResolveResult {
  1880. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1881. auto inner_id = GetLocalTypeInstId(resolver, inst.inner_id);
  1882. if (resolver.HasNewWork()) {
  1883. return ResolveResult::Retry();
  1884. }
  1885. return ResolveResult::Deduplicated<InstT>(
  1886. resolver, {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_id});
  1887. }
  1888. static auto HandleUnsupportedCppOverloadSet(ImportRefResolver& resolver,
  1889. SemIR::CppOverloadSetId id) {
  1890. // Supporting C++ overload resolution of imported functions is a large task,
  1891. // which might require serializing and deserializing AST for using decl ids,
  1892. // using modules and/or linking ASTs.
  1893. resolver.local_context().TODO(
  1894. SemIR::LocId::None,
  1895. llvm::formatv(
  1896. "Unsupported: Importing C++ function `{0}` indirectly",
  1897. resolver.import_ir().names().GetAsStringIfIdentifier(
  1898. resolver.import_ir().cpp_overload_sets().Get(id).name_id)));
  1899. return ResolveResult::Done(SemIR::ErrorInst::ConstantId,
  1900. SemIR::ErrorInst::InstId);
  1901. }
  1902. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1903. SemIR::CppOverloadSetType inst)
  1904. -> ResolveResult {
  1905. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1906. }
  1907. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1908. SemIR::CppOverloadSetValue inst)
  1909. -> ResolveResult {
  1910. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1911. }
  1912. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1913. SemIR::CustomWitness inst) -> ResolveResult {
  1914. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1915. SemIR::WitnessType::TypeInstId);
  1916. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  1917. const auto& import_specific_interface =
  1918. resolver.import_specific_interfaces().Get(
  1919. inst.query_specific_interface_id);
  1920. auto data =
  1921. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  1922. if (resolver.HasNewWork()) {
  1923. return ResolveResult::Retry();
  1924. }
  1925. auto elements_id =
  1926. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements);
  1927. auto specific_interface =
  1928. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  1929. auto query_specific_interface_id =
  1930. resolver.local_specific_interfaces().Add(specific_interface);
  1931. return ResolveResult::Deduplicated<SemIR::CustomWitness>(
  1932. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1933. SemIR::WitnessType::TypeInstId),
  1934. .elements_id = elements_id,
  1935. .query_specific_interface_id = query_specific_interface_id});
  1936. }
  1937. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1938. SemIR::ExportDecl inst) -> ResolveResult {
  1939. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1940. return ResolveResult::RetryOrDone(resolver, value_id);
  1941. }
  1942. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1943. SemIR::FieldDecl inst,
  1944. SemIR::InstId import_inst_id) -> ResolveResult {
  1945. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1946. if (resolver.HasNewWork()) {
  1947. return ResolveResult::Retry();
  1948. }
  1949. return ResolveResult::Unique<SemIR::FieldDecl>(
  1950. resolver, import_inst_id,
  1951. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(const_id),
  1952. .name_id = GetLocalNameId(resolver, inst.name_id),
  1953. .index = inst.index});
  1954. }
  1955. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1956. SemIR::FloatLiteralValue inst)
  1957. -> ResolveResult {
  1958. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1959. SemIR::FloatLiteralType::TypeInstId);
  1960. CARBON_CHECK(!resolver.HasNewWork());
  1961. auto real_id = resolver.local_ir().reals().Add(
  1962. resolver.import_ir().reals().Get(inst.real_id));
  1963. return ResolveResult::Deduplicated<SemIR::FloatLiteralValue>(
  1964. resolver,
  1965. {.type_id = GetSingletonType(resolver.local_context(),
  1966. SemIR::FloatLiteralType::TypeInstId),
  1967. .real_id = real_id});
  1968. }
  1969. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1970. SemIR::FloatType inst) -> ResolveResult {
  1971. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1972. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  1973. if (resolver.HasNewWork()) {
  1974. return ResolveResult::Retry();
  1975. }
  1976. return ResolveResult::Deduplicated<SemIR::FloatType>(
  1977. resolver, {.type_id = SemIR::TypeType::TypeId,
  1978. .bit_width_id = bit_width_id,
  1979. .float_kind = inst.float_kind});
  1980. }
  1981. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1982. SemIR::FloatValue inst) -> ResolveResult {
  1983. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1984. if (resolver.HasNewWork()) {
  1985. return ResolveResult::Retry();
  1986. }
  1987. auto float_id = resolver.local_ir().floats().Add(
  1988. resolver.import_ir().floats().Get(inst.float_id));
  1989. return ResolveResult::Deduplicated<SemIR::FloatValue>(
  1990. resolver,
  1991. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  1992. .float_id = float_id});
  1993. }
  1994. // Make a declaration of a function. This is done as a separate step from
  1995. // importing the function declaration in order to resolve cycles.
  1996. static auto ImportFunctionDecl(ImportContext& context,
  1997. const SemIR::Function& import_function,
  1998. SemIR::SpecificId specific_id)
  1999. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  2000. SemIR::FunctionDecl function_decl = {
  2001. .type_id = SemIR::TypeId::None,
  2002. .function_id = SemIR::FunctionId::None,
  2003. .decl_block_id = SemIR::InstBlockId::Empty};
  2004. auto function_decl_id = AddPlaceholderImportedInst(
  2005. context, import_function.first_decl_id(), function_decl);
  2006. // Start with an incomplete function.
  2007. function_decl.function_id = context.local_functions().Add(
  2008. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  2009. {.call_param_patterns_id = SemIR::InstBlockId::None,
  2010. .call_params_id = SemIR::InstBlockId::None,
  2011. .return_type_inst_id = SemIR::TypeInstId::None,
  2012. .return_form_inst_id = SemIR::InstId::None,
  2013. .return_patterns_id = SemIR::InstBlockId::None,
  2014. .virtual_modifier = import_function.virtual_modifier,
  2015. .virtual_index = import_function.virtual_index,
  2016. .evaluation_mode = import_function.evaluation_mode}});
  2017. // Directly add the function type constant. Don't use `GetFunctionType`
  2018. // because that will evaluate the function type, which we can't do if the
  2019. // specific's value block is still pending.
  2020. auto type_const_id = AddImportedConstant(
  2021. context.local_context(),
  2022. SemIR::FunctionType{.type_id = SemIR::TypeType::TypeId,
  2023. .function_id = function_decl.function_id,
  2024. .specific_id = specific_id});
  2025. function_decl.type_id =
  2026. context.local_types().GetTypeIdForTypeConstantId(type_const_id);
  2027. // Write the function ID and type into the FunctionDecl.
  2028. auto function_const_id =
  2029. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  2030. return {function_decl.function_id, function_const_id};
  2031. }
  2032. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2033. SemIR::FunctionDecl inst,
  2034. SemIR::ConstantId function_const_id)
  2035. -> ResolveResult {
  2036. const auto& import_function =
  2037. resolver.import_functions().Get(inst.function_id);
  2038. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  2039. if (!function_const_id.has_value()) {
  2040. auto import_specific_id = resolver.import_types()
  2041. .GetAs<SemIR::FunctionType>(inst.type_id)
  2042. .specific_id;
  2043. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2044. if (resolver.HasNewWork()) {
  2045. // This is the end of the first phase. Don't make a new function yet if
  2046. // we already have new work.
  2047. return ResolveResult::Retry();
  2048. }
  2049. // On the second phase, create a forward declaration of the function.
  2050. auto specific_id =
  2051. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2052. std::tie(function_id, function_const_id) =
  2053. ImportFunctionDecl(resolver, import_function, specific_id);
  2054. } else {
  2055. // On the third phase, compute the function ID from the constant value of
  2056. // the declaration.
  2057. auto function_const_inst = resolver.local_insts().Get(
  2058. resolver.local_constant_values().GetInstId(function_const_id));
  2059. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  2060. function_const_inst.type_id());
  2061. function_id = function_type.function_id;
  2062. }
  2063. auto call_param_patterns = GetLocalInstBlockContents(
  2064. resolver, import_function.call_param_patterns_id);
  2065. auto return_type_const_id = SemIR::ConstantId::None;
  2066. if (import_function.return_type_inst_id.has_value()) {
  2067. return_type_const_id =
  2068. GetLocalConstantId(resolver, import_function.return_type_inst_id);
  2069. }
  2070. auto return_form_const_id = SemIR::ConstantId::None;
  2071. if (import_function.return_form_inst_id.has_value()) {
  2072. return_form_const_id =
  2073. GetLocalConstantId(resolver, import_function.return_form_inst_id);
  2074. }
  2075. auto parent_scope_id =
  2076. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  2077. auto implicit_param_patterns = GetLocalInstBlockContents(
  2078. resolver, import_function.implicit_param_patterns_id);
  2079. auto param_patterns =
  2080. GetLocalInstBlockContents(resolver, import_function.param_patterns_id);
  2081. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  2082. auto self_param_id =
  2083. GetLocalConstantInstId(resolver, import_function.self_param_id);
  2084. auto return_patterns =
  2085. GetLocalInstBlockContents(resolver, import_function.return_patterns_id);
  2086. auto& new_function = resolver.local_functions().Get(function_id);
  2087. if (resolver.HasNewWork()) {
  2088. return ResolveResult::Retry(function_const_id,
  2089. new_function.first_decl_id());
  2090. }
  2091. // Add the function declaration.
  2092. new_function.call_param_patterns_id = GetLocalCanonicalInstBlockId(
  2093. resolver, import_function.call_param_patterns_id, call_param_patterns);
  2094. new_function.parent_scope_id = parent_scope_id;
  2095. new_function.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2096. resolver, import_function.implicit_param_patterns_id,
  2097. implicit_param_patterns);
  2098. new_function.self_param_id = self_param_id;
  2099. new_function.param_patterns_id = GetLocalCanonicalInstBlockId(
  2100. resolver, import_function.param_patterns_id, param_patterns);
  2101. new_function.return_type_inst_id = SemIR::TypeInstId::None;
  2102. if (import_function.return_type_inst_id.has_value()) {
  2103. new_function.return_type_inst_id = AddLoadedImportRefForType(
  2104. resolver, import_function.return_type_inst_id, return_type_const_id);
  2105. }
  2106. new_function.return_form_inst_id = SemIR::InstId::None;
  2107. if (import_function.return_form_inst_id.has_value()) {
  2108. new_function.return_form_inst_id = AddLoadedImportRef(
  2109. resolver, SemIR::FormType::TypeId, import_function.return_form_inst_id,
  2110. return_form_const_id);
  2111. }
  2112. new_function.return_patterns_id = GetLocalCanonicalInstBlockId(
  2113. resolver, import_function.return_patterns_id, return_patterns);
  2114. if (import_function.definition_id.has_value()) {
  2115. new_function.definition_id = new_function.first_owning_decl_id;
  2116. }
  2117. switch (import_function.special_function_kind) {
  2118. case SemIR::Function::SpecialFunctionKind::None: {
  2119. break;
  2120. }
  2121. case SemIR::Function::SpecialFunctionKind::Builtin: {
  2122. new_function.SetBuiltinFunction(import_function.builtin_function_kind());
  2123. break;
  2124. }
  2125. case SemIR::Function::SpecialFunctionKind::Thunk: {
  2126. auto entity_name_id = resolver.local_entity_names().AddCanonical(
  2127. {.name_id = new_function.name_id,
  2128. .parent_scope_id = new_function.parent_scope_id});
  2129. new_function.SetThunk(AddImportRef(
  2130. resolver, import_function.thunk_decl_id(), entity_name_id));
  2131. break;
  2132. }
  2133. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  2134. resolver.local_context().TODO(SemIR::LocId::None,
  2135. "Unsupported: Importing C++ functions that "
  2136. "require thunks indirectly");
  2137. }
  2138. }
  2139. return ResolveResult::FinishGenericOrDone(
  2140. resolver, function_const_id, new_function.first_decl_id(),
  2141. import_function.generic_id, new_function.generic_id, generic_data);
  2142. }
  2143. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2144. SemIR::VtableDecl inst) -> ResolveResult {
  2145. const auto& import_vtable = resolver.import_vtables().Get(inst.vtable_id);
  2146. auto class_const_id =
  2147. GetLocalConstantId(resolver, resolver.import_classes()
  2148. .Get(import_vtable.class_id)
  2149. .first_owning_decl_id);
  2150. auto class_const_inst = resolver.local_insts().Get(
  2151. resolver.local_constant_values().GetInstId(class_const_id));
  2152. // TODO: Ensure the vtable is only imported once, in eg: if there's distinct
  2153. // vtable constants (imported from multiple libraries using the vtable) that
  2154. // refer to the same vtable, the vtable should still be singular.
  2155. auto virtual_functions =
  2156. resolver.import_inst_blocks().Get(import_vtable.virtual_functions_id);
  2157. llvm::SmallVector<SemIR::InstId> lazy_virtual_functions;
  2158. lazy_virtual_functions.reserve(virtual_functions.size());
  2159. for (auto vtable_entry_id : virtual_functions) {
  2160. auto local_attached_constant_id =
  2161. GetLocalConstantId(resolver, vtable_entry_id);
  2162. lazy_virtual_functions.push_back(
  2163. resolver.local_constant_values().GetInstIdIfValid(
  2164. local_attached_constant_id));
  2165. }
  2166. if (resolver.HasNewWork()) {
  2167. return ResolveResult::Retry();
  2168. }
  2169. for (auto [import_vtable_entry_inst_id, local_vtable_entry_inst_id] :
  2170. llvm::zip_equal(virtual_functions, lazy_virtual_functions)) {
  2171. // Use LoadedImportRef for imported symbolic constant vtable entries so they
  2172. // can carry attached constants necessary for applying specifics to these
  2173. // constants when they are used.
  2174. auto local_attached_constant_id =
  2175. resolver.local_constant_values().GetAttached(
  2176. local_vtable_entry_inst_id);
  2177. if (local_attached_constant_id.is_symbolic()) {
  2178. local_vtable_entry_inst_id = AddLoadedImportRef(
  2179. resolver,
  2180. GetSingletonType(resolver.local_context(),
  2181. SemIR::SpecificFunctionType::TypeInstId),
  2182. import_vtable_entry_inst_id, local_attached_constant_id);
  2183. }
  2184. }
  2185. auto class_id = SemIR::ClassId::None;
  2186. if (class_const_inst.Is<SemIR::ClassType>()) {
  2187. class_id = class_const_inst.As<SemIR::ClassType>().class_id;
  2188. } else {
  2189. auto generic_class_type =
  2190. resolver.local_types().GetAs<SemIR::GenericClassType>(
  2191. class_const_inst.type_id());
  2192. class_id = generic_class_type.class_id;
  2193. }
  2194. auto new_vtable_id = resolver.local_vtables().Add(
  2195. {{.class_id = class_id,
  2196. .virtual_functions_id =
  2197. resolver.local_inst_blocks().Add(lazy_virtual_functions)}});
  2198. return ResolveResult::Deduplicated<SemIR::VtableDecl>(
  2199. resolver, {.type_id = GetPointerType(resolver.local_context(),
  2200. SemIR::VtableType::TypeInstId),
  2201. .vtable_id = new_vtable_id});
  2202. }
  2203. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2204. SemIR::VtablePtr inst) -> ResolveResult {
  2205. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2206. auto vtable_const_id = GetLocalConstantId(
  2207. resolver, resolver.import_classes()
  2208. .Get(resolver.import_vtables().Get(inst.vtable_id).class_id)
  2209. .vtable_decl_id);
  2210. auto vtable_const_inst = resolver.local_insts().Get(
  2211. resolver.local_constant_values().GetInstId(vtable_const_id));
  2212. if (resolver.HasNewWork()) {
  2213. return ResolveResult::Retry();
  2214. }
  2215. return ResolveResult::Deduplicated<SemIR::VtablePtr>(
  2216. resolver,
  2217. {.type_id = GetPointerType(resolver.local_context(),
  2218. SemIR::VtableType::TypeInstId),
  2219. .vtable_id = vtable_const_inst.As<SemIR::VtableDecl>().vtable_id,
  2220. .specific_id =
  2221. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data)});
  2222. }
  2223. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2224. SemIR::FunctionType inst) -> ResolveResult {
  2225. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2226. auto fn_val_id = GetLocalConstantInstId(
  2227. resolver,
  2228. resolver.import_functions().Get(inst.function_id).first_decl_id());
  2229. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2230. if (resolver.HasNewWork()) {
  2231. return ResolveResult::Retry();
  2232. }
  2233. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  2234. return ResolveResult::Deduplicated<SemIR::FunctionType>(
  2235. resolver, {.type_id = SemIR::TypeType::TypeId,
  2236. .function_id = resolver.local_types()
  2237. .GetAs<SemIR::FunctionType>(fn_type_id)
  2238. .function_id,
  2239. .specific_id = GetOrAddLocalSpecific(
  2240. resolver, inst.specific_id, specific_data)});
  2241. }
  2242. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2243. SemIR::FunctionTypeWithSelfType inst)
  2244. -> ResolveResult {
  2245. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2246. auto interface_function_type_id =
  2247. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  2248. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  2249. if (resolver.HasNewWork()) {
  2250. return ResolveResult::Retry();
  2251. }
  2252. return ResolveResult::Deduplicated<SemIR::FunctionTypeWithSelfType>(
  2253. resolver, {.type_id = SemIR::TypeType::TypeId,
  2254. .interface_function_type_id = interface_function_type_id,
  2255. .self_id = self_id});
  2256. }
  2257. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2258. SemIR::GenericClassType inst) -> ResolveResult {
  2259. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2260. auto class_val_id = GetLocalConstantInstId(
  2261. resolver,
  2262. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  2263. if (resolver.HasNewWork()) {
  2264. return ResolveResult::Retry();
  2265. }
  2266. auto class_val = resolver.local_insts().Get(class_val_id);
  2267. CARBON_CHECK(
  2268. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  2269. return ResolveResult::Done(
  2270. resolver.local_types().GetConstantId(class_val.type_id()));
  2271. }
  2272. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2273. SemIR::GenericInterfaceType inst)
  2274. -> ResolveResult {
  2275. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2276. auto interface_val_id = GetLocalConstantInstId(
  2277. resolver,
  2278. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2279. if (resolver.HasNewWork()) {
  2280. return ResolveResult::Retry();
  2281. }
  2282. auto interface_val = resolver.local_insts().Get(interface_val_id);
  2283. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  2284. interface_val.type_id()));
  2285. return ResolveResult::Done(
  2286. resolver.local_types().GetConstantId(interface_val.type_id()));
  2287. }
  2288. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2289. SemIR::GenericNamedConstraintType inst)
  2290. -> ResolveResult {
  2291. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2292. auto constraint_val_id =
  2293. GetLocalConstantInstId(resolver, resolver.import_named_constraints()
  2294. .Get(inst.named_constraint_id)
  2295. .first_owning_decl_id);
  2296. if (resolver.HasNewWork()) {
  2297. return ResolveResult::Retry();
  2298. }
  2299. auto constraint_val = resolver.local_insts().Get(constraint_val_id);
  2300. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericNamedConstraintType>(
  2301. constraint_val.type_id()));
  2302. return ResolveResult::Done(
  2303. resolver.local_types().GetConstantId(constraint_val.type_id()));
  2304. }
  2305. // Make a declaration of an impl. This is done as a separate step from
  2306. // importing the impl definition in order to resolve cycles.
  2307. static auto ImportImplDecl(ImportContext& context,
  2308. const SemIR::Impl& import_impl,
  2309. SemIR::InstId witness_id)
  2310. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  2311. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  2312. .decl_block_id = SemIR::InstBlockId::Empty};
  2313. auto impl_decl_id = AddPlaceholderImportedInst(
  2314. context, import_impl.latest_decl_id(), impl_decl);
  2315. impl_decl.impl_id = context.local_impls().Add(
  2316. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  2317. {.self_id = SemIR::TypeInstId::None,
  2318. .constraint_id = SemIR::TypeInstId::None,
  2319. .interface = SemIR::SpecificInterface::None,
  2320. .witness_id = witness_id,
  2321. .scope_id = import_impl.is_complete() ? AddPlaceholderNameScope(context)
  2322. : SemIR::NameScopeId::None,
  2323. .is_final = import_impl.is_final}});
  2324. // Write the impl ID into the ImplDecl.
  2325. auto impl_const_id =
  2326. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  2327. return {impl_decl.impl_id, impl_const_id};
  2328. }
  2329. // Imports the definition of an impl.
  2330. static auto ImportImplDefinition(ImportContext& context,
  2331. const SemIR::Impl& import_impl,
  2332. SemIR::Impl& new_impl) -> void {
  2333. new_impl.definition_id = new_impl.first_owning_decl_id;
  2334. new_impl.defined = true;
  2335. if (import_impl.scope_id.has_value()) {
  2336. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  2337. new_scope.Set(new_impl.first_owning_decl_id, SemIR::NameId::None,
  2338. new_impl.parent_scope_id);
  2339. // Import the contents of the definition scope, if we might need it. Name
  2340. // lookup is never performed into this scope by a user of the impl, so
  2341. // this is only necessary in the same library that defined the impl, in
  2342. // order to support defining members of the impl out of line in the impl
  2343. // file when the impl is defined in the API file.
  2344. // TODO: Check to see if this impl is owned by the API file, rather than
  2345. // merely being imported into it.
  2346. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2347. const auto& import_scope =
  2348. context.import_name_scopes().Get(import_impl.scope_id);
  2349. // Push a block so that we can add scoped instructions to it.
  2350. context.local_context().inst_block_stack().Push();
  2351. AddNameScopeImportRefs(context, import_scope, new_scope);
  2352. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  2353. }
  2354. }
  2355. }
  2356. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2357. SemIR::ImplDecl inst,
  2358. SemIR::ConstantId impl_const_id)
  2359. -> ResolveResult {
  2360. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  2361. // functions. Factor out the commonality.
  2362. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2363. auto specific_interface_data =
  2364. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  2365. SemIR::ImplId impl_id = SemIR::ImplId::None;
  2366. if (!impl_const_id.has_value()) {
  2367. if (resolver.HasNewWork()) {
  2368. // This is the end of the first phase. Don't make a new impl yet if we
  2369. // already have new work.
  2370. return ResolveResult::Retry();
  2371. }
  2372. // On the second phase, create a forward declaration of the impl for any
  2373. // recursive references.
  2374. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  2375. std::tie(impl_id, impl_const_id) =
  2376. ImportImplDecl(resolver, import_impl, witness_id);
  2377. } else {
  2378. // On the third phase, compute the impl ID from the "constant value" of
  2379. // the declaration, which is a reference to the created ImplDecl.
  2380. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  2381. resolver.local_constant_values().GetInstId(impl_const_id));
  2382. impl_id = impl_const_inst.impl_id;
  2383. }
  2384. // Load constants for the definition.
  2385. auto parent_scope_id =
  2386. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  2387. auto implicit_param_patterns = GetLocalInstBlockContents(
  2388. resolver, import_impl.implicit_param_patterns_id);
  2389. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  2390. auto self_const_id = GetLocalConstantId(resolver, import_impl.self_id);
  2391. auto constraint_const_id =
  2392. GetLocalConstantId(resolver, import_impl.constraint_id);
  2393. auto& new_impl = resolver.local_impls().Get(impl_id);
  2394. if (resolver.HasNewWork()) {
  2395. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2396. }
  2397. new_impl.parent_scope_id = parent_scope_id;
  2398. new_impl.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2399. resolver, import_impl.implicit_param_patterns_id,
  2400. implicit_param_patterns);
  2401. // Create instructions for self and constraint to hold the symbolic constant
  2402. // value for a generic impl.
  2403. new_impl.self_id =
  2404. AddLoadedImportRefForType(resolver, import_impl.self_id, self_const_id);
  2405. new_impl.constraint_id = AddLoadedImportRefForType(
  2406. resolver, import_impl.constraint_id, constraint_const_id);
  2407. new_impl.interface = GetLocalSpecificInterface(
  2408. resolver, import_impl.interface, specific_interface_data);
  2409. // Create a local IdentifiedFacetType for the imported facet type, since impl
  2410. // declarations always identify the facet type.
  2411. if (auto facet_type = resolver.local_insts().TryGetAs<SemIR::FacetType>(
  2412. resolver.local_constant_values().GetInstId(constraint_const_id))) {
  2413. // Lookups later will be with the unattached constant, whereas
  2414. // GetLocalConstantId gave us an attached constant.
  2415. auto unattached_self_const_id =
  2416. resolver.local_constant_values().GetUnattachedConstant(self_const_id);
  2417. RequireIdentifiedFacetType(
  2418. resolver.local_context(), SemIR::LocId::None, unattached_self_const_id,
  2419. *facet_type, []([[maybe_unused]] auto& builder) {
  2420. CARBON_FATAL("Imported impl constraint can't be identified");
  2421. });
  2422. }
  2423. if (import_impl.is_complete()) {
  2424. ImportImplDefinition(resolver, import_impl, new_impl);
  2425. }
  2426. // If the `impl` is declared in the API file corresponding to the current
  2427. // file, add this to impl lookup so that it can be found by redeclarations
  2428. // in the current file.
  2429. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2430. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2431. }
  2432. return ResolveResult::FinishGenericOrDone(
  2433. resolver, impl_const_id, new_impl.first_decl_id(), import_impl.generic_id,
  2434. new_impl.generic_id, generic_data);
  2435. }
  2436. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2437. SemIR::RequireImplsDecl inst,
  2438. SemIR::ConstantId require_decl_const_id)
  2439. -> ResolveResult {
  2440. const auto& import_require =
  2441. resolver.import_require_impls().Get(inst.require_impls_id);
  2442. auto require_decl_id = SemIR::InstId::None;
  2443. auto require_impls_id = SemIR::RequireImplsId::None;
  2444. if (!require_decl_const_id.has_value()) {
  2445. // Phase one: Make the decl and structure with placeholder values to be
  2446. // filled in. Begin the generic so instructions can be attached to it.
  2447. SemIR::RequireImplsDecl require_decl = {
  2448. .require_impls_id = SemIR::RequireImplsId::None,
  2449. .decl_block_id = SemIR::InstBlockId::Empty};
  2450. auto require_decl_id = AddPlaceholderImportedInst(
  2451. resolver, import_require.decl_id, require_decl);
  2452. require_impls_id = resolver.local_require_impls().Add(
  2453. {.self_id = SemIR::TypeInstId::None,
  2454. .facet_type_inst_id = SemIR::TypeInstId::None,
  2455. .decl_id = require_decl_id,
  2456. .parent_scope_id = SemIR::NameScopeId::None,
  2457. .generic_id = ImportIncompleteGeneric(resolver, require_decl_id,
  2458. import_require.generic_id)});
  2459. // Write the RequireImplsId into the RequireImplsDecl.
  2460. require_decl.require_impls_id = require_impls_id;
  2461. require_decl_const_id =
  2462. ReplacePlaceholderImportedInst(resolver, require_decl_id, require_decl);
  2463. } else {
  2464. // Phase two: Get the `require_decl_id` and `require_impls_id` from the
  2465. // RequireImplsDecl constructed in phase one.
  2466. require_decl_id =
  2467. resolver.local_constant_values().GetInstId(require_decl_const_id);
  2468. require_impls_id = resolver.local_insts()
  2469. .GetAs<SemIR::RequireImplsDecl>(require_decl_id)
  2470. .require_impls_id;
  2471. }
  2472. // Load dependent constants.
  2473. auto parent_scope_id =
  2474. GetLocalNameScopeId(resolver, import_require.parent_scope_id);
  2475. auto generic_data = GetLocalGenericData(resolver, import_require.generic_id);
  2476. auto self_const_id = GetLocalConstantId(resolver, import_require.self_id);
  2477. auto facet_type_const_id =
  2478. GetLocalConstantId(resolver, import_require.facet_type_inst_id);
  2479. if (resolver.HasNewWork()) {
  2480. return ResolveResult::Retry(require_decl_const_id, require_decl_id);
  2481. }
  2482. // Fill in the RequireImpls structure.
  2483. auto& new_require = resolver.local_require_impls().Get(require_impls_id);
  2484. new_require.self_id = AddLoadedImportRefForType(
  2485. resolver, import_require.self_id, self_const_id);
  2486. new_require.facet_type_inst_id = AddLoadedImportRefForType(
  2487. resolver, import_require.facet_type_inst_id, facet_type_const_id);
  2488. new_require.extend_self = import_require.extend_self;
  2489. new_require.parent_scope_id = parent_scope_id;
  2490. return ResolveResult::FinishGenericOrDone(
  2491. resolver, require_decl_const_id, require_decl_id,
  2492. import_require.generic_id, new_require.generic_id, generic_data);
  2493. }
  2494. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2495. SemIR::ImportRefLoaded /*inst*/,
  2496. SemIR::InstId inst_id) -> ResolveResult {
  2497. // Return the constant for the instruction of the imported constant.
  2498. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2499. CARBON_CHECK(constant_id.has_value(),
  2500. "Loaded import ref has no constant value");
  2501. if (!constant_id.is_constant()) {
  2502. resolver.local_context().TODO(
  2503. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2504. return ResolveResult::Done(constant_id);
  2505. }
  2506. auto new_constant_id = GetLocalConstantId(resolver, constant_id);
  2507. return ResolveResult::RetryOrDone(resolver, new_constant_id);
  2508. }
  2509. // Make a declaration of an interface. This is done as a separate step from
  2510. // importing the interface definition in order to resolve cycles.
  2511. static auto ImportInterfaceDecl(ImportContext& context,
  2512. const SemIR::Interface& import_interface,
  2513. SemIR::SpecificId enclosing_specific_id)
  2514. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2515. SemIR::InterfaceDecl interface_decl = {
  2516. .type_id = SemIR::TypeType::TypeId,
  2517. .interface_id = SemIR::InterfaceId::None,
  2518. .decl_block_id = SemIR::InstBlockId::Empty};
  2519. auto interface_decl_id = AddPlaceholderImportedInst(
  2520. context, import_interface.first_owning_decl_id, interface_decl);
  2521. // Start with an incomplete interface.
  2522. //
  2523. // The generic_with_self_id is constructed by the InterfaceWithSelfDecl
  2524. // instruction inside the InterfaceDecl's body.
  2525. interface_decl.interface_id = context.local_interfaces().Add(
  2526. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2527. import_interface),
  2528. {.scope_without_self_id = import_interface.is_complete()
  2529. ? AddPlaceholderNameScope(context)
  2530. : SemIR::NameScopeId::None,
  2531. .scope_with_self_id = import_interface.is_complete()
  2532. ? AddPlaceholderNameScope(context)
  2533. : SemIR::NameScopeId::None}});
  2534. if (import_interface.has_parameters()) {
  2535. interface_decl.type_id = GetGenericInterfaceType(
  2536. context.local_context(), interface_decl.interface_id,
  2537. enclosing_specific_id);
  2538. }
  2539. // Write the interface ID into the InterfaceDecl.
  2540. auto interface_const_id = ReplacePlaceholderImportedInst(
  2541. context, interface_decl_id, interface_decl);
  2542. return {interface_decl.interface_id, interface_const_id};
  2543. }
  2544. // Imports the definition for an interface that has been imported as a forward
  2545. // declaration.
  2546. static auto ImportInterfaceDefinition(ImportContext& context,
  2547. const SemIR::Interface& import_interface,
  2548. SemIR::Interface& new_interface,
  2549. SemIR::InstId self_param_id) -> void {
  2550. auto& new_scope =
  2551. context.local_name_scopes().Get(new_interface.scope_without_self_id);
  2552. const auto& import_scope =
  2553. context.import_name_scopes().Get(import_interface.scope_without_self_id);
  2554. // Push a block so that we can add scoped instructions to it.
  2555. context.local_context().inst_block_stack().Push();
  2556. InitializeNameScopeAndImportRefs(
  2557. context, import_scope, new_scope, new_interface.first_owning_decl_id,
  2558. SemIR::NameId::None, new_interface.parent_scope_id);
  2559. new_interface.body_block_without_self_id =
  2560. context.local_context().inst_block_stack().Pop();
  2561. new_interface.self_param_id = self_param_id;
  2562. }
  2563. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2564. SemIR::InterfaceDecl inst,
  2565. SemIR::ConstantId interface_const_id)
  2566. -> ResolveResult {
  2567. const auto& import_interface =
  2568. resolver.import_interfaces().Get(inst.interface_id);
  2569. auto interface_id = SemIR::InterfaceId::None;
  2570. if (!interface_const_id.has_value()) {
  2571. auto import_specific_id = SemIR::SpecificId::None;
  2572. if (auto import_generic_interface_type =
  2573. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2574. inst.type_id)) {
  2575. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2576. }
  2577. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2578. if (resolver.HasNewWork()) {
  2579. // This is the end of the first phase. Don't make a new interface yet if
  2580. // we already have new work.
  2581. return ResolveResult::Retry();
  2582. }
  2583. // On the second phase, create a forward declaration of the interface.
  2584. auto enclosing_specific_id =
  2585. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2586. std::tie(interface_id, interface_const_id) =
  2587. ImportInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2588. } else {
  2589. // On the third phase, compute the interface ID from the constant value of
  2590. // the declaration.
  2591. auto interface_const_inst = resolver.local_insts().Get(
  2592. resolver.local_constant_values().GetInstId(interface_const_id));
  2593. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2594. const SemIR::FacetTypeInfo& facet_type_info =
  2595. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2596. auto single = facet_type_info.TryAsSingleExtend();
  2597. CARBON_CHECK(single);
  2598. interface_id = std::get<SemIR::SpecificInterface>(*single).interface_id;
  2599. } else {
  2600. auto generic_interface_type =
  2601. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2602. interface_const_inst.type_id());
  2603. interface_id = generic_interface_type.interface_id;
  2604. }
  2605. }
  2606. auto parent_scope_id =
  2607. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2608. auto implicit_param_patterns = GetLocalInstBlockContents(
  2609. resolver, import_interface.implicit_param_patterns_id);
  2610. auto param_patterns =
  2611. GetLocalInstBlockContents(resolver, import_interface.param_patterns_id);
  2612. auto generic_data =
  2613. GetLocalGenericData(resolver, import_interface.generic_id);
  2614. auto require_impls = GetLocalRequireImplsBlockContents(
  2615. resolver, import_interface.require_impls_block_id);
  2616. std::optional<SemIR::InstId> self_param_id;
  2617. if (import_interface.is_complete()) {
  2618. // Note the TODO on ResolveLocalEvalBlock, the generic eval block is rebuilt
  2619. // instead of being imported. When it's imported maybe this should be an
  2620. // ImportRef?
  2621. self_param_id =
  2622. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2623. // Importing the `generic_with_self_id` imports the InterfaceWithSelfDecl
  2624. // which sets the associated constants in the interface (if it's complete)
  2625. // which marks the local interface as complete. The InterfaceWithSelfDecl
  2626. // also sets the `generic_with_self_id` field on the local interface.
  2627. GetLocalConstantId(resolver, import_interface.generic_with_self_id);
  2628. }
  2629. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2630. if (resolver.HasNewWork()) {
  2631. return ResolveResult::Retry(interface_const_id,
  2632. new_interface.first_decl_id());
  2633. }
  2634. new_interface.parent_scope_id = parent_scope_id;
  2635. new_interface.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2636. resolver, import_interface.implicit_param_patterns_id,
  2637. implicit_param_patterns);
  2638. new_interface.param_patterns_id = GetLocalCanonicalInstBlockId(
  2639. resolver, import_interface.param_patterns_id, param_patterns);
  2640. new_interface.require_impls_block_id = GetLocalCanonicalRequireImplsBlockId(
  2641. resolver, import_interface.require_impls_block_id, require_impls);
  2642. if (import_interface.is_complete()) {
  2643. CARBON_CHECK(self_param_id);
  2644. ImportInterfaceDefinition(resolver, import_interface, new_interface,
  2645. *self_param_id);
  2646. }
  2647. // The interface's `generic_with_self_id` is filled out and finished by
  2648. // importing the InterfaceWithSelfDecl instruction which we find inside the
  2649. // InterfaceDecl.
  2650. return ResolveResult::FinishGenericOrDone(
  2651. resolver, interface_const_id, new_interface.first_decl_id(),
  2652. import_interface.generic_id, new_interface.generic_id, generic_data);
  2653. }
  2654. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2655. SemIR::InterfaceWithSelfDecl inst,
  2656. SemIR::ConstantId const_id) -> ResolveResult {
  2657. auto interface_const_id = GetLocalConstantId(
  2658. resolver,
  2659. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2660. // These are set differently in each phase.
  2661. auto decl_id = SemIR::InstId::None;
  2662. auto local_interface_id = SemIR::InterfaceId::None;
  2663. auto generic_with_self_id = SemIR::GenericId::None;
  2664. // Note that InterfaceWithSelfDecl always occurs inside an InterfaceDecl, so
  2665. // the import here can rely on the `Interface` already existing.
  2666. auto import_generic_with_self_id =
  2667. resolver.import_interfaces().Get(inst.interface_id).generic_with_self_id;
  2668. if (!const_id.has_value()) {
  2669. if (resolver.HasNewWork()) {
  2670. // This is the end of the first phase. Don't make a new generic yet if we
  2671. // already have new work.
  2672. return ResolveResult::Retry();
  2673. }
  2674. // Get the local interface ID from the constant value of the interface decl,
  2675. // which is either a GenericInterfaceType (if generic) or a FacetType (if
  2676. // not).
  2677. auto interface_const_inst_id =
  2678. resolver.local_constant_values().GetInstId(interface_const_id);
  2679. if (auto struct_value = resolver.local_insts().TryGetAs<SemIR::StructValue>(
  2680. interface_const_inst_id)) {
  2681. auto generic_interface_type =
  2682. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2683. struct_value->type_id);
  2684. local_interface_id = generic_interface_type.interface_id;
  2685. } else {
  2686. auto local_facet_type = resolver.local_insts().GetAs<SemIR::FacetType>(
  2687. interface_const_inst_id);
  2688. const auto& local_facet_type_info =
  2689. resolver.local_facet_types().Get(local_facet_type.facet_type_id);
  2690. auto single_interface = *local_facet_type_info.TryAsSingleExtend();
  2691. CARBON_KIND_SWITCH(single_interface) {
  2692. case CARBON_KIND(SemIR::SpecificInterface specific_interface): {
  2693. local_interface_id = specific_interface.interface_id;
  2694. break;
  2695. }
  2696. case CARBON_KIND(SemIR::SpecificNamedConstraint _): {
  2697. CARBON_FATAL(
  2698. "Unexpected NamedConstraint in InterfaceDecl value's facet type");
  2699. }
  2700. }
  2701. }
  2702. // On the second phase, create a local decl instruction with a local generic
  2703. // ID. Store that generic ID in the local interface.
  2704. const auto& import_generic =
  2705. resolver.import_generics().Get(import_generic_with_self_id);
  2706. SemIR::InterfaceWithSelfDecl interface_with_self_decl = {
  2707. .interface_id = SemIR::InterfaceId::None};
  2708. decl_id = AddPlaceholderImportedInst(resolver, import_generic.decl_id,
  2709. interface_with_self_decl);
  2710. generic_with_self_id =
  2711. ImportIncompleteGeneric(resolver, decl_id, import_generic_with_self_id);
  2712. interface_with_self_decl.interface_id = local_interface_id;
  2713. const_id = ReplacePlaceholderImportedInst(resolver, decl_id,
  2714. interface_with_self_decl);
  2715. resolver.local_interfaces().Get(local_interface_id).generic_with_self_id =
  2716. generic_with_self_id;
  2717. } else {
  2718. // On the third phase, get the interface, decl and generic IDs from the
  2719. // constant value of the decl (which is itself) from the second phase.
  2720. auto decl = resolver.local_insts().GetAs<SemIR::InterfaceWithSelfDecl>(
  2721. resolver.local_constant_values().GetInstId(const_id));
  2722. local_interface_id = decl.interface_id;
  2723. generic_with_self_id = resolver.local_interfaces()
  2724. .Get(local_interface_id)
  2725. .generic_with_self_id;
  2726. decl_id = resolver.local_generics().Get(generic_with_self_id).decl_id;
  2727. }
  2728. auto generic_with_self_data =
  2729. GetLocalGenericData(resolver, import_generic_with_self_id);
  2730. if (resolver.HasNewWork()) {
  2731. return ResolveResult::Retry(const_id, decl_id);
  2732. }
  2733. auto& local_interface = resolver.local_interfaces().Get(
  2734. resolver.local_insts()
  2735. .GetAs<SemIR::InterfaceWithSelfDecl>(decl_id)
  2736. .interface_id);
  2737. const auto& import_interface =
  2738. resolver.import_interfaces().Get(inst.interface_id);
  2739. auto& new_scope =
  2740. resolver.local_name_scopes().Get(local_interface.scope_with_self_id);
  2741. const auto& import_scope =
  2742. resolver.import_name_scopes().Get(import_interface.scope_with_self_id);
  2743. // Push a block so that we can add scoped instructions to it.
  2744. resolver.local_context().inst_block_stack().Push();
  2745. InitializeNameScopeAndImportRefs(resolver, import_scope, new_scope, decl_id,
  2746. SemIR::NameId::None,
  2747. local_interface.scope_without_self_id);
  2748. new_scope.set_is_interface_definition();
  2749. local_interface.associated_entities_id =
  2750. AddAssociatedEntities(resolver, local_interface.scope_with_self_id,
  2751. import_interface.associated_entities_id);
  2752. local_interface.body_block_with_self_id =
  2753. resolver.local_context().inst_block_stack().Pop();
  2754. return ResolveResult::FinishGenericOrDone(
  2755. resolver, const_id, decl_id, import_generic_with_self_id,
  2756. generic_with_self_id, generic_with_self_data);
  2757. }
  2758. // Make a declaration of a named constraint. This is done as a separate step
  2759. // from importing the constraint definition in order to resolve cycles.
  2760. static auto ImportNamedConstraintDecl(
  2761. ImportContext& context,
  2762. const SemIR::NamedConstraint& import_named_constraint,
  2763. SemIR::SpecificId enclosing_specific_id)
  2764. -> std::pair<SemIR::NamedConstraintId, SemIR::ConstantId> {
  2765. SemIR::NamedConstraintDecl named_constraint_decl = {
  2766. .type_id = SemIR::TypeType::TypeId,
  2767. .named_constraint_id = SemIR::NamedConstraintId::None,
  2768. .decl_block_id = SemIR::InstBlockId::Empty};
  2769. auto named_constraint_decl_id = AddPlaceholderImportedInst(
  2770. context, import_named_constraint.first_owning_decl_id,
  2771. named_constraint_decl);
  2772. // Start with an incomplete named constraint.
  2773. //
  2774. // The generic_with_self_id is constructed by the NamedConstraintWithSelfDecl
  2775. // instruction inside the NamedConstraintDecl's body.
  2776. named_constraint_decl.named_constraint_id =
  2777. context.local_named_constraints().Add(
  2778. {GetIncompleteLocalEntityBase(context, named_constraint_decl_id,
  2779. import_named_constraint),
  2780. {.scope_without_self_id = import_named_constraint.is_complete()
  2781. ? AddPlaceholderNameScope(context)
  2782. : SemIR::NameScopeId::None,
  2783. .scope_with_self_id = import_named_constraint.is_complete()
  2784. ? AddPlaceholderNameScope(context)
  2785. : SemIR::NameScopeId::None}});
  2786. if (import_named_constraint.has_parameters()) {
  2787. named_constraint_decl.type_id = GetGenericNamedConstraintType(
  2788. context.local_context(), named_constraint_decl.named_constraint_id,
  2789. enclosing_specific_id);
  2790. }
  2791. // Write the named constraint ID into the NameConstraintDecl.
  2792. auto interface_const_id = ReplacePlaceholderImportedInst(
  2793. context, named_constraint_decl_id, named_constraint_decl);
  2794. return {named_constraint_decl.named_constraint_id, interface_const_id};
  2795. }
  2796. // Imports the definition for a named constraint that has been imported as a
  2797. // forward declaration.
  2798. static auto ImportNamedConstraintDefinition(
  2799. ImportContext& context,
  2800. const SemIR::NamedConstraint& import_named_constraint,
  2801. SemIR::NamedConstraint& new_named_constraint, SemIR::InstId self_param_id)
  2802. -> void {
  2803. auto& new_scope = context.local_name_scopes().Get(
  2804. new_named_constraint.scope_without_self_id);
  2805. const auto& import_scope = context.import_name_scopes().Get(
  2806. import_named_constraint.scope_without_self_id);
  2807. // Push a block so that we can add scoped instructions to it.
  2808. context.local_context().inst_block_stack().Push();
  2809. InitializeNameScopeAndImportRefs(context, import_scope, new_scope,
  2810. new_named_constraint.first_owning_decl_id,
  2811. SemIR::NameId::None,
  2812. new_named_constraint.parent_scope_id);
  2813. new_named_constraint.body_block_without_self_id =
  2814. context.local_context().inst_block_stack().Pop();
  2815. new_named_constraint.self_param_id = self_param_id;
  2816. }
  2817. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2818. SemIR::NamedConstraintDecl inst,
  2819. SemIR::ConstantId named_constraint_const_id)
  2820. -> ResolveResult {
  2821. const auto& import_named_constraint =
  2822. resolver.import_named_constraints().Get(inst.named_constraint_id);
  2823. auto named_constraint_id = SemIR::NamedConstraintId::None;
  2824. if (!named_constraint_const_id.has_value()) {
  2825. auto import_specific_id = SemIR::SpecificId::None;
  2826. if (auto import_generic_named_constraint_type =
  2827. resolver.import_types().TryGetAs<SemIR::GenericNamedConstraintType>(
  2828. inst.type_id)) {
  2829. import_specific_id =
  2830. import_generic_named_constraint_type->enclosing_specific_id;
  2831. }
  2832. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2833. if (resolver.HasNewWork()) {
  2834. // This is the end of the first phase. Don't make a new interface yet if
  2835. // we already have new work.
  2836. return ResolveResult::Retry();
  2837. }
  2838. // On the second phase, create a forward declaration of the interface.
  2839. auto enclosing_specific_id =
  2840. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2841. std::tie(named_constraint_id, named_constraint_const_id) =
  2842. ImportNamedConstraintDecl(resolver, import_named_constraint,
  2843. enclosing_specific_id);
  2844. } else {
  2845. // On the third phase, compute the interface ID from the constant value of
  2846. // the declaration.
  2847. auto named_constraint_const_inst = resolver.local_insts().Get(
  2848. resolver.local_constant_values().GetInstId(named_constraint_const_id));
  2849. if (auto facet_type =
  2850. named_constraint_const_inst.TryAs<SemIR::FacetType>()) {
  2851. const SemIR::FacetTypeInfo& facet_type_info =
  2852. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2853. auto single = facet_type_info.TryAsSingleExtend();
  2854. CARBON_CHECK(single);
  2855. named_constraint_id =
  2856. std::get<SemIR::SpecificNamedConstraint>(*single).named_constraint_id;
  2857. } else {
  2858. auto generic_named_constraint_type =
  2859. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  2860. named_constraint_const_inst.type_id());
  2861. named_constraint_id = generic_named_constraint_type.named_constraint_id;
  2862. }
  2863. }
  2864. auto parent_scope_id =
  2865. GetLocalNameScopeId(resolver, import_named_constraint.parent_scope_id);
  2866. auto implicit_param_patterns = GetLocalInstBlockContents(
  2867. resolver, import_named_constraint.implicit_param_patterns_id);
  2868. auto param_patterns = GetLocalInstBlockContents(
  2869. resolver, import_named_constraint.param_patterns_id);
  2870. auto generic_data =
  2871. GetLocalGenericData(resolver, import_named_constraint.generic_id);
  2872. auto require_impls = GetLocalRequireImplsBlockContents(
  2873. resolver, import_named_constraint.require_impls_block_id);
  2874. std::optional<SemIR::InstId> self_param_id;
  2875. if (import_named_constraint.is_complete()) {
  2876. self_param_id =
  2877. GetLocalConstantInstId(resolver, import_named_constraint.self_param_id);
  2878. // Importing the `generic_with_self_id` imports the
  2879. // NamedConstraintWithSelfDecl which (if it's complete) marks the local
  2880. // named constraint as complete. The NamedConstraintWithSelfDecl also sets
  2881. // the `generic_with_self_id` field on the local interface.
  2882. GetLocalConstantId(resolver, import_named_constraint.generic_with_self_id);
  2883. }
  2884. auto& new_named_constraint =
  2885. resolver.local_named_constraints().Get(named_constraint_id);
  2886. if (resolver.HasNewWork()) {
  2887. return ResolveResult::Retry(named_constraint_const_id,
  2888. new_named_constraint.first_decl_id());
  2889. }
  2890. new_named_constraint.parent_scope_id = parent_scope_id;
  2891. new_named_constraint.implicit_param_patterns_id =
  2892. GetLocalCanonicalInstBlockId(
  2893. resolver, import_named_constraint.implicit_param_patterns_id,
  2894. implicit_param_patterns);
  2895. new_named_constraint.param_patterns_id = GetLocalCanonicalInstBlockId(
  2896. resolver, import_named_constraint.param_patterns_id, param_patterns);
  2897. new_named_constraint.require_impls_block_id =
  2898. GetLocalCanonicalRequireImplsBlockId(
  2899. resolver, import_named_constraint.require_impls_block_id,
  2900. require_impls);
  2901. if (import_named_constraint.is_complete()) {
  2902. CARBON_CHECK(self_param_id);
  2903. ImportNamedConstraintDefinition(resolver, import_named_constraint,
  2904. new_named_constraint, *self_param_id);
  2905. }
  2906. // The named constraint's `generic_with_self_id` is filled out and finished by
  2907. // importing the NamedConstraintWithSelfDecl instruction which we find inside
  2908. // the NamedConstraintDecl.
  2909. return ResolveResult::FinishGenericOrDone(
  2910. resolver, named_constraint_const_id, new_named_constraint.first_decl_id(),
  2911. import_named_constraint.generic_id, new_named_constraint.generic_id,
  2912. generic_data);
  2913. }
  2914. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2915. SemIR::NamedConstraintWithSelfDecl inst,
  2916. SemIR::ConstantId const_id) -> ResolveResult {
  2917. auto constraint_const_id =
  2918. GetLocalConstantId(resolver, resolver.import_named_constraints()
  2919. .Get(inst.named_constraint_id)
  2920. .first_owning_decl_id);
  2921. // These are set differently in each phase.
  2922. auto decl_id = SemIR::InstId::None;
  2923. auto local_constraint_id = SemIR::NamedConstraintId::None;
  2924. auto generic_with_self_id = SemIR::GenericId::None;
  2925. // Note that NamedConstraintWithSelfDecl always occurs inside an
  2926. // NamedConstraintDecl, so the import here can rely on the `NamedConstraint`
  2927. // already existing.
  2928. auto import_generic_with_self_id = resolver.import_named_constraints()
  2929. .Get(inst.named_constraint_id)
  2930. .generic_with_self_id;
  2931. if (!const_id.has_value()) {
  2932. if (resolver.HasNewWork()) {
  2933. // This is the end of the first phase. Don't make a new generic yet if we
  2934. // already have new work.
  2935. return ResolveResult::Retry();
  2936. }
  2937. // Get the local named constraint ID from the constant value of the named
  2938. // constraint decl, which is either a GenericNamedConstraintType (if
  2939. // generic) or a FacetType (if not).
  2940. auto constraint_const_inst_id =
  2941. resolver.local_constant_values().GetInstId(constraint_const_id);
  2942. if (auto struct_value = resolver.local_insts().TryGetAs<SemIR::StructValue>(
  2943. constraint_const_inst_id)) {
  2944. auto generic_constraint_type =
  2945. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  2946. struct_value->type_id);
  2947. local_constraint_id = generic_constraint_type.named_constraint_id;
  2948. } else {
  2949. auto local_facet_type = resolver.local_insts().GetAs<SemIR::FacetType>(
  2950. constraint_const_inst_id);
  2951. const auto& local_facet_type_info =
  2952. resolver.local_facet_types().Get(local_facet_type.facet_type_id);
  2953. auto single_interface = *local_facet_type_info.TryAsSingleExtend();
  2954. CARBON_KIND_SWITCH(single_interface) {
  2955. case CARBON_KIND(SemIR::SpecificNamedConstraint specific_constraint): {
  2956. local_constraint_id = specific_constraint.named_constraint_id;
  2957. break;
  2958. }
  2959. case CARBON_KIND(SemIR::SpecificInterface _): {
  2960. CARBON_FATAL(
  2961. "Unexpected Interface in NamedConstraintDecl value's facet type");
  2962. }
  2963. }
  2964. }
  2965. // On the second phase, create a local decl instruction with a local generic
  2966. // ID. Store that generic ID in the local interface.
  2967. const auto& import_generic =
  2968. resolver.import_generics().Get(import_generic_with_self_id);
  2969. SemIR::NamedConstraintWithSelfDecl constraint_with_self_decl = {
  2970. .named_constraint_id = SemIR::NamedConstraintId::None};
  2971. decl_id = AddPlaceholderImportedInst(resolver, import_generic.decl_id,
  2972. constraint_with_self_decl);
  2973. generic_with_self_id =
  2974. ImportIncompleteGeneric(resolver, decl_id, import_generic_with_self_id);
  2975. constraint_with_self_decl.named_constraint_id = local_constraint_id;
  2976. const_id = ReplacePlaceholderImportedInst(resolver, decl_id,
  2977. constraint_with_self_decl);
  2978. resolver.local_named_constraints()
  2979. .Get(local_constraint_id)
  2980. .generic_with_self_id = generic_with_self_id;
  2981. } else {
  2982. // On the third phase, get the interface, decl and generic IDs from the
  2983. // constant value of the decl (which is itself) from the second phase.
  2984. auto decl =
  2985. resolver.local_insts().GetAs<SemIR::NamedConstraintWithSelfDecl>(
  2986. resolver.local_constant_values().GetInstId(const_id));
  2987. local_constraint_id = decl.named_constraint_id;
  2988. generic_with_self_id = resolver.local_named_constraints()
  2989. .Get(local_constraint_id)
  2990. .generic_with_self_id;
  2991. decl_id = resolver.local_generics().Get(generic_with_self_id).decl_id;
  2992. }
  2993. auto generic_with_self_data =
  2994. GetLocalGenericData(resolver, import_generic_with_self_id);
  2995. if (resolver.HasNewWork()) {
  2996. return ResolveResult::Retry(const_id, decl_id);
  2997. }
  2998. auto& local_constraint = resolver.local_named_constraints().Get(
  2999. resolver.local_insts()
  3000. .GetAs<SemIR::NamedConstraintWithSelfDecl>(decl_id)
  3001. .named_constraint_id);
  3002. const auto& import_constraint =
  3003. resolver.import_named_constraints().Get(inst.named_constraint_id);
  3004. auto& new_scope =
  3005. resolver.local_name_scopes().Get(local_constraint.scope_with_self_id);
  3006. const auto& import_scope =
  3007. resolver.import_name_scopes().Get(import_constraint.scope_with_self_id);
  3008. // Push a block so that we can add scoped instructions to it.
  3009. resolver.local_context().inst_block_stack().Push();
  3010. InitializeNameScopeAndImportRefs(resolver, import_scope, new_scope, decl_id,
  3011. SemIR::NameId::None,
  3012. local_constraint.scope_without_self_id);
  3013. local_constraint.complete = import_constraint.complete;
  3014. local_constraint.body_block_with_self_id =
  3015. resolver.local_context().inst_block_stack().Pop();
  3016. return ResolveResult::FinishGenericOrDone(
  3017. resolver, const_id, decl_id, import_generic_with_self_id,
  3018. generic_with_self_id, generic_with_self_data);
  3019. }
  3020. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3021. SemIR::FacetAccessType inst) -> ResolveResult {
  3022. auto facet_value_inst_id =
  3023. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  3024. if (resolver.HasNewWork()) {
  3025. return ResolveResult::Retry();
  3026. }
  3027. return ResolveResult::Deduplicated<SemIR::FacetAccessType>(
  3028. resolver, {.type_id = SemIR::TypeType::TypeId,
  3029. .facet_value_inst_id = facet_value_inst_id});
  3030. }
  3031. // Collects and assigns constants for a `FacetTypeInfo`. Discards constants when
  3032. // `local_facet_type_info` is null.
  3033. static auto ResolveFacetTypeInfo(
  3034. ImportRefResolver& resolver,
  3035. const SemIR::FacetTypeInfo& import_facet_type_info,
  3036. SemIR::FacetTypeInfo* local_facet_type_info) -> void {
  3037. if (local_facet_type_info) {
  3038. local_facet_type_info->extend_constraints.reserve(
  3039. import_facet_type_info.extend_constraints.size());
  3040. }
  3041. for (auto interface : import_facet_type_info.extend_constraints) {
  3042. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  3043. if (local_facet_type_info) {
  3044. local_facet_type_info->extend_constraints.push_back(
  3045. GetLocalSpecificInterface(resolver, interface, data));
  3046. }
  3047. }
  3048. if (local_facet_type_info) {
  3049. local_facet_type_info->self_impls_constraints.reserve(
  3050. import_facet_type_info.self_impls_constraints.size());
  3051. }
  3052. for (auto interface : import_facet_type_info.self_impls_constraints) {
  3053. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  3054. if (local_facet_type_info) {
  3055. local_facet_type_info->self_impls_constraints.push_back(
  3056. GetLocalSpecificInterface(resolver, interface, data));
  3057. }
  3058. }
  3059. if (local_facet_type_info) {
  3060. local_facet_type_info->extend_named_constraints.reserve(
  3061. import_facet_type_info.extend_named_constraints.size());
  3062. }
  3063. for (auto constraint : import_facet_type_info.extend_named_constraints) {
  3064. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  3065. if (local_facet_type_info) {
  3066. local_facet_type_info->extend_named_constraints.push_back(
  3067. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  3068. }
  3069. }
  3070. if (local_facet_type_info) {
  3071. local_facet_type_info->self_impls_named_constraints.reserve(
  3072. import_facet_type_info.self_impls_named_constraints.size());
  3073. }
  3074. for (auto constraint : import_facet_type_info.self_impls_named_constraints) {
  3075. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  3076. if (local_facet_type_info) {
  3077. local_facet_type_info->self_impls_named_constraints.push_back(
  3078. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  3079. }
  3080. }
  3081. if (local_facet_type_info) {
  3082. local_facet_type_info->rewrite_constraints.reserve(
  3083. import_facet_type_info.rewrite_constraints.size());
  3084. }
  3085. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  3086. auto lhs_id = GetLocalConstantInstId(resolver, rewrite.lhs_id);
  3087. auto rhs_id = GetLocalConstantInstId(resolver, rewrite.rhs_id);
  3088. if (local_facet_type_info) {
  3089. local_facet_type_info->rewrite_constraints.push_back(
  3090. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  3091. }
  3092. }
  3093. }
  3094. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3095. SemIR::FacetType inst) -> ResolveResult {
  3096. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3097. const SemIR::FacetTypeInfo& import_facet_type_info =
  3098. resolver.import_facet_types().Get(inst.facet_type_id);
  3099. // Ensure values are imported, but discard them to avoid allocations.
  3100. ResolveFacetTypeInfo(resolver, import_facet_type_info,
  3101. /*local_facet_type_info=*/nullptr);
  3102. if (resolver.HasNewWork()) {
  3103. return ResolveResult::Retry();
  3104. }
  3105. SemIR::FacetTypeInfo local_facet_type_info = {
  3106. // TODO: Also process the other requirements.
  3107. .other_requirements = import_facet_type_info.other_requirements};
  3108. // Re-resolve and add values to the local `FacetTypeInfo`.
  3109. ResolveFacetTypeInfo(resolver, import_facet_type_info,
  3110. &local_facet_type_info);
  3111. SemIR::FacetTypeId facet_type_id =
  3112. resolver.local_facet_types().Add(std::move(local_facet_type_info));
  3113. return ResolveResult::Deduplicated<SemIR::FacetType>(
  3114. resolver,
  3115. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  3116. }
  3117. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3118. SemIR::FacetValue inst) -> ResolveResult {
  3119. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3120. auto type_inst_id = GetLocalTypeInstId(resolver, inst.type_inst_id);
  3121. auto witnesses = GetLocalInstBlockContents(resolver, inst.witnesses_block_id);
  3122. if (resolver.HasNewWork()) {
  3123. return ResolveResult::Retry();
  3124. }
  3125. auto witnesses_block_id = SemIR::InstBlockId::None;
  3126. if (inst.witnesses_block_id.has_value()) {
  3127. witnesses_block_id =
  3128. AddCanonicalWitnessesBlock(resolver.local_ir(), witnesses);
  3129. }
  3130. return ResolveResult::Deduplicated<SemIR::FacetValue>(
  3131. resolver,
  3132. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3133. .type_inst_id = type_inst_id,
  3134. .witnesses_block_id = witnesses_block_id});
  3135. }
  3136. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3137. SemIR::LookupImplWitness inst)
  3138. -> ResolveResult {
  3139. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3140. SemIR::WitnessType::TypeInstId);
  3141. auto query_self_inst_id =
  3142. GetLocalConstantInstId(resolver, inst.query_self_inst_id);
  3143. const auto& import_specific_interface =
  3144. resolver.import_specific_interfaces().Get(
  3145. inst.query_specific_interface_id);
  3146. auto data =
  3147. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  3148. if (resolver.HasNewWork()) {
  3149. return ResolveResult::Retry();
  3150. }
  3151. auto specific_interface =
  3152. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  3153. auto query_specific_interface_id =
  3154. resolver.local_specific_interfaces().Add(specific_interface);
  3155. return ResolveResult::Deduplicated<SemIR::LookupImplWitness>(
  3156. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3157. SemIR::WitnessType::TypeInstId),
  3158. .query_self_inst_id = query_self_inst_id,
  3159. .query_specific_interface_id = query_specific_interface_id});
  3160. }
  3161. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3162. SemIR::ImplWitness inst) -> ResolveResult {
  3163. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3164. SemIR::WitnessType::TypeInstId);
  3165. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3166. auto witness_table_id =
  3167. GetLocalConstantInstId(resolver, inst.witness_table_id);
  3168. if (resolver.HasNewWork()) {
  3169. return ResolveResult::Retry();
  3170. }
  3171. auto specific_id =
  3172. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3173. return ResolveResult::Deduplicated<SemIR::ImplWitness>(
  3174. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3175. SemIR::WitnessType::TypeInstId),
  3176. .witness_table_id = witness_table_id,
  3177. .specific_id = specific_id});
  3178. }
  3179. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3180. SemIR::ImplWitnessAccess inst)
  3181. -> ResolveResult {
  3182. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3183. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  3184. if (resolver.HasNewWork()) {
  3185. return ResolveResult::Retry();
  3186. }
  3187. return ResolveResult::Deduplicated<SemIR::ImplWitnessAccess>(
  3188. resolver,
  3189. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3190. .witness_id = witness_id,
  3191. .index = inst.index});
  3192. }
  3193. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3194. SemIR::ImplWitnessTable inst,
  3195. SemIR::InstId import_inst_id) -> ResolveResult {
  3196. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  3197. auto import_decl_inst_id = import_impl.first_decl_id();
  3198. auto local_decl_inst_id =
  3199. GetLocalConstantInstId(resolver, import_decl_inst_id);
  3200. if (resolver.HasNewWork()) {
  3201. return ResolveResult::Retry();
  3202. }
  3203. auto impl_decl =
  3204. resolver.local_insts().GetAs<SemIR::ImplDecl>(local_decl_inst_id);
  3205. auto impl_id = impl_decl.impl_id;
  3206. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  3207. // Create a corresponding instruction to represent the table.
  3208. return ResolveResult::Unique<SemIR::ImplWitnessTable>(
  3209. resolver, import_inst_id,
  3210. {.elements_id = elements_id, .impl_id = impl_id});
  3211. }
  3212. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3213. SemIR::InitForm inst) -> ResolveResult {
  3214. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3215. auto type_component_const_id =
  3216. GetLocalConstantId(resolver, inst.type_component_inst_id);
  3217. if (resolver.HasNewWork()) {
  3218. return ResolveResult::Retry();
  3219. }
  3220. return ResolveResult::Deduplicated<SemIR::InitForm>(
  3221. resolver,
  3222. SemIR::InitForm{
  3223. .type_id =
  3224. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3225. .type_component_inst_id = resolver.local_types().GetTypeInstId(
  3226. resolver.local_types().GetTypeIdForTypeConstantId(
  3227. type_component_const_id)),
  3228. .index = inst.index});
  3229. }
  3230. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3231. SemIR::IntValue inst) -> ResolveResult {
  3232. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3233. if (resolver.HasNewWork()) {
  3234. return ResolveResult::Retry();
  3235. }
  3236. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  3237. // to add a new canonical int in this IR.
  3238. auto int_id = inst.int_id.is_embedded_value()
  3239. ? inst.int_id
  3240. : resolver.local_ints().AddSigned(
  3241. resolver.import_ints().Get(inst.int_id));
  3242. return ResolveResult::Deduplicated<SemIR::IntValue>(
  3243. resolver,
  3244. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3245. .int_id = int_id});
  3246. }
  3247. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3248. SemIR::IntType inst) -> ResolveResult {
  3249. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3250. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  3251. if (resolver.HasNewWork()) {
  3252. return ResolveResult::Retry();
  3253. }
  3254. return ResolveResult::Deduplicated<SemIR::IntType>(
  3255. resolver, {.type_id = SemIR::TypeType::TypeId,
  3256. .int_kind = inst.int_kind,
  3257. .bit_width_id = bit_width_id});
  3258. }
  3259. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3260. SemIR::Namespace inst,
  3261. SemIR::InstId import_inst_id) -> ResolveResult {
  3262. const auto& name_scope =
  3263. resolver.import_name_scopes().Get(inst.name_scope_id);
  3264. // A package from a different file becomes a child of the package here, as it
  3265. // would be if it were imported.
  3266. auto parent_scope_id =
  3267. inst.name_scope_id == SemIR::NameScopeId::Package
  3268. ? SemIR::NameScopeId::Package
  3269. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  3270. if (resolver.HasNewWork()) {
  3271. return ResolveResult::Retry();
  3272. }
  3273. auto namespace_type_id = GetSingletonType(resolver.local_context(),
  3274. SemIR::NamespaceType::TypeInstId);
  3275. auto namespace_decl =
  3276. SemIR::Namespace{.type_id = namespace_type_id,
  3277. .name_scope_id = SemIR::NameScopeId::None,
  3278. .import_id = SemIR::AbsoluteInstId::None};
  3279. auto inst_id =
  3280. AddPlaceholderImportedInst(resolver, import_inst_id, namespace_decl);
  3281. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  3282. namespace_decl.name_scope_id =
  3283. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  3284. // Namespaces from this package are eagerly imported, so anything we load here
  3285. // must be a closed import.
  3286. resolver.local_name_scopes()
  3287. .Get(namespace_decl.name_scope_id)
  3288. .set_is_closed_import(true);
  3289. auto namespace_const_id =
  3290. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  3291. return {.const_id = namespace_const_id};
  3292. }
  3293. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3294. SemIR::PatternType inst) -> ResolveResult {
  3295. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3296. auto scrutinee_type_inst_id =
  3297. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  3298. if (resolver.HasNewWork()) {
  3299. return ResolveResult::Retry();
  3300. }
  3301. return ResolveResult::Deduplicated<SemIR::PatternType>(
  3302. resolver, {.type_id = SemIR::TypeType::TypeId,
  3303. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  3304. }
  3305. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3306. SemIR::PointerType inst) -> ResolveResult {
  3307. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3308. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  3309. if (resolver.HasNewWork()) {
  3310. return ResolveResult::Retry();
  3311. }
  3312. return ResolveResult::Deduplicated<SemIR::PointerType>(
  3313. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  3314. }
  3315. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3316. SemIR::RequireCompleteType inst)
  3317. -> ResolveResult {
  3318. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3319. SemIR::WitnessType::TypeInstId);
  3320. auto complete_type_inst_id =
  3321. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  3322. if (resolver.HasNewWork()) {
  3323. return ResolveResult::Retry();
  3324. }
  3325. return ResolveResult::Deduplicated<SemIR::RequireCompleteType>(
  3326. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3327. SemIR::WitnessType::TypeInstId),
  3328. .complete_type_inst_id = complete_type_inst_id});
  3329. }
  3330. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3331. SemIR::RequireSpecificDefinition inst)
  3332. -> ResolveResult {
  3333. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3334. SemIR::RequireSpecificDefinitionType::TypeInstId);
  3335. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3336. if (resolver.HasNewWork()) {
  3337. return ResolveResult::Retry();
  3338. }
  3339. auto specific_id =
  3340. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3341. return ResolveResult::Deduplicated<SemIR::RequireSpecificDefinition>(
  3342. resolver, {.type_id = GetSingletonType(
  3343. resolver.local_context(),
  3344. SemIR::RequireSpecificDefinitionType::TypeInstId),
  3345. .specific_id = specific_id});
  3346. }
  3347. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3348. SemIR::ReturnSlotPattern inst,
  3349. SemIR::InstId import_inst_id) -> ResolveResult {
  3350. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3351. if (resolver.HasNewWork()) {
  3352. return ResolveResult::Retry();
  3353. }
  3354. return ResolveResult::Unique<SemIR::ReturnSlotPattern>(
  3355. resolver, import_inst_id,
  3356. {.type_id =
  3357. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3358. .type_inst_id = SemIR::TypeInstId::None});
  3359. }
  3360. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3361. SemIR::SpecificFunction inst) -> ResolveResult {
  3362. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3363. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3364. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3365. if (resolver.HasNewWork()) {
  3366. return ResolveResult::Retry();
  3367. }
  3368. auto type_id =
  3369. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id);
  3370. auto specific_id =
  3371. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3372. return ResolveResult::Deduplicated<SemIR::SpecificFunction>(
  3373. resolver,
  3374. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3375. }
  3376. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3377. SemIR::SpecificImplFunction inst)
  3378. -> ResolveResult {
  3379. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3380. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3381. if (resolver.HasNewWork()) {
  3382. return ResolveResult::Retry();
  3383. }
  3384. auto type_id = GetSingletonType(resolver.local_context(),
  3385. SemIR::SpecificFunctionType::TypeInstId);
  3386. auto specific_id =
  3387. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3388. return ResolveResult::Deduplicated<SemIR::SpecificImplFunction>(
  3389. resolver,
  3390. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3391. }
  3392. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3393. SemIR::StructAccess inst) -> ResolveResult {
  3394. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3395. auto struct_id = GetLocalConstantInstId(resolver, inst.struct_id);
  3396. if (resolver.HasNewWork()) {
  3397. return ResolveResult::Retry();
  3398. }
  3399. // A `struct_access` constant requires its struct operand to have a complete
  3400. // type.
  3401. CompleteTypeOrCheckFail(resolver.local_context(),
  3402. resolver.local_insts().Get(struct_id).type_id());
  3403. return ResolveResult::Deduplicated<SemIR::StructAccess>(
  3404. resolver,
  3405. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3406. .struct_id = struct_id,
  3407. .index = inst.index});
  3408. }
  3409. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3410. SemIR::StructType inst) -> ResolveResult {
  3411. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3412. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  3413. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  3414. field_type_inst_ids.reserve(orig_fields.size());
  3415. for (auto field : orig_fields) {
  3416. field_type_inst_ids.push_back(
  3417. GetLocalTypeInstId(resolver, field.type_inst_id));
  3418. }
  3419. if (resolver.HasNewWork()) {
  3420. return ResolveResult::Retry();
  3421. }
  3422. // Prepare a vector of fields for GetStructType.
  3423. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  3424. new_fields.reserve(orig_fields.size());
  3425. for (auto [orig_field, field_type_inst_id] :
  3426. llvm::zip_equal(orig_fields, field_type_inst_ids)) {
  3427. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  3428. new_fields.push_back(
  3429. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  3430. }
  3431. return ResolveResult::Deduplicated<SemIR::StructType>(
  3432. resolver, {.type_id = SemIR::TypeType::TypeId,
  3433. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  3434. new_fields)});
  3435. }
  3436. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3437. SemIR::StructValue inst) -> ResolveResult {
  3438. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3439. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3440. if (resolver.HasNewWork()) {
  3441. return ResolveResult::Retry();
  3442. }
  3443. return ResolveResult::Deduplicated<SemIR::StructValue>(
  3444. resolver,
  3445. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3446. .elements_id =
  3447. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3448. }
  3449. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3450. SemIR::SymbolicBindingType inst)
  3451. -> ResolveResult {
  3452. auto facet_value_inst_id =
  3453. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  3454. if (resolver.HasNewWork()) {
  3455. return ResolveResult::Retry();
  3456. }
  3457. auto entity_name_id =
  3458. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  3459. return ResolveResult::Deduplicated<SemIR::SymbolicBindingType>(
  3460. resolver, {.type_id = SemIR::TypeType::TypeId,
  3461. .entity_name_id = entity_name_id,
  3462. .facet_value_inst_id = facet_value_inst_id});
  3463. }
  3464. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3465. SemIR::TupleAccess inst) -> ResolveResult {
  3466. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3467. auto tuple_id = GetLocalConstantInstId(resolver, inst.tuple_id);
  3468. if (resolver.HasNewWork()) {
  3469. return ResolveResult::Retry();
  3470. }
  3471. // A `tuple_access` constant requires its struct operand to have a complete
  3472. // type.
  3473. CompleteTypeOrCheckFail(resolver.local_context(),
  3474. resolver.local_insts().Get(tuple_id).type_id());
  3475. return ResolveResult::Deduplicated<SemIR::TupleAccess>(
  3476. resolver,
  3477. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3478. .tuple_id = tuple_id,
  3479. .index = inst.index});
  3480. }
  3481. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3482. SemIR::TuplePattern inst,
  3483. SemIR::InstId import_inst_id) -> ResolveResult {
  3484. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3485. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  3486. if (resolver.HasNewWork()) {
  3487. return ResolveResult::Retry();
  3488. }
  3489. return ResolveResult::Unique<SemIR::TuplePattern>(
  3490. resolver, import_inst_id,
  3491. {.type_id =
  3492. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3493. .elements_id =
  3494. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements)});
  3495. }
  3496. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3497. SemIR::TupleType inst) -> ResolveResult {
  3498. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3499. auto orig_type_inst_ids =
  3500. resolver.import_inst_blocks().Get(inst.type_elements_id);
  3501. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  3502. // type system that its holding `TypeInstId` elements.
  3503. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  3504. type_inst_ids.reserve(orig_type_inst_ids.size());
  3505. for (auto elem_type_inst_id :
  3506. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  3507. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  3508. }
  3509. if (resolver.HasNewWork()) {
  3510. return ResolveResult::Retry();
  3511. }
  3512. return ResolveResult::Deduplicated<SemIR::TupleType>(
  3513. resolver, {.type_id = SemIR::TypeType::TypeId,
  3514. .type_elements_id = GetLocalCanonicalInstBlockId(
  3515. resolver, inst.type_elements_id, type_inst_ids)});
  3516. }
  3517. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3518. SemIR::TupleValue inst) -> ResolveResult {
  3519. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3520. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3521. if (resolver.HasNewWork()) {
  3522. return ResolveResult::Retry();
  3523. }
  3524. return ResolveResult::Deduplicated<SemIR::TupleValue>(
  3525. resolver,
  3526. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3527. .elements_id =
  3528. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3529. }
  3530. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3531. SemIR::UnboundElementType inst)
  3532. -> ResolveResult {
  3533. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3534. auto class_const_inst_id =
  3535. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  3536. auto elem_const_inst_id =
  3537. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  3538. if (resolver.HasNewWork()) {
  3539. return ResolveResult::Retry();
  3540. }
  3541. return ResolveResult::Deduplicated<SemIR::UnboundElementType>(
  3542. resolver, {.type_id = SemIR::TypeType::TypeId,
  3543. .class_type_inst_id = class_const_inst_id,
  3544. .element_type_inst_id = elem_const_inst_id});
  3545. }
  3546. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3547. SemIR::VarPattern inst,
  3548. SemIR::InstId import_inst_id) -> ResolveResult {
  3549. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3550. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  3551. if (resolver.HasNewWork()) {
  3552. return ResolveResult::Retry();
  3553. }
  3554. return ResolveResult::Unique<SemIR::VarPattern>(
  3555. resolver, import_inst_id,
  3556. {.type_id =
  3557. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3558. .subpattern_id = subpattern_id});
  3559. }
  3560. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3561. SemIR::VarStorage inst,
  3562. SemIR::InstId import_inst_id) -> ResolveResult {
  3563. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3564. auto pattern_id = GetLocalConstantInstId(resolver, inst.pattern_id);
  3565. if (resolver.HasNewWork()) {
  3566. return ResolveResult::Retry();
  3567. }
  3568. return ResolveResult::Unique<SemIR::VarStorage>(
  3569. resolver, import_inst_id,
  3570. {.type_id =
  3571. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3572. .pattern_id = pattern_id});
  3573. }
  3574. // Tries to resolve the InstId, returning a canonical constant when ready, or
  3575. // `None` if more has been added to the stack. This is the same as
  3576. // TryResolveInst, except that it may resolve symbolic constants as canonical
  3577. // constants instead of as constants associated with a particular generic.
  3578. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  3579. SemIR::InstId inst_id,
  3580. SemIR::ConstantId const_id)
  3581. -> ResolveResult {
  3582. // These instruction types are imported across multiple phases to arrive at
  3583. // their constant value. We can't just import their constant value instruction
  3584. // directly.
  3585. auto untyped_inst = resolver.import_insts().GetWithAttachedType(inst_id);
  3586. CARBON_KIND_SWITCH(untyped_inst) {
  3587. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  3588. return TryResolveTypedInst(resolver, inst, const_id);
  3589. }
  3590. case CARBON_KIND(SemIR::ClassDecl inst): {
  3591. return TryResolveTypedInst(resolver, inst, const_id);
  3592. }
  3593. case CARBON_KIND(SemIR::FunctionDecl inst): {
  3594. return TryResolveTypedInst(resolver, inst, const_id);
  3595. }
  3596. case CARBON_KIND(SemIR::ImplDecl inst): {
  3597. return TryResolveTypedInst(resolver, inst, const_id);
  3598. }
  3599. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  3600. return TryResolveTypedInst(resolver, inst, const_id);
  3601. }
  3602. case CARBON_KIND(SemIR::InterfaceWithSelfDecl inst): {
  3603. return TryResolveTypedInst(resolver, inst, const_id);
  3604. }
  3605. case CARBON_KIND(SemIR::NamedConstraintDecl inst): {
  3606. return TryResolveTypedInst(resolver, inst, const_id);
  3607. }
  3608. case CARBON_KIND(SemIR::NamedConstraintWithSelfDecl inst): {
  3609. return TryResolveTypedInst(resolver, inst, const_id);
  3610. }
  3611. case CARBON_KIND(SemIR::RequireImplsDecl inst): {
  3612. return TryResolveTypedInst(resolver, inst, const_id);
  3613. }
  3614. default:
  3615. break;
  3616. }
  3617. // Other instructions are imported in a single phase (once their dependencies
  3618. // are all imported).
  3619. CARBON_CHECK(!const_id.has_value());
  3620. auto inst_constant_id = resolver.import_constant_values().Get(inst_id);
  3621. if (!inst_constant_id.is_constant()) {
  3622. // TODO: Import of non-constant BindNames happens when importing `let`
  3623. // declarations.
  3624. CARBON_CHECK(resolver.import_insts().Is<SemIR::AnyBinding>(inst_id),
  3625. "TryResolveInst on non-constant instruction {0}", inst_id);
  3626. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  3627. }
  3628. // Import the canonical constant value instruction for `inst_id` directly. We
  3629. // don't try to import the non-canonical `inst_id`.
  3630. auto constant_inst_id =
  3631. resolver.import_constant_values().GetInstId(inst_constant_id);
  3632. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  3633. constant_inst_id) == constant_inst_id,
  3634. "Constant value of constant instruction should refer to "
  3635. "the same instruction");
  3636. if (SemIR::IsSingletonInstId(constant_inst_id)) {
  3637. // Constants for builtins can be directly copied.
  3638. return ResolveResult::Done(
  3639. resolver.local_constant_values().Get(constant_inst_id));
  3640. }
  3641. auto untyped_constant_inst =
  3642. resolver.import_insts().GetWithAttachedType(constant_inst_id);
  3643. CARBON_KIND_SWITCH(untyped_constant_inst) {
  3644. case CARBON_KIND(SemIR::AdaptDecl inst): {
  3645. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3646. }
  3647. case CARBON_KIND(SemIR::ArrayType inst): {
  3648. return TryResolveTypedInst(resolver, inst);
  3649. }
  3650. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  3651. return TryResolveTypedInst(resolver, inst);
  3652. }
  3653. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  3654. return TryResolveTypedInst(resolver, inst);
  3655. }
  3656. case CARBON_KIND(SemIR::BaseDecl inst): {
  3657. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3658. }
  3659. case CARBON_KIND(SemIR::AliasBinding inst): {
  3660. return TryResolveTypedInst(resolver, inst);
  3661. }
  3662. case CARBON_KIND(SemIR::SymbolicBinding inst): {
  3663. return TryResolveTypedInst(resolver, inst);
  3664. }
  3665. case CARBON_KIND(SemIR::BoolLiteral inst): {
  3666. return TryResolveTypedInst(resolver, inst);
  3667. }
  3668. case CARBON_KIND(SemIR::BoundMethod inst): {
  3669. return TryResolveTypedInst(resolver, inst);
  3670. }
  3671. case CARBON_KIND(SemIR::Call inst): {
  3672. return TryResolveTypedInst(resolver, inst);
  3673. }
  3674. case CARBON_KIND(SemIR::CharLiteralValue inst): {
  3675. return TryResolveTypedInst(resolver, inst);
  3676. }
  3677. case CARBON_KIND(SemIR::ClassType inst): {
  3678. return TryResolveTypedInst(resolver, inst);
  3679. }
  3680. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  3681. return TryResolveTypedInst(resolver, inst);
  3682. }
  3683. case CARBON_KIND(SemIR::ConstType inst): {
  3684. return TryResolveTypedInst(resolver, inst);
  3685. }
  3686. case CARBON_KIND(SemIR::CppOverloadSetType inst): {
  3687. return TryResolveTypedInst(resolver, inst);
  3688. }
  3689. case CARBON_KIND(SemIR::CppOverloadSetValue inst): {
  3690. return TryResolveTypedInst(resolver, inst);
  3691. }
  3692. case CARBON_KIND(SemIR::CustomWitness inst): {
  3693. return TryResolveTypedInst(resolver, inst);
  3694. }
  3695. case CARBON_KIND(SemIR::ExportDecl inst): {
  3696. return TryResolveTypedInst(resolver, inst);
  3697. }
  3698. case CARBON_KIND(SemIR::FacetAccessType inst): {
  3699. return TryResolveTypedInst(resolver, inst);
  3700. }
  3701. case CARBON_KIND(SemIR::FacetType inst): {
  3702. return TryResolveTypedInst(resolver, inst);
  3703. }
  3704. case CARBON_KIND(SemIR::FacetValue inst): {
  3705. return TryResolveTypedInst(resolver, inst);
  3706. }
  3707. case CARBON_KIND(SemIR::FieldDecl inst): {
  3708. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3709. }
  3710. case CARBON_KIND(SemIR::FloatLiteralValue inst): {
  3711. return TryResolveTypedInst(resolver, inst);
  3712. }
  3713. case CARBON_KIND(SemIR::FloatType inst): {
  3714. return TryResolveTypedInst(resolver, inst);
  3715. }
  3716. case CARBON_KIND(SemIR::FloatValue inst): {
  3717. return TryResolveTypedInst(resolver, inst);
  3718. }
  3719. case CARBON_KIND(SemIR::FunctionType inst): {
  3720. return TryResolveTypedInst(resolver, inst);
  3721. }
  3722. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  3723. return TryResolveTypedInst(resolver, inst);
  3724. }
  3725. case CARBON_KIND(SemIR::GenericClassType inst): {
  3726. return TryResolveTypedInst(resolver, inst);
  3727. }
  3728. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  3729. return TryResolveTypedInst(resolver, inst);
  3730. }
  3731. case CARBON_KIND(SemIR::GenericNamedConstraintType inst): {
  3732. return TryResolveTypedInst(resolver, inst);
  3733. }
  3734. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  3735. return TryResolveTypedInst(resolver, inst);
  3736. }
  3737. case CARBON_KIND(SemIR::ImplWitness inst): {
  3738. return TryResolveTypedInst(resolver, inst);
  3739. }
  3740. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  3741. return TryResolveTypedInst(resolver, inst);
  3742. }
  3743. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  3744. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3745. }
  3746. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  3747. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3748. }
  3749. case CARBON_KIND(SemIR::InitForm inst): {
  3750. return TryResolveTypedInst(resolver, inst);
  3751. }
  3752. case CARBON_KIND(SemIR::IntValue inst): {
  3753. return TryResolveTypedInst(resolver, inst);
  3754. }
  3755. case CARBON_KIND(SemIR::IntType inst): {
  3756. return TryResolveTypedInst(resolver, inst);
  3757. }
  3758. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  3759. return TryResolveTypedInst(resolver, inst);
  3760. }
  3761. case CARBON_KIND(SemIR::Namespace inst): {
  3762. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3763. }
  3764. case CARBON_KIND(SemIR::OutParamPattern inst): {
  3765. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3766. }
  3767. case CARBON_KIND(SemIR::PartialType inst): {
  3768. return TryResolveTypedInst(resolver, inst);
  3769. }
  3770. case CARBON_KIND(SemIR::PatternType inst): {
  3771. return TryResolveTypedInst(resolver, inst);
  3772. }
  3773. case CARBON_KIND(SemIR::PointerType inst): {
  3774. return TryResolveTypedInst(resolver, inst);
  3775. }
  3776. case CARBON_KIND(SemIR::RefBindingPattern inst): {
  3777. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3778. }
  3779. case CARBON_KIND(SemIR::RefParamPattern inst): {
  3780. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3781. }
  3782. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  3783. return TryResolveTypedInst(resolver, inst);
  3784. }
  3785. case CARBON_KIND(SemIR::RequireSpecificDefinition inst): {
  3786. return TryResolveTypedInst(resolver, inst);
  3787. }
  3788. case CARBON_KIND(SemIR::ReturnSlotPattern inst): {
  3789. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3790. }
  3791. case CARBON_KIND(SemIR::SpecificFunction inst): {
  3792. return TryResolveTypedInst(resolver, inst);
  3793. }
  3794. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  3795. return TryResolveTypedInst(resolver, inst);
  3796. }
  3797. case CARBON_KIND(SemIR::StructAccess inst): {
  3798. return TryResolveTypedInst(resolver, inst);
  3799. }
  3800. case CARBON_KIND(SemIR::StructType inst): {
  3801. return TryResolveTypedInst(resolver, inst);
  3802. }
  3803. case CARBON_KIND(SemIR::StructValue inst): {
  3804. return TryResolveTypedInst(resolver, inst);
  3805. }
  3806. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  3807. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3808. }
  3809. case CARBON_KIND(SemIR::SymbolicBindingType inst): {
  3810. return TryResolveTypedInst(resolver, inst);
  3811. }
  3812. case CARBON_KIND(SemIR::TupleAccess inst): {
  3813. return TryResolveTypedInst(resolver, inst);
  3814. }
  3815. case CARBON_KIND(SemIR::TuplePattern inst): {
  3816. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3817. }
  3818. case CARBON_KIND(SemIR::TupleType inst): {
  3819. return TryResolveTypedInst(resolver, inst);
  3820. }
  3821. case CARBON_KIND(SemIR::TupleValue inst): {
  3822. return TryResolveTypedInst(resolver, inst);
  3823. }
  3824. case CARBON_KIND(SemIR::UnboundElementType inst): {
  3825. return TryResolveTypedInst(resolver, inst);
  3826. }
  3827. case CARBON_KIND(SemIR::ValueBindingPattern inst): {
  3828. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3829. }
  3830. case CARBON_KIND(SemIR::ValueParamPattern inst): {
  3831. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3832. }
  3833. case CARBON_KIND(SemIR::VarParamPattern inst): {
  3834. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3835. }
  3836. case CARBON_KIND(SemIR::VarPattern inst): {
  3837. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3838. }
  3839. case CARBON_KIND(SemIR::VarStorage inst): {
  3840. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3841. }
  3842. case CARBON_KIND(SemIR::VtableDecl inst): {
  3843. return TryResolveTypedInst(resolver, inst);
  3844. }
  3845. case CARBON_KIND(SemIR::VtablePtr inst): {
  3846. return TryResolveTypedInst(resolver, inst);
  3847. }
  3848. default:
  3849. // Found a canonical instruction which needs to be resolved, but which is
  3850. // not yet handled.
  3851. //
  3852. // TODO: Could we turn this into a compile-time error?
  3853. CARBON_FATAL(
  3854. "Missing case in TryResolveInstCanonical for instruction kind {0}",
  3855. untyped_constant_inst.kind());
  3856. }
  3857. }
  3858. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  3859. // more has been added to the stack. A similar API is followed for all
  3860. // following TryResolveTypedInst helper functions.
  3861. //
  3862. // `const_id` is `None` unless we've tried to resolve this instruction
  3863. // before, in which case it's the previous result.
  3864. //
  3865. // TODO: Error is returned when support is missing, but that should go away.
  3866. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  3867. SemIR::ConstantId const_id) -> ResolveResult {
  3868. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  3869. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  3870. return TryResolveInstCanonical(resolver, inst_id, const_id);
  3871. }
  3872. // Try to import the generic. This might add new work.
  3873. const auto& symbolic_const =
  3874. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  3875. auto generic_const_id =
  3876. GetLocalConstantId(resolver, symbolic_const.generic_id);
  3877. auto inner_const_id = SemIR::ConstantId::None;
  3878. if (const_id.has_value()) {
  3879. // For the third phase, extract the constant value that
  3880. // TryResolveInstCanonical produced previously.
  3881. inner_const_id = resolver.local_constant_values().GetAttached(
  3882. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  3883. }
  3884. // Import the constant and rebuild the symbolic constant data.
  3885. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  3886. if (!result.const_id.has_value()) {
  3887. // First phase: TryResolveInstCanoncial needs a retry.
  3888. return result;
  3889. }
  3890. if (!const_id.has_value()) {
  3891. // Second phase: we have created an unattached constant. Create a
  3892. // corresponding attached constant.
  3893. if (symbolic_const.generic_id.has_value()) {
  3894. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  3895. {.inst_id =
  3896. resolver.local_constant_values().GetInstId(result.const_id),
  3897. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  3898. .index = symbolic_const.index,
  3899. .dependence = symbolic_const.dependence});
  3900. if (result.decl_id.has_value()) {
  3901. // Overwrite the unattached symbolic constant given initially to the
  3902. // declaration with its final attached symbolic value.
  3903. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  3904. }
  3905. }
  3906. } else {
  3907. // Third phase: perform a consistency check and produce the constant we
  3908. // created in the second phase.
  3909. CARBON_CHECK(result.const_id == inner_const_id,
  3910. "Constant value changed in third phase.");
  3911. result.const_id = const_id;
  3912. }
  3913. return result;
  3914. }
  3915. auto ImportRefResolver::Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  3916. work_stack_.push_back(InstWork{.inst_id = inst_id});
  3917. while (!work_stack_.empty()) {
  3918. auto work_variant = work_stack_.back();
  3919. CARBON_KIND_SWITCH(work_variant) {
  3920. case CARBON_KIND(InstWork work): {
  3921. CARBON_CHECK(work.inst_id.has_value());
  3922. // Step 1: check for a constant value.
  3923. auto existing = FindResolvedConstId(work.inst_id);
  3924. if (existing.const_id.has_value() && !work.retry_with_constant_value) {
  3925. work_stack_.pop_back();
  3926. continue;
  3927. }
  3928. // Step 2: resolve the instruction.
  3929. initial_work_ = work_stack_.size();
  3930. auto result = TryResolveInst(*this, work.inst_id, existing.const_id);
  3931. CARBON_CHECK(!HasNewWork() || result.retry);
  3932. CARBON_CHECK(!existing.const_id.has_value() ||
  3933. existing.const_id == result.const_id,
  3934. "Constant value changed in third phase.");
  3935. if (!existing.const_id.has_value()) {
  3936. SetResolvedConstId(work.inst_id, existing.indirect_insts,
  3937. result.const_id);
  3938. }
  3939. // Step 3: pop or retry.
  3940. if (result.retry) {
  3941. std::get<InstWork>(work_stack_[initial_work_ - 1])
  3942. .retry_with_constant_value = result.const_id.has_value();
  3943. } else {
  3944. work_stack_.pop_back();
  3945. for (const auto& resolve : result.resolve_generic) {
  3946. if (resolve.import_generic_id.has_value()) {
  3947. work_stack_.push_back(
  3948. GenericWork{.import_id = resolve.import_generic_id,
  3949. .local_id = resolve.local_generic_id});
  3950. }
  3951. }
  3952. }
  3953. break;
  3954. }
  3955. case CARBON_KIND(GenericWork generic_work): {
  3956. // Generics may require 2 steps to finish, similar to step 2 and step 3
  3957. // of instructions.
  3958. initial_work_ = work_stack_.size();
  3959. if (TryFinishGeneric(*this, generic_work.import_id,
  3960. generic_work.local_id)) {
  3961. work_stack_.pop_back();
  3962. }
  3963. break;
  3964. }
  3965. case CARBON_KIND(SpecificWork specific_work): {
  3966. // Specifics may require 2 steps to finish, similar to step 2 and step 3
  3967. // of instructions.
  3968. initial_work_ = work_stack_.size();
  3969. if (TryFinishSpecific(*this, specific_work.import_id,
  3970. specific_work.local_id)) {
  3971. work_stack_.pop_back();
  3972. }
  3973. break;
  3974. }
  3975. }
  3976. }
  3977. auto constant_id =
  3978. local_constant_values_for_import_insts().GetAttached(inst_id);
  3979. CARBON_CHECK(constant_id.has_value());
  3980. return constant_id;
  3981. }
  3982. auto ImportRefResolver::ResolveConstant(SemIR::ConstantId import_const_id)
  3983. -> SemIR::ConstantId {
  3984. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  3985. }
  3986. auto ImportRefResolver::ResolveType(SemIR::TypeId import_type_id)
  3987. -> SemIR::TypeId {
  3988. if (!import_type_id.has_value()) {
  3989. return import_type_id;
  3990. }
  3991. auto import_type_const_id = import_ir().types().GetConstantId(import_type_id);
  3992. CARBON_CHECK(import_type_const_id.has_value());
  3993. if (auto import_type_inst_id = import_ir().types().GetAsTypeInstId(
  3994. import_ir().constant_values().GetInstId(import_type_const_id));
  3995. SemIR::IsSingletonInstId(import_type_inst_id)) {
  3996. // Builtins don't require constant resolution; we can use them directly.
  3997. return GetSingletonType(local_context(), import_type_inst_id);
  3998. } else {
  3999. return local_types().GetTypeIdForTypeConstantId(
  4000. ResolveConstant(import_type_id.AsConstantId()));
  4001. }
  4002. }
  4003. auto ImportRefResolver::HasNewWork() -> bool {
  4004. CARBON_CHECK(initial_work_ <= work_stack_.size(), "Work shouldn't decrease");
  4005. return initial_work_ < work_stack_.size();
  4006. }
  4007. auto ImportRefResolver::PushSpecific(SemIR::SpecificId import_id,
  4008. SemIR::SpecificId local_id) -> void {
  4009. // Insert before the current instruction.
  4010. work_stack_.insert(
  4011. work_stack_.begin() + initial_work_ - 1,
  4012. SpecificWork{.import_id = import_id, .local_id = local_id});
  4013. ++initial_work_;
  4014. }
  4015. auto ImportRefResolver::GetLocalConstantValueOrPush(SemIR::InstId inst_id)
  4016. -> SemIR::ConstantId {
  4017. if (!inst_id.has_value()) {
  4018. return SemIR::ConstantId::None;
  4019. }
  4020. auto const_id = local_constant_values_for_import_insts().GetAttached(inst_id);
  4021. if (!const_id.has_value()) {
  4022. work_stack_.push_back(InstWork{.inst_id = inst_id});
  4023. }
  4024. return const_id;
  4025. }
  4026. auto ImportRefResolver::FindResolvedConstId(SemIR::InstId inst_id)
  4027. -> ResolvedConstId {
  4028. ResolvedConstId result;
  4029. if (auto existing_const_id =
  4030. local_constant_values_for_import_insts().GetAttached(inst_id);
  4031. existing_const_id.has_value()) {
  4032. result.const_id = existing_const_id;
  4033. return result;
  4034. }
  4035. const auto* cursor_ir = &import_ir();
  4036. auto cursor_inst_id = inst_id;
  4037. while (true) {
  4038. auto import_ir_inst_id = cursor_ir->insts().GetImportSource(cursor_inst_id);
  4039. if (!import_ir_inst_id.has_value()) {
  4040. return result;
  4041. }
  4042. auto ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
  4043. if (ir_inst.ir_id() == SemIR::ImportIRId::Cpp) {
  4044. local_context().TODO(SemIR::LocId::None,
  4045. "Unsupported: Importing C++ indirectly");
  4046. SetResolvedConstId(inst_id, result.indirect_insts,
  4047. SemIR::ErrorInst::ConstantId);
  4048. result.const_id = SemIR::ErrorInst::ConstantId;
  4049. result.indirect_insts.clear();
  4050. return result;
  4051. }
  4052. const auto* prev_ir = cursor_ir;
  4053. auto prev_inst_id = cursor_inst_id;
  4054. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id()).sem_ir;
  4055. auto cursor_ir_id =
  4056. AddImportIR(local_context(), {.decl_id = SemIR::InstId::None,
  4057. .is_export = false,
  4058. .sem_ir = cursor_ir});
  4059. cursor_inst_id = ir_inst.inst_id();
  4060. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id, "{0}",
  4061. cursor_ir->insts().Get(cursor_inst_id));
  4062. if (auto const_id =
  4063. local_context()
  4064. .import_ir_constant_values()
  4065. [local_ir().import_irs().GetRawIndex(cursor_ir_id)]
  4066. .GetAttached(cursor_inst_id);
  4067. const_id.has_value()) {
  4068. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  4069. result.const_id = const_id;
  4070. result.indirect_insts.clear();
  4071. return result;
  4072. } else {
  4073. result.indirect_insts.push_back(
  4074. SemIR::ImportIRInst(cursor_ir_id, cursor_inst_id));
  4075. }
  4076. }
  4077. }
  4078. auto ImportRefResolver::SetResolvedConstId(
  4079. SemIR::InstId inst_id, llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  4080. SemIR::ConstantId const_id) -> void {
  4081. local_constant_values_for_import_insts().Set(inst_id, const_id);
  4082. SetIndirectConstantValues(local_context(), indirect_insts, const_id);
  4083. }
  4084. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  4085. // loaded (including the one pointed at directly by the ImportRef), and the
  4086. // final instruction's type ID.
  4087. //
  4088. // This addresses cases where an ImportRefUnloaded may point at another
  4089. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  4090. // constant-evaluated version of the instruction to work with.
  4091. static auto GetInstForLoad(Context& context,
  4092. SemIR::ImportIRInstId import_ir_inst_id)
  4093. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  4094. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  4095. {}, SemIR::TypeId::None};
  4096. auto& [import_ir_insts, type_id] = result;
  4097. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  4098. // The first ImportIRInst is added directly because the IR doesn't need to be
  4099. // localized.
  4100. import_ir_insts.push_back(import_ir_inst);
  4101. const auto* cursor_ir =
  4102. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  4103. while (true) {
  4104. auto cursor_inst =
  4105. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  4106. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  4107. if (!import_ref) {
  4108. type_id = cursor_inst.type_id();
  4109. return result;
  4110. }
  4111. import_ir_inst =
  4112. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  4113. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  4114. import_ir_insts.push_back(SemIR::ImportIRInst(
  4115. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  4116. .is_export = false,
  4117. .sem_ir = cursor_ir}),
  4118. import_ir_inst.inst_id()));
  4119. }
  4120. }
  4121. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  4122. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  4123. if (!inst) {
  4124. return;
  4125. }
  4126. auto [indirect_insts, load_type_id] =
  4127. GetInstForLoad(context, inst->import_ir_inst_id);
  4128. // The last indirect instruction is the one to resolve. Pop it here because
  4129. // Resolve will assign the constant.
  4130. auto load_ir_inst = indirect_insts.pop_back_val();
  4131. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  4132. // Loading an import ref creates local constants from the import ones, but
  4133. // shouldn't be generating novel instructions in the semir as a side effect of
  4134. // that process. Doing so in a generic context would also cause them to end up
  4135. // in the eval block, which would be doubly wrong.
  4136. context.inst_block_stack().Push();
  4137. auto type_id = resolver.ResolveType(load_type_id);
  4138. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  4139. CARBON_CHECK(
  4140. context.inst_block_stack().PeekCurrentBlockContents().empty(),
  4141. "Importing an instruction shouldn't add new instructions to the "
  4142. "local inst block. Found {0} new instructions, first is {1}: {2}.",
  4143. context.inst_block_stack().PeekCurrentBlockContents().size(),
  4144. context.inst_block_stack().PeekCurrentBlockContents().front(),
  4145. context.insts().Get(
  4146. context.inst_block_stack().PeekCurrentBlockContents().front()));
  4147. context.inst_block_stack().PopAndDiscard();
  4148. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  4149. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  4150. // TryEvalInst, which we want to avoid with ImportRefs.
  4151. context.sem_ir().insts().Set(
  4152. inst_id,
  4153. SemIR::ImportRefLoaded{.type_id = type_id,
  4154. .import_ir_inst_id = inst->import_ir_inst_id,
  4155. .entity_name_id = inst->entity_name_id});
  4156. // Store the constant for both the ImportRefLoaded and indirect instructions.
  4157. context.constant_values().Set(inst_id, constant_id);
  4158. SetIndirectConstantValues(context, indirect_insts, constant_id);
  4159. }
  4160. auto ImportImplsFromApiFile(Context& context) -> void {
  4161. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  4162. auto& import_ir = context.import_irs().Get(import_ir_id);
  4163. if (!import_ir.sem_ir) {
  4164. return;
  4165. }
  4166. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  4167. // Resolve the imported impl to a local impl ID.
  4168. ImportImpl(context, import_ir_id, impl_id);
  4169. }
  4170. }
  4171. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  4172. SemIR::ImplId impl_id) -> void {
  4173. ImportRefResolver resolver(&context, import_ir_id);
  4174. resolver.Resolve(resolver.import_impls().Get(impl_id).first_decl_id());
  4175. }
  4176. auto ImportInterface(Context& context, SemIR::ImportIRId import_ir_id,
  4177. SemIR::InterfaceId interface_id) -> SemIR::InterfaceId {
  4178. ImportRefResolver resolver(&context, import_ir_id);
  4179. auto local_id = resolver.Resolve(
  4180. resolver.import_interfaces().Get(interface_id).first_decl_id());
  4181. auto local_inst =
  4182. context.insts().Get(context.constant_values().GetInstId(local_id));
  4183. // A non-generic interface will import as a facet type for that single
  4184. // interface.
  4185. if (auto facet_type = local_inst.TryAs<SemIR::FacetType>()) {
  4186. auto single = context.facet_types()
  4187. .Get(facet_type->facet_type_id)
  4188. .TryAsSingleExtend();
  4189. CARBON_CHECK(single,
  4190. "Importing an interface didn't produce a single interface");
  4191. return std::get<SemIR::SpecificInterface>(*single).interface_id;
  4192. }
  4193. // A generic interface will import as a constant of generic interface type.
  4194. auto generic_interface_type =
  4195. context.types().GetAs<SemIR::GenericInterfaceType>(local_inst.type_id());
  4196. return generic_interface_type.interface_id;
  4197. }
  4198. } // namespace Carbon::Check