import_ref.cpp 195 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707
  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. SemIR::LocIdAndInst::RuntimeVerified(
  89. context.sem_ir(), 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. SemIR::LocIdAndInst::RuntimeVerified(context.local_context().sem_ir(),
  476. import_ir_inst_id, 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. SemIR::LocIdAndInst::RuntimeVerified(context.local_context().sem_ir(),
  517. import_ir_inst_id, 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. local_specific.decl_block_has_error = import_specific.decl_block_has_error;
  975. }
  976. local_specific.definition_block_id = GetLocalCanonicalInstBlockId(
  977. resolver, import_specific.definition_block_id, definition_block);
  978. local_specific.definition_block_has_error =
  979. import_specific.definition_block_has_error;
  980. return true;
  981. }
  982. namespace {
  983. struct SpecificInterfaceData {
  984. SemIR::ConstantId interface_const_id;
  985. SpecificData specific_data;
  986. };
  987. } // namespace
  988. static auto GetLocalSpecificInterfaceData(
  989. ImportRefResolver& resolver, SemIR::SpecificInterface import_interface)
  990. -> SpecificInterfaceData {
  991. SemIR::ConstantId interface_const_id = SemIR::ConstantId::None;
  992. if (import_interface.interface_id.has_value()) {
  993. interface_const_id =
  994. GetLocalConstantId(resolver, resolver.import_interfaces()
  995. .Get(import_interface.interface_id)
  996. .first_owning_decl_id);
  997. }
  998. return {.interface_const_id = interface_const_id,
  999. .specific_data =
  1000. GetLocalSpecificData(resolver, import_interface.specific_id)};
  1001. }
  1002. static auto GetLocalSpecificInterface(
  1003. ImportRefResolver& resolver,
  1004. SemIR::SpecificInterface import_specific_interface,
  1005. SpecificInterfaceData interface_data) -> SemIR::SpecificInterface {
  1006. if (!interface_data.interface_const_id.has_value()) {
  1007. return SemIR::SpecificInterface::None;
  1008. }
  1009. // Find the corresponding interface type. For a non-generic interface,
  1010. // this is the type of the interface declaration. For a generic interface,
  1011. // build a interface type referencing this specialization of the generic
  1012. // interface.
  1013. auto interface_const_inst =
  1014. resolver.local_insts().Get(resolver.local_constant_values().GetInstId(
  1015. interface_data.interface_const_id));
  1016. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  1017. const SemIR::FacetTypeInfo& new_facet_type_info =
  1018. resolver.local_facet_types().Get(facet_type->facet_type_id);
  1019. return std::get<SemIR::SpecificInterface>(
  1020. *new_facet_type_info.TryAsSingleExtend());
  1021. } else {
  1022. auto generic_interface_type =
  1023. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  1024. interface_const_inst.type_id());
  1025. auto specific_id =
  1026. GetOrAddLocalSpecific(resolver, import_specific_interface.specific_id,
  1027. interface_data.specific_data);
  1028. return {generic_interface_type.interface_id, specific_id};
  1029. }
  1030. }
  1031. namespace {
  1032. struct SpecificNamedConstraintData {
  1033. SemIR::ConstantId constraint_const_id;
  1034. SpecificData specific_data;
  1035. };
  1036. } // namespace
  1037. static auto GetLocalSpecificNamedConstraintData(
  1038. ImportRefResolver& resolver,
  1039. SemIR::SpecificNamedConstraint import_constraint)
  1040. -> SpecificNamedConstraintData {
  1041. SemIR::ConstantId constraint_const_id = SemIR::ConstantId::None;
  1042. if (import_constraint.named_constraint_id.has_value()) {
  1043. constraint_const_id = GetLocalConstantId(
  1044. resolver, resolver.import_named_constraints()
  1045. .Get(import_constraint.named_constraint_id)
  1046. .first_owning_decl_id);
  1047. }
  1048. return {.constraint_const_id = constraint_const_id,
  1049. .specific_data =
  1050. GetLocalSpecificData(resolver, import_constraint.specific_id)};
  1051. }
  1052. static auto GetLocalSpecificNamedConstraint(
  1053. ImportRefResolver& resolver,
  1054. SemIR::SpecificNamedConstraint import_specific_constraint,
  1055. SpecificNamedConstraintData constraint_data)
  1056. -> SemIR::SpecificNamedConstraint {
  1057. if (!constraint_data.constraint_const_id.has_value()) {
  1058. return SemIR::SpecificNamedConstraint::None;
  1059. }
  1060. // Find the corresponding named constraint type. For a non-generic constraint,
  1061. // this is the type of the named constraint declaration. For a generic
  1062. // constraint, build a named constraint type referencing this specialization
  1063. // of the generic named constraint.
  1064. auto constraint_const_inst =
  1065. resolver.local_insts().Get(resolver.local_constant_values().GetInstId(
  1066. constraint_data.constraint_const_id));
  1067. if (auto facet_type = constraint_const_inst.TryAs<SemIR::FacetType>()) {
  1068. const SemIR::FacetTypeInfo& new_facet_type_info =
  1069. resolver.local_facet_types().Get(facet_type->facet_type_id);
  1070. return std::get<SemIR::SpecificNamedConstraint>(
  1071. *new_facet_type_info.TryAsSingleExtend());
  1072. } else {
  1073. auto generic_constraint_type =
  1074. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  1075. constraint_const_inst.type_id());
  1076. auto specific_id =
  1077. GetOrAddLocalSpecific(resolver, import_specific_constraint.specific_id,
  1078. constraint_data.specific_data);
  1079. return {generic_constraint_type.named_constraint_id, specific_id};
  1080. }
  1081. }
  1082. static auto GetLocalNameScopeIdImpl(ImportRefResolver& resolver,
  1083. SemIR::ConstantId const_id)
  1084. -> SemIR::NameScopeId {
  1085. if (!const_id.has_value()) {
  1086. return SemIR::NameScopeId::None;
  1087. }
  1088. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  1089. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  1090. CARBON_KIND_SWITCH(name_scope_inst) {
  1091. case CARBON_KIND(SemIR::Namespace inst): {
  1092. return inst.name_scope_id;
  1093. }
  1094. case CARBON_KIND(SemIR::ClassType inst): {
  1095. return resolver.local_classes().Get(inst.class_id).scope_id;
  1096. }
  1097. case CARBON_KIND(SemIR::FacetType inst): {
  1098. const SemIR::FacetTypeInfo& facet_type_info =
  1099. resolver.local_facet_types().Get(inst.facet_type_id);
  1100. if (auto single = facet_type_info.TryAsSingleExtend()) {
  1101. // This is the facet type produced by an interface or named constraint
  1102. // declaration.
  1103. CARBON_KIND_SWITCH(*single) {
  1104. case CARBON_KIND(SemIR::SpecificInterface interface): {
  1105. return resolver.local_interfaces()
  1106. .Get(interface.interface_id)
  1107. .scope_without_self_id;
  1108. }
  1109. case CARBON_KIND(SemIR::SpecificNamedConstraint constraint): {
  1110. return resolver.local_named_constraints()
  1111. .Get(constraint.named_constraint_id)
  1112. .scope_without_self_id;
  1113. }
  1114. }
  1115. }
  1116. break;
  1117. }
  1118. case CARBON_KIND(SemIR::ImplDecl inst): {
  1119. return resolver.local_impls().Get(inst.impl_id).scope_id;
  1120. }
  1121. case CARBON_KIND(SemIR::InterfaceWithSelfDecl interface_with_self): {
  1122. return resolver.local_interfaces()
  1123. .Get(interface_with_self.interface_id)
  1124. .scope_with_self_id;
  1125. }
  1126. case CARBON_KIND(SemIR::NamedConstraintWithSelfDecl constraint_with_self): {
  1127. return resolver.local_named_constraints()
  1128. .Get(constraint_with_self.named_constraint_id)
  1129. .scope_with_self_id;
  1130. }
  1131. case SemIR::StructValue::Kind: {
  1132. auto type_inst =
  1133. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  1134. CARBON_KIND_SWITCH(type_inst) {
  1135. case CARBON_KIND(SemIR::GenericClassType inst): {
  1136. return resolver.local_classes().Get(inst.class_id).scope_id;
  1137. }
  1138. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  1139. return resolver.local_interfaces()
  1140. .Get(inst.interface_id)
  1141. .scope_without_self_id;
  1142. }
  1143. case CARBON_KIND(SemIR::GenericNamedConstraintType inst): {
  1144. return resolver.local_named_constraints()
  1145. .Get(inst.named_constraint_id)
  1146. .scope_without_self_id;
  1147. }
  1148. default: {
  1149. break;
  1150. }
  1151. }
  1152. break;
  1153. }
  1154. default: {
  1155. if (const_inst_id == SemIR::ErrorInst::InstId) {
  1156. return SemIR::NameScopeId::None;
  1157. }
  1158. break;
  1159. }
  1160. }
  1161. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  1162. name_scope_inst);
  1163. }
  1164. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  1165. // unresolved constants to the resolver's work stack.
  1166. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  1167. SemIR::NameScopeId name_scope_id)
  1168. -> SemIR::NameScopeId {
  1169. // Get the instruction that created the scope.
  1170. auto [inst_id, inst] =
  1171. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  1172. if (!inst) {
  1173. // Map scopes that aren't associated with an instruction to `None`. For now,
  1174. // such scopes aren't used, and we don't have a good way to remap them.
  1175. return SemIR::NameScopeId::None;
  1176. }
  1177. // Get the constant value for the scope.
  1178. auto const_id = GetLocalConstantId(resolver, inst_id);
  1179. if (!const_id.has_value()) {
  1180. return SemIR::NameScopeId::None;
  1181. }
  1182. auto result = GetLocalNameScopeIdImpl(resolver, const_id);
  1183. CARBON_CHECK(result.has_value());
  1184. return result;
  1185. }
  1186. // Given an imported entity base, returns an incomplete, local version of it.
  1187. //
  1188. // Most fields are set in the third phase once they're imported. Import enough
  1189. // of the parameter lists that we know whether this interface is a generic
  1190. // interface and can build the right constant value for it.
  1191. //
  1192. // TODO: Support extern.
  1193. static auto GetIncompleteLocalEntityBase(
  1194. ImportContext& context, SemIR::InstId decl_id,
  1195. const SemIR::EntityWithParamsBase& import_base)
  1196. -> SemIR::EntityWithParamsBase {
  1197. // Translate the extern_library_id if present.
  1198. auto extern_library_id = SemIR::LibraryNameId::None;
  1199. if (import_base.extern_library_id.has_value()) {
  1200. if (import_base.extern_library_id.index >= 0) {
  1201. auto val = context.import_string_literal_values().Get(
  1202. import_base.extern_library_id.AsStringLiteralValueId());
  1203. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  1204. context.local_string_literal_values().Add(val));
  1205. } else {
  1206. extern_library_id = import_base.extern_library_id;
  1207. }
  1208. }
  1209. return {
  1210. .name_id = GetLocalNameId(context, import_base.name_id),
  1211. .parent_scope_id = SemIR::NameScopeId::None,
  1212. .generic_id =
  1213. ImportIncompleteGeneric(context, decl_id, import_base.generic_id),
  1214. .first_param_node_id = Parse::NodeId::None,
  1215. .last_param_node_id = Parse::NodeId::None,
  1216. .pattern_block_id = SemIR::InstBlockId::None,
  1217. .implicit_param_patterns_id =
  1218. import_base.implicit_param_patterns_id.has_value()
  1219. ? SemIR::InstBlockId::Empty
  1220. : SemIR::InstBlockId::None,
  1221. .param_patterns_id = import_base.param_patterns_id.has_value()
  1222. ? SemIR::InstBlockId::Empty
  1223. : SemIR::InstBlockId::None,
  1224. .is_extern = import_base.is_extern,
  1225. .extern_library_id = extern_library_id,
  1226. .non_owning_decl_id = import_base.non_owning_decl_id.has_value()
  1227. ? decl_id
  1228. : SemIR::InstId::None,
  1229. .first_owning_decl_id = import_base.first_owning_decl_id.has_value()
  1230. ? decl_id
  1231. : SemIR::InstId::None,
  1232. };
  1233. }
  1234. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1235. // lookup.
  1236. static auto AddNameScopeImportRefs(ImportContext& context,
  1237. const SemIR::NameScope& import_scope,
  1238. SemIR::NameScope& new_scope) -> void {
  1239. for (auto entry : import_scope.entries()) {
  1240. SemIR::ScopeLookupResult result = entry.result;
  1241. if (result.is_poisoned()) {
  1242. continue;
  1243. }
  1244. auto ref_id = AddImportRef(context, result.target_inst_id());
  1245. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1246. .result = SemIR::ScopeLookupResult::MakeFound(
  1247. ref_id, result.access_kind())});
  1248. }
  1249. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1250. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1251. }
  1252. }
  1253. // Given a block ID for a list of associated entities of a witness, returns a
  1254. // version localized to the current IR.
  1255. static auto AddAssociatedEntities(ImportContext& context,
  1256. SemIR::NameScopeId local_name_scope_id,
  1257. SemIR::InstBlockId associated_entities_id)
  1258. -> SemIR::InstBlockId {
  1259. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1260. return SemIR::InstBlockId::Empty;
  1261. }
  1262. auto associated_entities =
  1263. context.import_inst_blocks().Get(associated_entities_id);
  1264. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1265. new_associated_entities.reserve(associated_entities.size());
  1266. for (auto inst_id : associated_entities) {
  1267. // Determine the name of the associated entity, by switching on its kind.
  1268. SemIR::NameId import_name_id = SemIR::NameId::None;
  1269. if (auto assoc_const_decl =
  1270. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1271. inst_id)) {
  1272. const auto& assoc_const = context.import_associated_constants().Get(
  1273. assoc_const_decl->assoc_const_id);
  1274. import_name_id = assoc_const.name_id;
  1275. } else if (auto function_decl =
  1276. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1277. inst_id)) {
  1278. const auto& function =
  1279. context.import_functions().Get(function_decl->function_id);
  1280. import_name_id = function.name_id;
  1281. } else if (auto import_ref =
  1282. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1283. inst_id)) {
  1284. import_name_id =
  1285. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1286. } else {
  1287. // We don't need `GetWithAttachedType` here because we don't access the
  1288. // type.
  1289. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1290. context.import_insts().Get(inst_id).kind());
  1291. }
  1292. auto name_id = GetLocalNameId(context, import_name_id);
  1293. auto entity_name_id = context.local_entity_names().Add(
  1294. {.name_id = name_id, .parent_scope_id = local_name_scope_id});
  1295. new_associated_entities.push_back(
  1296. AddImportRef(context, inst_id, entity_name_id));
  1297. }
  1298. return context.local_inst_blocks().Add(new_associated_entities);
  1299. }
  1300. namespace {
  1301. namespace Internal {
  1302. // Internal concept for instruction kinds that produce unique constants.
  1303. template <typename InstT>
  1304. concept HasUniqueConstantKind =
  1305. InstT::Kind.constant_kind() == SemIR::InstConstantKind::AlwaysUnique ||
  1306. InstT::Kind.constant_kind() == SemIR::InstConstantKind::ConditionalUnique;
  1307. } // namespace Internal
  1308. // The result of attempting to resolve an imported instruction to a constant.
  1309. struct ResolveResult {
  1310. // The new constant value, if known.
  1311. SemIR::ConstantId const_id;
  1312. // Newly created declaration whose value is being resolved, if any.
  1313. SemIR::InstId decl_id = SemIR::InstId::None;
  1314. // Whether resolution has been attempted once and needs to be retried.
  1315. bool retry = false;
  1316. // If a generic needs to be resolved, the generic information.
  1317. struct ResolveGeneric {
  1318. SemIR::GenericId import_generic_id = SemIR::GenericId::None;
  1319. SemIR::GenericId local_generic_id = SemIR::GenericId::None;
  1320. };
  1321. std::array<ResolveGeneric, 2> resolve_generic;
  1322. // Produces a resolve result that tries resolving this instruction again. If
  1323. // `const_id` is specified, then this is the end of the second phase, and the
  1324. // constant value will be passed to the next resolution attempt. Otherwise,
  1325. // this is the end of the first phase.
  1326. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::None,
  1327. SemIR::InstId decl_id = SemIR::InstId::None)
  1328. -> ResolveResult {
  1329. return {.const_id = const_id, .decl_id = decl_id, .retry = true};
  1330. }
  1331. // Produces a resolve result that provides the given constant value. Requires
  1332. // that there is no new work.
  1333. static auto Done(SemIR::ConstantId const_id,
  1334. SemIR::InstId decl_id = SemIR::InstId::None)
  1335. -> ResolveResult {
  1336. return {.const_id = const_id, .decl_id = decl_id};
  1337. }
  1338. // Produces a resolve result that provides the given constant value. Retries
  1339. // instead if work has been added.
  1340. static auto RetryOrDone(ImportRefResolver& resolver,
  1341. SemIR::ConstantId const_id) -> ResolveResult {
  1342. if (resolver.HasNewWork()) {
  1343. return Retry();
  1344. }
  1345. return Done(const_id);
  1346. }
  1347. // If there's no generic, this is equivalent to `Done`. If there is a generic,
  1348. // it's still done, but the fetched generic data is processed and the generic
  1349. // is enqueued for further work.
  1350. //
  1351. // It's not valid to have a generic-with-self but no base generic.
  1352. static auto FinishGenericOrDone(ImportRefResolver& resolver,
  1353. SemIR::ConstantId const_id,
  1354. SemIR::InstId decl_id,
  1355. SemIR::GenericId import_generic_id,
  1356. SemIR::GenericId local_generic_id,
  1357. GenericData generic_data) -> ResolveResult {
  1358. auto result = Done(const_id, decl_id);
  1359. if (import_generic_id.has_value()) {
  1360. SetGenericDataForResolveResult(resolver, import_generic_id,
  1361. local_generic_id, generic_data);
  1362. result.resolve_generic[0].import_generic_id = import_generic_id;
  1363. result.resolve_generic[0].local_generic_id = local_generic_id;
  1364. }
  1365. return result;
  1366. }
  1367. // Adds `inst` to the local context as a deduplicated constant and returns a
  1368. // successful `ResolveResult`. Requires that there is no new work.
  1369. //
  1370. // This implements phases 2 and 3 of resolving the inst (as described on
  1371. // `ImportRefResolver`) for the common case where those phases are combined.
  1372. // Cases where that isn't applicable should instead use
  1373. // `AddPlaceholderImportedInst` and `ReplacePlaceholderImportedInst`.
  1374. //
  1375. // This should not be used for instructions that represent declarations, or
  1376. // other instructions with `constant_kind == InstConstantKind::Unique`,
  1377. // because they should not be deduplicated.
  1378. template <typename InstT>
  1379. requires(!Internal::HasUniqueConstantKind<InstT>)
  1380. static auto Deduplicated(ImportRefResolver& resolver, InstT inst)
  1381. -> ResolveResult {
  1382. CARBON_CHECK(!resolver.HasNewWork());
  1383. // AddImportedConstant produces an unattached constant, so its type must
  1384. // be unattached as well.
  1385. inst.type_id = resolver.local_types().GetUnattachedType(inst.type_id);
  1386. auto const_id = AddImportedConstant(resolver.local_context(), inst);
  1387. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1388. return Done(const_id);
  1389. }
  1390. // Adds `inst` to the local context as a unique constant and returns a
  1391. // successful `ResolveResult`. `import_inst_id` is the corresponding inst ID
  1392. // in the local context. Requires that there is no new work.
  1393. //
  1394. // This implements phases 2 and 3 of resolving the inst (as described on
  1395. // `ImportRefResolver`) for the common case where those phases are combined.
  1396. // Cases where that isn't applicable should instead use
  1397. // `AddPlaceholderImportedInst` and `ReplacePlaceholderImportedInst`.
  1398. //
  1399. // This should only be used for instructions that represent declarations, or
  1400. // other instructions with `constant_kind == InstConstantKind::Unique`,
  1401. // because it does not perform deduplication.
  1402. template <typename InstT>
  1403. requires Internal::HasUniqueConstantKind<InstT>
  1404. static auto Unique(ImportRefResolver& resolver, SemIR::InstId import_inst_id,
  1405. InstT inst) -> ResolveResult {
  1406. CARBON_CHECK(!resolver.HasNewWork());
  1407. auto inst_id = AddPlaceholderImportedInst(resolver, import_inst_id, inst);
  1408. auto const_id = SetConstantValue(resolver.local_context(), inst_id, inst);
  1409. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1410. return Done(const_id, inst_id);
  1411. }
  1412. };
  1413. } // namespace
  1414. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1415. SemIR::AdaptDecl inst,
  1416. SemIR::InstId import_inst_id) -> ResolveResult {
  1417. auto adapted_type_const_id =
  1418. GetLocalConstantId(resolver, inst.adapted_type_inst_id);
  1419. if (resolver.HasNewWork()) {
  1420. return ResolveResult::Retry();
  1421. }
  1422. auto adapted_type_inst_id = AddLoadedImportRefForType(
  1423. resolver, inst.adapted_type_inst_id, adapted_type_const_id);
  1424. // Create a corresponding instruction to represent the declaration.
  1425. return ResolveResult::Unique<SemIR::AdaptDecl>(
  1426. resolver, import_inst_id, {.adapted_type_inst_id = adapted_type_inst_id});
  1427. }
  1428. template <typename ParamPatternT>
  1429. requires SemIR::Internal::HasInstCategory<SemIR::AnyLeafParamPattern,
  1430. ParamPatternT> &&
  1431. (!std::same_as<ParamPatternT, SemIR::FormParamPattern>)
  1432. static auto TryResolveTypedInst(ImportRefResolver& resolver, ParamPatternT inst,
  1433. SemIR::InstId import_inst_id) -> ResolveResult {
  1434. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1435. auto name_id = GetLocalNameId(resolver, inst.pretty_name_id);
  1436. if (resolver.HasNewWork()) {
  1437. return ResolveResult::Retry();
  1438. }
  1439. return ResolveResult::Unique<ParamPatternT>(
  1440. resolver, import_inst_id,
  1441. {.type_id =
  1442. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1443. .pretty_name_id = name_id});
  1444. }
  1445. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1446. SemIR::ArrayType inst) -> ResolveResult {
  1447. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1448. auto element_type_inst_id =
  1449. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  1450. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1451. if (resolver.HasNewWork()) {
  1452. return ResolveResult::Retry();
  1453. }
  1454. return ResolveResult::Deduplicated<SemIR::ArrayType>(
  1455. resolver, {.type_id = SemIR::TypeType::TypeId,
  1456. .bound_id = bound_id,
  1457. .element_type_inst_id = element_type_inst_id});
  1458. }
  1459. static auto ImportAssociatedConstant(
  1460. ImportContext& context, const SemIR::AssociatedConstant& import_assoc_const,
  1461. SemIR::TypeId type_id)
  1462. -> std::pair<SemIR::AssociatedConstantId, SemIR::ConstantId> {
  1463. SemIR::AssociatedConstantDecl assoc_const_decl = {
  1464. .type_id = type_id,
  1465. .assoc_const_id = SemIR::AssociatedConstantId::None,
  1466. .decl_block_id = SemIR::InstBlockId::Empty};
  1467. auto assoc_const_decl_id = AddPlaceholderImportedInst(
  1468. context, import_assoc_const.decl_id, assoc_const_decl);
  1469. assoc_const_decl.assoc_const_id = context.local_associated_constants().Add({
  1470. .name_id = GetLocalNameId(context, import_assoc_const.name_id),
  1471. .parent_scope_id = SemIR::NameScopeId::None,
  1472. .decl_id = assoc_const_decl_id,
  1473. .default_value_id =
  1474. import_assoc_const.default_value_id.has_value()
  1475. ? AddImportRef(context, import_assoc_const.default_value_id)
  1476. : SemIR::InstId::None,
  1477. });
  1478. // Write the associated constant ID into the AssociatedConstantDecl.
  1479. auto const_id = ReplacePlaceholderImportedInst(context, assoc_const_decl_id,
  1480. assoc_const_decl);
  1481. return {assoc_const_decl.assoc_const_id, const_id};
  1482. }
  1483. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1484. SemIR::AssociatedConstantDecl inst,
  1485. SemIR::ConstantId const_id) -> ResolveResult {
  1486. const auto& import_assoc_const =
  1487. resolver.import_associated_constants().Get(inst.assoc_const_id);
  1488. SemIR::AssociatedConstantId assoc_const_id =
  1489. SemIR::AssociatedConstantId::None;
  1490. if (!const_id.has_value()) {
  1491. // In the first phase, import the type of the associated constant.
  1492. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1493. if (resolver.HasNewWork()) {
  1494. return ResolveResult::Retry();
  1495. }
  1496. // In the second phase, create the associated constant and its declaration.
  1497. auto type_id =
  1498. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id);
  1499. std::tie(assoc_const_id, const_id) =
  1500. ImportAssociatedConstant(resolver, import_assoc_const, type_id);
  1501. } else {
  1502. // In the third phase, compute the associated constant ID from the constant
  1503. // value of the declaration.
  1504. assoc_const_id = resolver.local_constant_values()
  1505. .GetInstAs<SemIR::AssociatedConstantDecl>(const_id)
  1506. .assoc_const_id;
  1507. }
  1508. // Load the values to populate the entity with.
  1509. auto parent_scope_id =
  1510. GetLocalNameScopeId(resolver, import_assoc_const.parent_scope_id);
  1511. auto& new_assoc_const =
  1512. resolver.local_associated_constants().Get(assoc_const_id);
  1513. if (resolver.HasNewWork()) {
  1514. return ResolveResult::Retry(const_id, new_assoc_const.decl_id);
  1515. }
  1516. // Populate the entity.
  1517. new_assoc_const.parent_scope_id = parent_scope_id;
  1518. return ResolveResult::Done(const_id, new_assoc_const.decl_id);
  1519. }
  1520. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1521. SemIR::AssociatedEntity inst) -> ResolveResult {
  1522. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1523. if (resolver.HasNewWork()) {
  1524. return ResolveResult::Retry();
  1525. }
  1526. // Add a lazy reference to the target declaration.
  1527. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1528. return ResolveResult::Deduplicated<SemIR::AssociatedEntity>(
  1529. resolver, {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(
  1530. type_const_id),
  1531. .index = inst.index,
  1532. .decl_id = decl_id});
  1533. }
  1534. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1535. SemIR::AssociatedEntityType inst)
  1536. -> ResolveResult {
  1537. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1538. auto data =
  1539. GetLocalSpecificInterfaceData(resolver, inst.GetSpecificInterface());
  1540. if (resolver.HasNewWork()) {
  1541. return ResolveResult::Retry();
  1542. }
  1543. auto specific_interface =
  1544. GetLocalSpecificInterface(resolver, inst.GetSpecificInterface(), data);
  1545. return ResolveResult::Deduplicated<SemIR::AssociatedEntityType>(
  1546. resolver,
  1547. {.type_id = SemIR::TypeType::TypeId,
  1548. .interface_id = specific_interface.interface_id,
  1549. .interface_without_self_specific_id = specific_interface.specific_id});
  1550. }
  1551. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1552. SemIR::BaseDecl inst,
  1553. SemIR::InstId import_inst_id) -> ResolveResult {
  1554. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1555. auto base_type_const_id =
  1556. GetLocalConstantId(resolver, inst.base_type_inst_id);
  1557. if (resolver.HasNewWork()) {
  1558. return ResolveResult::Retry();
  1559. }
  1560. auto base_type_inst_id = AddLoadedImportRefForType(
  1561. resolver, inst.base_type_inst_id, base_type_const_id);
  1562. // Create a corresponding instruction to represent the declaration.
  1563. return ResolveResult::Unique<SemIR::BaseDecl>(
  1564. resolver, import_inst_id,
  1565. {.type_id =
  1566. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1567. .base_type_inst_id = base_type_inst_id,
  1568. .index = inst.index});
  1569. }
  1570. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1571. SemIR::AliasBinding inst) -> ResolveResult {
  1572. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1573. return ResolveResult::RetryOrDone(resolver, value_id);
  1574. }
  1575. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1576. SemIR::SymbolicBinding inst) -> ResolveResult {
  1577. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1578. if (resolver.HasNewWork()) {
  1579. return ResolveResult::Retry();
  1580. }
  1581. auto entity_name_id =
  1582. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  1583. return ResolveResult::Deduplicated<SemIR::SymbolicBinding>(
  1584. resolver,
  1585. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  1586. .entity_name_id = entity_name_id,
  1587. .value_id = SemIR::InstId::None});
  1588. }
  1589. template <typename BindingPatternT>
  1590. requires SemIR::Internal::HasInstCategory<SemIR::AnyBindingPattern,
  1591. BindingPatternT>
  1592. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1593. BindingPatternT inst,
  1594. SemIR::InstId import_inst_id) -> ResolveResult {
  1595. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1596. const auto& import_entity_name =
  1597. resolver.import_entity_names().Get(inst.entity_name_id);
  1598. auto parent_scope_id =
  1599. GetLocalNameScopeId(resolver, import_entity_name.parent_scope_id);
  1600. auto subpattern_id = SemIR::InstId::None;
  1601. if constexpr (std::is_same_v<BindingPatternT, SemIR::WrapperBindingPattern>) {
  1602. subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  1603. }
  1604. if (resolver.HasNewWork()) {
  1605. return ResolveResult::Retry();
  1606. }
  1607. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1608. auto entity_name_id = resolver.local_entity_names().Add(
  1609. {.name_id = name_id,
  1610. .parent_scope_id = parent_scope_id,
  1611. .bind_index_value = import_entity_name.bind_index().index,
  1612. .is_template = import_entity_name.is_template});
  1613. // We use AnyBindingPattern here so that we can initialize it uniformly,
  1614. // regardless of whether BindingPatternT has a subpattern_id field.
  1615. SemIR::AnyBindingPattern result = {
  1616. .kind = BindingPatternT::Kind,
  1617. .type_id =
  1618. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1619. .entity_name_id = entity_name_id,
  1620. .subpattern_id = subpattern_id};
  1621. return ResolveResult::Unique<BindingPatternT>(
  1622. resolver, import_inst_id, SemIR::Inst(result).As<BindingPatternT>());
  1623. }
  1624. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1625. SemIR::BoolLiteral inst) -> ResolveResult {
  1626. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1627. SemIR::BoolType::TypeInstId);
  1628. CARBON_CHECK(!resolver.HasNewWork());
  1629. return ResolveResult::Deduplicated<SemIR::BoolLiteral>(
  1630. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1631. SemIR::BoolType::TypeInstId),
  1632. .value = inst.value});
  1633. }
  1634. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1635. SemIR::BoundMethod inst) -> ResolveResult {
  1636. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1637. SemIR::BoundMethodType::TypeInstId);
  1638. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1639. auto function_decl_id =
  1640. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1641. if (resolver.HasNewWork()) {
  1642. return ResolveResult::Retry();
  1643. }
  1644. return ResolveResult::Deduplicated<SemIR::BoundMethod>(
  1645. resolver,
  1646. {.type_id = GetSingletonType(resolver.local_context(),
  1647. SemIR::BoundMethodType::TypeInstId),
  1648. .object_id = object_id,
  1649. .function_decl_id = function_decl_id});
  1650. }
  1651. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1652. -> ResolveResult {
  1653. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1654. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1655. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1656. if (resolver.HasNewWork()) {
  1657. return ResolveResult::Retry();
  1658. }
  1659. return ResolveResult::Deduplicated<SemIR::Call>(
  1660. resolver,
  1661. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  1662. .callee_id = callee_id,
  1663. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1664. }
  1665. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1666. SemIR::CharLiteralValue inst) -> ResolveResult {
  1667. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1668. SemIR::CharLiteralType::TypeInstId);
  1669. CARBON_CHECK(!resolver.HasNewWork());
  1670. return ResolveResult::Deduplicated<SemIR::CharLiteralValue>(
  1671. resolver,
  1672. {.type_id = GetSingletonType(resolver.local_context(),
  1673. SemIR::CharLiteralType::TypeInstId),
  1674. .value = inst.value});
  1675. }
  1676. static auto AddPlaceholderNameScope(ImportContext& context)
  1677. -> SemIR::NameScopeId {
  1678. return context.local_name_scopes().Add(
  1679. SemIR::InstId::None, SemIR::NameId::None, SemIR::NameScopeId::None);
  1680. }
  1681. // Makes an incomplete class. This is necessary even with classes with a
  1682. // complete declaration, because things such as `Self` may refer back to the
  1683. // type.
  1684. static auto ImportIncompleteClass(ImportContext& context,
  1685. const SemIR::Class& import_class,
  1686. SemIR::SpecificId enclosing_specific_id)
  1687. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1688. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::TypeId,
  1689. .class_id = SemIR::ClassId::None,
  1690. .decl_block_id = SemIR::InstBlockId::Empty};
  1691. auto class_decl_id = AddPlaceholderImportedInst(
  1692. context, import_class.latest_decl_id(), class_decl);
  1693. // Regardless of whether ClassDecl is a complete type, we first need an
  1694. // incomplete type so that any references have something to point at.
  1695. class_decl.class_id = context.local_classes().Add(
  1696. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1697. {.self_type_id = SemIR::TypeId::None,
  1698. .inheritance_kind = import_class.inheritance_kind,
  1699. .is_dynamic = import_class.is_dynamic,
  1700. .scope_id = import_class.is_complete()
  1701. ? AddPlaceholderNameScope(context)
  1702. : SemIR::NameScopeId::None}});
  1703. if (import_class.has_parameters()) {
  1704. class_decl.type_id = GetGenericClassType(
  1705. context.local_context(), class_decl.class_id, enclosing_specific_id);
  1706. }
  1707. // Write the class ID into the ClassDecl.
  1708. auto self_const_id =
  1709. ReplacePlaceholderImportedInst(context, class_decl_id, class_decl);
  1710. return {class_decl.class_id, self_const_id};
  1711. }
  1712. static auto InitializeNameScopeAndImportRefs(
  1713. ImportContext& context, const SemIR::NameScope& import_scope,
  1714. SemIR::NameScope& new_scope, SemIR::InstId decl_id, SemIR::NameId name_id,
  1715. SemIR::NameScopeId parent_scope_id) {
  1716. new_scope.Set(decl_id, name_id, parent_scope_id);
  1717. AddNameScopeImportRefs(context, import_scope, new_scope);
  1718. }
  1719. // Fills out the class definition for an incomplete class.
  1720. static auto ImportClassDefinition(ImportContext& context,
  1721. const SemIR::Class& import_class,
  1722. SemIR::Class& new_class,
  1723. SemIR::InstId complete_type_witness_id,
  1724. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1725. SemIR::InstId vtable_decl_id) -> void {
  1726. new_class.definition_id = new_class.first_owning_decl_id;
  1727. new_class.complete_type_witness_id = complete_type_witness_id;
  1728. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1729. const auto& import_scope =
  1730. context.import_name_scopes().Get(import_class.scope_id);
  1731. // Push a block so that we can add scoped instructions to it.
  1732. context.local_context().inst_block_stack().Push();
  1733. InitializeNameScopeAndImportRefs(
  1734. context, import_scope, new_scope, new_class.first_owning_decl_id,
  1735. SemIR::NameId::None, new_class.parent_scope_id);
  1736. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1737. if (import_class.base_id.has_value()) {
  1738. new_class.base_id = base_id;
  1739. }
  1740. if (import_class.adapt_id.has_value()) {
  1741. new_class.adapt_id = adapt_id;
  1742. }
  1743. if (import_class.vtable_decl_id.has_value()) {
  1744. new_class.vtable_decl_id = vtable_decl_id;
  1745. }
  1746. }
  1747. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1748. SemIR::ClassDecl inst,
  1749. SemIR::ConstantId class_const_id)
  1750. -> ResolveResult {
  1751. // TODO: The handling of interfaces repeats a lot with the handling of
  1752. // classes, and will likely also be repeated for named constraints and
  1753. // choice types. Factor out some of this functionality.
  1754. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1755. SemIR::ClassId class_id = SemIR::ClassId::None;
  1756. if (!class_const_id.has_value()) {
  1757. auto import_specific_id = SemIR::SpecificId::None;
  1758. if (auto import_generic_class_type =
  1759. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1760. inst.type_id)) {
  1761. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1762. }
  1763. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1764. if (resolver.HasNewWork()) {
  1765. // This is the end of the first phase. Don't make a new class yet if
  1766. // we already have new work.
  1767. return ResolveResult::Retry();
  1768. }
  1769. // On the second phase, create a forward declaration of the class for any
  1770. // recursive references.
  1771. auto enclosing_specific_id =
  1772. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1773. std::tie(class_id, class_const_id) =
  1774. ImportIncompleteClass(resolver, import_class, enclosing_specific_id);
  1775. } else {
  1776. // On the third phase, compute the class ID from the constant
  1777. // value of the declaration.
  1778. auto class_const_inst = resolver.local_insts().Get(
  1779. resolver.local_constant_values().GetInstId(class_const_id));
  1780. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1781. class_id = class_type->class_id;
  1782. } else {
  1783. auto generic_class_type =
  1784. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1785. class_const_inst.type_id());
  1786. class_id = generic_class_type.class_id;
  1787. }
  1788. }
  1789. // Load constants for the definition.
  1790. auto parent_scope_id =
  1791. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1792. auto implicit_param_patterns = GetLocalInstBlockContents(
  1793. resolver, import_class.implicit_param_patterns_id);
  1794. auto param_patterns =
  1795. GetLocalInstBlockContents(resolver, import_class.param_patterns_id);
  1796. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1797. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1798. auto complete_type_witness_const_id =
  1799. import_class.complete_type_witness_id.has_value()
  1800. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1801. : SemIR::ConstantId::None;
  1802. auto base_id = import_class.base_id.has_value()
  1803. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1804. : SemIR::InstId::None;
  1805. auto adapt_id = import_class.adapt_id.has_value()
  1806. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1807. : SemIR::InstId::None;
  1808. auto vtable_decl_id =
  1809. import_class.vtable_decl_id.has_value()
  1810. ? AddImportRef(resolver, import_class.vtable_decl_id)
  1811. : SemIR::InstId::None;
  1812. auto& new_class = resolver.local_classes().Get(class_id);
  1813. if (resolver.HasNewWork()) {
  1814. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1815. }
  1816. new_class.parent_scope_id = parent_scope_id;
  1817. new_class.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1818. resolver, import_class.implicit_param_patterns_id,
  1819. implicit_param_patterns);
  1820. new_class.param_patterns_id = GetLocalCanonicalInstBlockId(
  1821. resolver, import_class.param_patterns_id, param_patterns);
  1822. new_class.self_type_id =
  1823. resolver.local_types().GetTypeIdForTypeConstantId(self_const_id);
  1824. if (import_class.is_complete()) {
  1825. auto complete_type_witness_id = AddLoadedImportRef(
  1826. resolver,
  1827. GetSingletonType(resolver.local_context(),
  1828. SemIR::WitnessType::TypeInstId),
  1829. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1830. ImportClassDefinition(resolver, import_class, new_class,
  1831. complete_type_witness_id, base_id, adapt_id,
  1832. vtable_decl_id);
  1833. }
  1834. return ResolveResult::FinishGenericOrDone(
  1835. resolver, class_const_id, new_class.first_decl_id(),
  1836. import_class.generic_id, new_class.generic_id, generic_data);
  1837. }
  1838. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1839. SemIR::ClassType inst) -> ResolveResult {
  1840. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1841. auto class_const_id = GetLocalConstantId(
  1842. resolver,
  1843. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1844. if (class_const_id == SemIR::ErrorInst::ConstantId) {
  1845. // TODO: It should be possible to remove this once C++ imports work.
  1846. return ResolveResult::Done(class_const_id);
  1847. }
  1848. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1849. if (resolver.HasNewWork()) {
  1850. return ResolveResult::Retry();
  1851. }
  1852. // Find the corresponding class type. For a non-generic class, this is the
  1853. // type of the class declaration. For a generic class, build a class type
  1854. // referencing this specialization of the generic class.
  1855. auto class_const_inst = resolver.local_insts().Get(
  1856. resolver.local_constant_values().GetInstId(class_const_id));
  1857. if (class_const_inst.Is<SemIR::ClassType>()) {
  1858. return ResolveResult::Done(class_const_id);
  1859. } else {
  1860. auto generic_class_type =
  1861. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1862. class_const_inst.type_id());
  1863. auto specific_id =
  1864. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1865. return ResolveResult::Deduplicated<SemIR::ClassType>(
  1866. resolver, {.type_id = SemIR::TypeType::TypeId,
  1867. .class_id = generic_class_type.class_id,
  1868. .specific_id = specific_id});
  1869. }
  1870. }
  1871. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1872. SemIR::CompleteTypeWitness inst)
  1873. -> ResolveResult {
  1874. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1875. SemIR::WitnessType::TypeInstId);
  1876. auto object_repr_type_inst_id =
  1877. GetLocalTypeInstId(resolver, inst.object_repr_type_inst_id);
  1878. if (resolver.HasNewWork()) {
  1879. return ResolveResult::Retry();
  1880. }
  1881. return ResolveResult::Deduplicated<SemIR::CompleteTypeWitness>(
  1882. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1883. SemIR::WitnessType::TypeInstId),
  1884. .object_repr_type_inst_id = object_repr_type_inst_id});
  1885. }
  1886. template <typename InstT>
  1887. requires SemIR::Internal::HasInstCategory<SemIR::AnyQualifiedType, InstT>
  1888. static auto TryResolveTypedInst(ImportRefResolver& resolver, InstT inst)
  1889. -> ResolveResult {
  1890. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1891. auto inner_id = GetLocalTypeInstId(resolver, inst.inner_id);
  1892. if (resolver.HasNewWork()) {
  1893. return ResolveResult::Retry();
  1894. }
  1895. return ResolveResult::Deduplicated<InstT>(
  1896. resolver, {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_id});
  1897. }
  1898. static auto HandleUnsupportedCppOverloadSet(ImportRefResolver& resolver,
  1899. SemIR::CppOverloadSetId id) {
  1900. // Supporting C++ overload resolution of imported functions is a large task,
  1901. // which might require serializing and deserializing AST for using decl ids,
  1902. // using modules and/or linking ASTs.
  1903. resolver.local_context().TODO(
  1904. SemIR::LocId::None,
  1905. llvm::formatv(
  1906. "Unsupported: Importing C++ function `{0}` indirectly",
  1907. resolver.import_ir().names().GetAsStringIfIdentifier(
  1908. resolver.import_ir().cpp_overload_sets().Get(id).name_id)));
  1909. return ResolveResult::Done(SemIR::ErrorInst::ConstantId,
  1910. SemIR::ErrorInst::InstId);
  1911. }
  1912. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1913. SemIR::CppOverloadSetType inst)
  1914. -> ResolveResult {
  1915. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1916. }
  1917. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1918. SemIR::CppOverloadSetValue inst)
  1919. -> ResolveResult {
  1920. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1921. }
  1922. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1923. SemIR::CustomWitness inst) -> ResolveResult {
  1924. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1925. SemIR::WitnessType::TypeInstId);
  1926. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  1927. const auto& import_specific_interface =
  1928. resolver.import_specific_interfaces().Get(
  1929. inst.query_specific_interface_id);
  1930. auto data =
  1931. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  1932. if (resolver.HasNewWork()) {
  1933. return ResolveResult::Retry();
  1934. }
  1935. auto elements_id =
  1936. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements);
  1937. auto specific_interface =
  1938. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  1939. auto query_specific_interface_id =
  1940. resolver.local_specific_interfaces().Add(specific_interface);
  1941. return ResolveResult::Deduplicated<SemIR::CustomWitness>(
  1942. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1943. SemIR::WitnessType::TypeInstId),
  1944. .elements_id = elements_id,
  1945. .query_specific_interface_id = query_specific_interface_id});
  1946. }
  1947. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1948. SemIR::ExportDecl inst) -> ResolveResult {
  1949. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1950. return ResolveResult::RetryOrDone(resolver, value_id);
  1951. }
  1952. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1953. SemIR::FieldDecl inst,
  1954. SemIR::InstId import_inst_id) -> ResolveResult {
  1955. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1956. if (resolver.HasNewWork()) {
  1957. return ResolveResult::Retry();
  1958. }
  1959. return ResolveResult::Unique<SemIR::FieldDecl>(
  1960. resolver, import_inst_id,
  1961. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(const_id),
  1962. .name_id = GetLocalNameId(resolver, inst.name_id),
  1963. .index = inst.index});
  1964. }
  1965. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1966. SemIR::FloatLiteralValue inst)
  1967. -> ResolveResult {
  1968. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1969. SemIR::FloatLiteralType::TypeInstId);
  1970. CARBON_CHECK(!resolver.HasNewWork());
  1971. auto real_id = resolver.local_ir().reals().Add(
  1972. resolver.import_ir().reals().Get(inst.real_id));
  1973. return ResolveResult::Deduplicated<SemIR::FloatLiteralValue>(
  1974. resolver,
  1975. {.type_id = GetSingletonType(resolver.local_context(),
  1976. SemIR::FloatLiteralType::TypeInstId),
  1977. .real_id = real_id});
  1978. }
  1979. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1980. SemIR::FloatType inst) -> ResolveResult {
  1981. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1982. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  1983. if (resolver.HasNewWork()) {
  1984. return ResolveResult::Retry();
  1985. }
  1986. return ResolveResult::Deduplicated<SemIR::FloatType>(
  1987. resolver, {.type_id = SemIR::TypeType::TypeId,
  1988. .bit_width_id = bit_width_id,
  1989. .float_kind = inst.float_kind});
  1990. }
  1991. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1992. SemIR::FloatValue inst) -> ResolveResult {
  1993. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1994. if (resolver.HasNewWork()) {
  1995. return ResolveResult::Retry();
  1996. }
  1997. auto float_id = resolver.local_ir().floats().Add(
  1998. resolver.import_ir().floats().Get(inst.float_id));
  1999. return ResolveResult::Deduplicated<SemIR::FloatValue>(
  2000. resolver,
  2001. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  2002. .float_id = float_id});
  2003. }
  2004. // Make a declaration of a function. This is done as a separate step from
  2005. // importing the function declaration in order to resolve cycles.
  2006. static auto ImportFunctionDecl(ImportContext& context,
  2007. const SemIR::Function& import_function,
  2008. SemIR::SpecificId specific_id)
  2009. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  2010. SemIR::FunctionDecl function_decl = {
  2011. .type_id = SemIR::TypeId::None,
  2012. .function_id = SemIR::FunctionId::None,
  2013. .decl_block_id = SemIR::InstBlockId::Empty};
  2014. auto function_decl_id = AddPlaceholderImportedInst(
  2015. context, import_function.first_decl_id(), function_decl);
  2016. // Start with an incomplete function.
  2017. function_decl.function_id = context.local_functions().Add(
  2018. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  2019. {.call_param_patterns_id = SemIR::InstBlockId::None,
  2020. .call_params_id = SemIR::InstBlockId::None,
  2021. .call_param_ranges = import_function.call_param_ranges,
  2022. .return_type_inst_id = SemIR::TypeInstId::None,
  2023. .return_form_inst_id = SemIR::InstId::None,
  2024. .return_patterns_id = SemIR::InstBlockId::None,
  2025. .virtual_modifier = import_function.virtual_modifier,
  2026. .virtual_index = import_function.virtual_index,
  2027. .evaluation_mode = import_function.evaluation_mode}});
  2028. // Directly add the function type constant. Don't use `GetFunctionType`
  2029. // because that will evaluate the function type, which we can't do if the
  2030. // specific's value block is still pending.
  2031. auto type_const_id = AddImportedConstant(
  2032. context.local_context(),
  2033. SemIR::FunctionType{.type_id = SemIR::TypeType::TypeId,
  2034. .function_id = function_decl.function_id,
  2035. .specific_id = specific_id});
  2036. function_decl.type_id =
  2037. context.local_types().GetTypeIdForTypeConstantId(type_const_id);
  2038. // Write the function ID and type into the FunctionDecl.
  2039. auto function_const_id =
  2040. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  2041. return {function_decl.function_id, function_const_id};
  2042. }
  2043. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2044. SemIR::FunctionDecl inst,
  2045. SemIR::ConstantId function_const_id)
  2046. -> ResolveResult {
  2047. const auto& import_function =
  2048. resolver.import_functions().Get(inst.function_id);
  2049. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  2050. if (!function_const_id.has_value()) {
  2051. auto import_specific_id = resolver.import_types()
  2052. .GetAs<SemIR::FunctionType>(inst.type_id)
  2053. .specific_id;
  2054. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2055. if (resolver.HasNewWork()) {
  2056. // This is the end of the first phase. Don't make a new function yet if
  2057. // we already have new work.
  2058. return ResolveResult::Retry();
  2059. }
  2060. // On the second phase, create a forward declaration of the function.
  2061. auto specific_id =
  2062. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2063. std::tie(function_id, function_const_id) =
  2064. ImportFunctionDecl(resolver, import_function, specific_id);
  2065. } else {
  2066. // On the third phase, compute the function ID from the constant value of
  2067. // the declaration.
  2068. auto function_const_inst = resolver.local_insts().Get(
  2069. resolver.local_constant_values().GetInstId(function_const_id));
  2070. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  2071. function_const_inst.type_id());
  2072. function_id = function_type.function_id;
  2073. }
  2074. auto call_param_patterns = GetLocalInstBlockContents(
  2075. resolver, import_function.call_param_patterns_id);
  2076. auto return_type_const_id = SemIR::ConstantId::None;
  2077. if (import_function.return_type_inst_id.has_value()) {
  2078. return_type_const_id =
  2079. GetLocalConstantId(resolver, import_function.return_type_inst_id);
  2080. }
  2081. auto return_form_const_id = SemIR::ConstantId::None;
  2082. if (import_function.return_form_inst_id.has_value()) {
  2083. return_form_const_id =
  2084. GetLocalConstantId(resolver, import_function.return_form_inst_id);
  2085. }
  2086. auto parent_scope_id =
  2087. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  2088. auto implicit_param_patterns = GetLocalInstBlockContents(
  2089. resolver, import_function.implicit_param_patterns_id);
  2090. auto param_patterns =
  2091. GetLocalInstBlockContents(resolver, import_function.param_patterns_id);
  2092. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  2093. auto self_param_id =
  2094. GetLocalConstantInstId(resolver, import_function.self_param_id);
  2095. auto return_patterns =
  2096. GetLocalInstBlockContents(resolver, import_function.return_patterns_id);
  2097. auto& new_function = resolver.local_functions().Get(function_id);
  2098. if (resolver.HasNewWork()) {
  2099. return ResolveResult::Retry(function_const_id,
  2100. new_function.first_decl_id());
  2101. }
  2102. // Add the function declaration.
  2103. new_function.call_param_patterns_id = GetLocalCanonicalInstBlockId(
  2104. resolver, import_function.call_param_patterns_id, call_param_patterns);
  2105. new_function.parent_scope_id = parent_scope_id;
  2106. new_function.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2107. resolver, import_function.implicit_param_patterns_id,
  2108. implicit_param_patterns);
  2109. new_function.self_param_id = self_param_id;
  2110. new_function.param_patterns_id = GetLocalCanonicalInstBlockId(
  2111. resolver, import_function.param_patterns_id, param_patterns);
  2112. new_function.return_type_inst_id = SemIR::TypeInstId::None;
  2113. if (import_function.return_type_inst_id.has_value()) {
  2114. new_function.return_type_inst_id = AddLoadedImportRefForType(
  2115. resolver, import_function.return_type_inst_id, return_type_const_id);
  2116. }
  2117. new_function.return_form_inst_id = SemIR::InstId::None;
  2118. if (import_function.return_form_inst_id.has_value()) {
  2119. new_function.return_form_inst_id = AddLoadedImportRef(
  2120. resolver, SemIR::FormType::TypeId, import_function.return_form_inst_id,
  2121. return_form_const_id);
  2122. }
  2123. new_function.return_patterns_id = GetLocalCanonicalInstBlockId(
  2124. resolver, import_function.return_patterns_id, return_patterns);
  2125. if (import_function.definition_id.has_value()) {
  2126. new_function.definition_id = new_function.first_owning_decl_id;
  2127. }
  2128. switch (import_function.special_function_kind) {
  2129. case SemIR::Function::SpecialFunctionKind::CppThunk:
  2130. case SemIR::Function::SpecialFunctionKind::None: {
  2131. break;
  2132. }
  2133. case SemIR::Function::SpecialFunctionKind::Builtin: {
  2134. new_function.SetBuiltinFunction(import_function.builtin_function_kind());
  2135. break;
  2136. }
  2137. case SemIR::Function::SpecialFunctionKind::CoreWitness: {
  2138. new_function.SetCoreWitness();
  2139. break;
  2140. }
  2141. case SemIR::Function::SpecialFunctionKind::Thunk: {
  2142. auto entity_name_id = resolver.local_entity_names().AddCanonical(
  2143. {.name_id = new_function.name_id,
  2144. .parent_scope_id = new_function.parent_scope_id});
  2145. new_function.SetThunk(AddImportRef(
  2146. resolver, import_function.thunk_decl_id(), entity_name_id));
  2147. break;
  2148. }
  2149. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  2150. resolver.local_context().TODO(SemIR::LocId::None,
  2151. "Unsupported: Importing C++ functions that "
  2152. "require thunks indirectly");
  2153. }
  2154. }
  2155. return ResolveResult::FinishGenericOrDone(
  2156. resolver, function_const_id, new_function.first_decl_id(),
  2157. import_function.generic_id, new_function.generic_id, generic_data);
  2158. }
  2159. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2160. SemIR::VtableDecl inst) -> ResolveResult {
  2161. const auto& import_vtable = resolver.import_vtables().Get(inst.vtable_id);
  2162. auto class_const_id =
  2163. GetLocalConstantId(resolver, resolver.import_classes()
  2164. .Get(import_vtable.class_id)
  2165. .first_owning_decl_id);
  2166. auto class_const_inst = resolver.local_insts().Get(
  2167. resolver.local_constant_values().GetInstId(class_const_id));
  2168. // TODO: Ensure the vtable is only imported once, in eg: if there's distinct
  2169. // vtable constants (imported from multiple libraries using the vtable) that
  2170. // refer to the same vtable, the vtable should still be singular.
  2171. auto virtual_functions =
  2172. resolver.import_inst_blocks().Get(import_vtable.virtual_functions_id);
  2173. llvm::SmallVector<SemIR::InstId> lazy_virtual_functions;
  2174. lazy_virtual_functions.reserve(virtual_functions.size());
  2175. for (auto vtable_entry_id : virtual_functions) {
  2176. auto local_attached_constant_id =
  2177. GetLocalConstantId(resolver, vtable_entry_id);
  2178. lazy_virtual_functions.push_back(
  2179. resolver.local_constant_values().GetInstIdIfValid(
  2180. local_attached_constant_id));
  2181. }
  2182. if (resolver.HasNewWork()) {
  2183. return ResolveResult::Retry();
  2184. }
  2185. for (auto [import_vtable_entry_inst_id, local_vtable_entry_inst_id] :
  2186. llvm::zip_equal(virtual_functions, lazy_virtual_functions)) {
  2187. // Use LoadedImportRef for imported symbolic constant vtable entries so they
  2188. // can carry attached constants necessary for applying specifics to these
  2189. // constants when they are used.
  2190. auto local_attached_constant_id =
  2191. resolver.local_constant_values().GetAttached(
  2192. local_vtable_entry_inst_id);
  2193. if (local_attached_constant_id.is_symbolic()) {
  2194. local_vtable_entry_inst_id = AddLoadedImportRef(
  2195. resolver,
  2196. GetSingletonType(resolver.local_context(),
  2197. SemIR::SpecificFunctionType::TypeInstId),
  2198. import_vtable_entry_inst_id, local_attached_constant_id);
  2199. }
  2200. }
  2201. auto class_id = SemIR::ClassId::None;
  2202. if (class_const_inst.Is<SemIR::ClassType>()) {
  2203. class_id = class_const_inst.As<SemIR::ClassType>().class_id;
  2204. } else {
  2205. auto generic_class_type =
  2206. resolver.local_types().GetAs<SemIR::GenericClassType>(
  2207. class_const_inst.type_id());
  2208. class_id = generic_class_type.class_id;
  2209. }
  2210. auto new_vtable_id = resolver.local_vtables().Add(
  2211. {{.class_id = class_id,
  2212. .virtual_functions_id =
  2213. resolver.local_inst_blocks().Add(lazy_virtual_functions)}});
  2214. return ResolveResult::Deduplicated<SemIR::VtableDecl>(
  2215. resolver, {.type_id = GetPointerType(resolver.local_context(),
  2216. SemIR::VtableType::TypeInstId),
  2217. .vtable_id = new_vtable_id});
  2218. }
  2219. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2220. SemIR::VtablePtr inst) -> ResolveResult {
  2221. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2222. auto vtable_const_id = GetLocalConstantId(
  2223. resolver, resolver.import_classes()
  2224. .Get(resolver.import_vtables().Get(inst.vtable_id).class_id)
  2225. .vtable_decl_id);
  2226. auto vtable_const_inst = resolver.local_insts().Get(
  2227. resolver.local_constant_values().GetInstId(vtable_const_id));
  2228. if (resolver.HasNewWork()) {
  2229. return ResolveResult::Retry();
  2230. }
  2231. return ResolveResult::Deduplicated<SemIR::VtablePtr>(
  2232. resolver,
  2233. {.type_id = GetPointerType(resolver.local_context(),
  2234. SemIR::VtableType::TypeInstId),
  2235. .vtable_id = vtable_const_inst.As<SemIR::VtableDecl>().vtable_id,
  2236. .specific_id =
  2237. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data)});
  2238. }
  2239. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2240. SemIR::FunctionType inst) -> ResolveResult {
  2241. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2242. auto fn_val_id = GetLocalConstantInstId(
  2243. resolver,
  2244. resolver.import_functions().Get(inst.function_id).first_decl_id());
  2245. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2246. if (resolver.HasNewWork()) {
  2247. return ResolveResult::Retry();
  2248. }
  2249. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  2250. return ResolveResult::Deduplicated<SemIR::FunctionType>(
  2251. resolver, {.type_id = SemIR::TypeType::TypeId,
  2252. .function_id = resolver.local_types()
  2253. .GetAs<SemIR::FunctionType>(fn_type_id)
  2254. .function_id,
  2255. .specific_id = GetOrAddLocalSpecific(
  2256. resolver, inst.specific_id, specific_data)});
  2257. }
  2258. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2259. SemIR::FunctionTypeWithSelfType inst)
  2260. -> ResolveResult {
  2261. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2262. auto interface_function_type_id =
  2263. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  2264. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  2265. if (resolver.HasNewWork()) {
  2266. return ResolveResult::Retry();
  2267. }
  2268. return ResolveResult::Deduplicated<SemIR::FunctionTypeWithSelfType>(
  2269. resolver, {.type_id = SemIR::TypeType::TypeId,
  2270. .interface_function_type_id = interface_function_type_id,
  2271. .self_id = self_id});
  2272. }
  2273. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2274. SemIR::GenericClassType inst) -> ResolveResult {
  2275. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2276. auto class_val_id = GetLocalConstantInstId(
  2277. resolver,
  2278. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  2279. if (resolver.HasNewWork()) {
  2280. return ResolveResult::Retry();
  2281. }
  2282. auto class_val = resolver.local_insts().Get(class_val_id);
  2283. CARBON_CHECK(
  2284. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  2285. return ResolveResult::Done(
  2286. resolver.local_types().GetConstantId(class_val.type_id()));
  2287. }
  2288. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2289. SemIR::GenericInterfaceType inst)
  2290. -> ResolveResult {
  2291. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2292. auto interface_val_id = GetLocalConstantInstId(
  2293. resolver,
  2294. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2295. if (resolver.HasNewWork()) {
  2296. return ResolveResult::Retry();
  2297. }
  2298. auto interface_val = resolver.local_insts().Get(interface_val_id);
  2299. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  2300. interface_val.type_id()));
  2301. return ResolveResult::Done(
  2302. resolver.local_types().GetConstantId(interface_val.type_id()));
  2303. }
  2304. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2305. SemIR::GenericNamedConstraintType inst)
  2306. -> ResolveResult {
  2307. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2308. auto constraint_val_id =
  2309. GetLocalConstantInstId(resolver, resolver.import_named_constraints()
  2310. .Get(inst.named_constraint_id)
  2311. .first_owning_decl_id);
  2312. if (resolver.HasNewWork()) {
  2313. return ResolveResult::Retry();
  2314. }
  2315. auto constraint_val = resolver.local_insts().Get(constraint_val_id);
  2316. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericNamedConstraintType>(
  2317. constraint_val.type_id()));
  2318. return ResolveResult::Done(
  2319. resolver.local_types().GetConstantId(constraint_val.type_id()));
  2320. }
  2321. // Make a declaration of an impl. This is done as a separate step from
  2322. // importing the impl definition in order to resolve cycles.
  2323. static auto ImportImplDecl(ImportContext& context,
  2324. const SemIR::Impl& import_impl,
  2325. SemIR::InstId witness_id)
  2326. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  2327. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  2328. .decl_block_id = SemIR::InstBlockId::Empty};
  2329. auto impl_decl_id = AddPlaceholderImportedInst(
  2330. context, import_impl.latest_decl_id(), impl_decl);
  2331. impl_decl.impl_id = context.local_impls().Add(
  2332. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  2333. {.self_id = SemIR::TypeInstId::None,
  2334. .constraint_id = SemIR::TypeInstId::None,
  2335. .interface = SemIR::SpecificInterface::None,
  2336. .witness_id = witness_id,
  2337. .scope_id = import_impl.is_complete() ? AddPlaceholderNameScope(context)
  2338. : SemIR::NameScopeId::None,
  2339. .is_final = import_impl.is_final}});
  2340. // Write the impl ID into the ImplDecl.
  2341. auto impl_const_id =
  2342. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  2343. return {impl_decl.impl_id, impl_const_id};
  2344. }
  2345. // Imports the definition of an impl.
  2346. static auto ImportImplDefinition(ImportContext& context,
  2347. const SemIR::Impl& import_impl,
  2348. SemIR::Impl& new_impl) -> void {
  2349. new_impl.definition_id = new_impl.first_owning_decl_id;
  2350. new_impl.defined = true;
  2351. if (import_impl.scope_id.has_value()) {
  2352. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  2353. new_scope.Set(new_impl.first_owning_decl_id, SemIR::NameId::None,
  2354. new_impl.parent_scope_id);
  2355. // Import the contents of the definition scope, if we might need it. Name
  2356. // lookup is never performed into this scope by a user of the impl, so
  2357. // this is only necessary in the same library that defined the impl, in
  2358. // order to support defining members of the impl out of line in the impl
  2359. // file when the impl is defined in the API file.
  2360. // TODO: Check to see if this impl is owned by the API file, rather than
  2361. // merely being imported into it.
  2362. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2363. const auto& import_scope =
  2364. context.import_name_scopes().Get(import_impl.scope_id);
  2365. // Push a block so that we can add scoped instructions to it.
  2366. context.local_context().inst_block_stack().Push();
  2367. AddNameScopeImportRefs(context, import_scope, new_scope);
  2368. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  2369. }
  2370. }
  2371. }
  2372. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2373. SemIR::ImplDecl inst,
  2374. SemIR::ConstantId impl_const_id)
  2375. -> ResolveResult {
  2376. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  2377. // functions. Factor out the commonality.
  2378. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2379. auto specific_interface_data =
  2380. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  2381. SemIR::ImplId impl_id = SemIR::ImplId::None;
  2382. if (!impl_const_id.has_value()) {
  2383. if (resolver.HasNewWork()) {
  2384. // This is the end of the first phase. Don't make a new impl yet if we
  2385. // already have new work.
  2386. return ResolveResult::Retry();
  2387. }
  2388. // On the second phase, create a forward declaration of the impl for any
  2389. // recursive references.
  2390. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  2391. std::tie(impl_id, impl_const_id) =
  2392. ImportImplDecl(resolver, import_impl, witness_id);
  2393. } else {
  2394. // On the third phase, compute the impl ID from the "constant value" of
  2395. // the declaration, which is a reference to the created ImplDecl.
  2396. auto impl_const_inst =
  2397. resolver.local_constant_values().GetInstAs<SemIR::ImplDecl>(
  2398. impl_const_id);
  2399. impl_id = impl_const_inst.impl_id;
  2400. }
  2401. // Load constants for the definition.
  2402. auto parent_scope_id =
  2403. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  2404. auto implicit_param_patterns = GetLocalInstBlockContents(
  2405. resolver, import_impl.implicit_param_patterns_id);
  2406. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  2407. auto self_const_id = GetLocalConstantId(resolver, import_impl.self_id);
  2408. auto constraint_const_id =
  2409. GetLocalConstantId(resolver, import_impl.constraint_id);
  2410. auto& new_impl = resolver.local_impls().Get(impl_id);
  2411. if (resolver.HasNewWork()) {
  2412. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2413. }
  2414. new_impl.parent_scope_id = parent_scope_id;
  2415. new_impl.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2416. resolver, import_impl.implicit_param_patterns_id,
  2417. implicit_param_patterns);
  2418. // Create instructions for self and constraint to hold the symbolic constant
  2419. // value for a generic impl.
  2420. new_impl.self_id =
  2421. AddLoadedImportRefForType(resolver, import_impl.self_id, self_const_id);
  2422. new_impl.constraint_id = AddLoadedImportRefForType(
  2423. resolver, import_impl.constraint_id, constraint_const_id);
  2424. new_impl.interface = GetLocalSpecificInterface(
  2425. resolver, import_impl.interface, specific_interface_data);
  2426. // Create a local IdentifiedFacetType for the imported facet type, since impl
  2427. // declarations always identify the facet type.
  2428. if (auto facet_type =
  2429. resolver.local_constant_values().TryGetInstAs<SemIR::FacetType>(
  2430. constraint_const_id)) {
  2431. // Lookups later will be with the unattached constant, whereas
  2432. // GetLocalConstantId gave us an attached constant.
  2433. auto unattached_self_const_id =
  2434. resolver.local_constant_values().GetUnattachedConstant(self_const_id);
  2435. RequireIdentifiedFacetType(
  2436. resolver.local_context(), SemIR::LocId::None, unattached_self_const_id,
  2437. *facet_type, []([[maybe_unused]] auto& builder) {
  2438. CARBON_FATAL("Imported impl constraint can't be identified");
  2439. });
  2440. }
  2441. if (import_impl.is_complete()) {
  2442. ImportImplDefinition(resolver, import_impl, new_impl);
  2443. }
  2444. // If the `impl` is declared in the API file corresponding to the current
  2445. // file, add this to impl lookup so that it can be found by redeclarations
  2446. // in the current file.
  2447. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2448. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2449. }
  2450. return ResolveResult::FinishGenericOrDone(
  2451. resolver, impl_const_id, new_impl.first_decl_id(), import_impl.generic_id,
  2452. new_impl.generic_id, generic_data);
  2453. }
  2454. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2455. SemIR::RequireImplsDecl inst,
  2456. SemIR::ConstantId require_decl_const_id)
  2457. -> ResolveResult {
  2458. const auto& import_require =
  2459. resolver.import_require_impls().Get(inst.require_impls_id);
  2460. auto require_decl_id = SemIR::InstId::None;
  2461. auto require_impls_id = SemIR::RequireImplsId::None;
  2462. if (!require_decl_const_id.has_value()) {
  2463. // Phase one: Make the decl and structure with placeholder values to be
  2464. // filled in. Begin the generic so instructions can be attached to it.
  2465. SemIR::RequireImplsDecl require_decl = {
  2466. .require_impls_id = SemIR::RequireImplsId::None,
  2467. .decl_block_id = SemIR::InstBlockId::Empty};
  2468. auto require_decl_id = AddPlaceholderImportedInst(
  2469. resolver, import_require.decl_id, require_decl);
  2470. require_impls_id = resolver.local_require_impls().Add(
  2471. {.self_id = SemIR::TypeInstId::None,
  2472. .facet_type_inst_id = SemIR::TypeInstId::None,
  2473. .decl_id = require_decl_id,
  2474. .parent_scope_id = SemIR::NameScopeId::None,
  2475. .generic_id = ImportIncompleteGeneric(resolver, require_decl_id,
  2476. import_require.generic_id)});
  2477. // Write the RequireImplsId into the RequireImplsDecl.
  2478. require_decl.require_impls_id = require_impls_id;
  2479. require_decl_const_id =
  2480. ReplacePlaceholderImportedInst(resolver, require_decl_id, require_decl);
  2481. } else {
  2482. // Phase two: Get the `require_decl_id` and `require_impls_id` from the
  2483. // RequireImplsDecl constructed in phase one.
  2484. require_decl_id =
  2485. resolver.local_constant_values().GetInstId(require_decl_const_id);
  2486. require_impls_id = resolver.local_insts()
  2487. .GetAs<SemIR::RequireImplsDecl>(require_decl_id)
  2488. .require_impls_id;
  2489. }
  2490. // Load dependent constants.
  2491. auto parent_scope_id =
  2492. GetLocalNameScopeId(resolver, import_require.parent_scope_id);
  2493. auto generic_data = GetLocalGenericData(resolver, import_require.generic_id);
  2494. auto self_const_id = GetLocalConstantId(resolver, import_require.self_id);
  2495. auto facet_type_const_id =
  2496. GetLocalConstantId(resolver, import_require.facet_type_inst_id);
  2497. if (resolver.HasNewWork()) {
  2498. return ResolveResult::Retry(require_decl_const_id, require_decl_id);
  2499. }
  2500. // Fill in the RequireImpls structure.
  2501. auto& new_require = resolver.local_require_impls().Get(require_impls_id);
  2502. new_require.self_id = AddLoadedImportRefForType(
  2503. resolver, import_require.self_id, self_const_id);
  2504. new_require.facet_type_inst_id = AddLoadedImportRefForType(
  2505. resolver, import_require.facet_type_inst_id, facet_type_const_id);
  2506. new_require.extend_self = import_require.extend_self;
  2507. new_require.parent_scope_id = parent_scope_id;
  2508. return ResolveResult::FinishGenericOrDone(
  2509. resolver, require_decl_const_id, require_decl_id,
  2510. import_require.generic_id, new_require.generic_id, generic_data);
  2511. }
  2512. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2513. SemIR::ImportRefLoaded /*inst*/,
  2514. SemIR::InstId inst_id) -> ResolveResult {
  2515. // Return the constant for the instruction of the imported constant.
  2516. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2517. CARBON_CHECK(constant_id.has_value(),
  2518. "Loaded import ref has no constant value");
  2519. if (!constant_id.is_constant()) {
  2520. resolver.local_context().TODO(
  2521. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2522. return ResolveResult::Done(constant_id);
  2523. }
  2524. auto new_constant_id = GetLocalConstantId(resolver, constant_id);
  2525. return ResolveResult::RetryOrDone(resolver, new_constant_id);
  2526. }
  2527. // Make a declaration of an interface. This is done as a separate step from
  2528. // importing the interface definition in order to resolve cycles.
  2529. static auto ImportInterfaceDecl(ImportContext& context,
  2530. const SemIR::Interface& import_interface,
  2531. SemIR::SpecificId enclosing_specific_id)
  2532. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2533. SemIR::InterfaceDecl interface_decl = {
  2534. .type_id = SemIR::TypeType::TypeId,
  2535. .interface_id = SemIR::InterfaceId::None,
  2536. .decl_block_id = SemIR::InstBlockId::Empty};
  2537. auto interface_decl_id = AddPlaceholderImportedInst(
  2538. context, import_interface.first_owning_decl_id, interface_decl);
  2539. // Start with an incomplete interface.
  2540. //
  2541. // The generic_with_self_id is constructed by the InterfaceWithSelfDecl
  2542. // instruction inside the InterfaceDecl's body.
  2543. interface_decl.interface_id = context.local_interfaces().Add(
  2544. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2545. import_interface),
  2546. {.scope_without_self_id = import_interface.is_complete()
  2547. ? AddPlaceholderNameScope(context)
  2548. : SemIR::NameScopeId::None,
  2549. .scope_with_self_id = import_interface.is_complete()
  2550. ? AddPlaceholderNameScope(context)
  2551. : SemIR::NameScopeId::None}});
  2552. if (import_interface.has_parameters()) {
  2553. interface_decl.type_id = GetGenericInterfaceType(
  2554. context.local_context(), interface_decl.interface_id,
  2555. enclosing_specific_id);
  2556. }
  2557. // Write the interface ID into the InterfaceDecl.
  2558. auto interface_const_id = ReplacePlaceholderImportedInst(
  2559. context, interface_decl_id, interface_decl);
  2560. return {interface_decl.interface_id, interface_const_id};
  2561. }
  2562. // Imports the definition for an interface that has been imported as a forward
  2563. // declaration.
  2564. static auto ImportInterfaceDefinition(ImportContext& context,
  2565. const SemIR::Interface& import_interface,
  2566. SemIR::Interface& new_interface,
  2567. SemIR::InstId self_param_id) -> void {
  2568. auto& new_scope =
  2569. context.local_name_scopes().Get(new_interface.scope_without_self_id);
  2570. const auto& import_scope =
  2571. context.import_name_scopes().Get(import_interface.scope_without_self_id);
  2572. // Push a block so that we can add scoped instructions to it.
  2573. context.local_context().inst_block_stack().Push();
  2574. InitializeNameScopeAndImportRefs(
  2575. context, import_scope, new_scope, new_interface.first_owning_decl_id,
  2576. SemIR::NameId::None, new_interface.parent_scope_id);
  2577. new_interface.body_block_without_self_id =
  2578. context.local_context().inst_block_stack().Pop();
  2579. new_interface.self_param_id = self_param_id;
  2580. }
  2581. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2582. SemIR::InterfaceDecl inst,
  2583. SemIR::ConstantId interface_const_id)
  2584. -> ResolveResult {
  2585. const auto& import_interface =
  2586. resolver.import_interfaces().Get(inst.interface_id);
  2587. auto interface_id = SemIR::InterfaceId::None;
  2588. if (!interface_const_id.has_value()) {
  2589. auto import_specific_id = SemIR::SpecificId::None;
  2590. if (auto import_generic_interface_type =
  2591. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2592. inst.type_id)) {
  2593. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2594. }
  2595. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2596. if (resolver.HasNewWork()) {
  2597. // This is the end of the first phase. Don't make a new interface yet if
  2598. // we already have new work.
  2599. return ResolveResult::Retry();
  2600. }
  2601. // On the second phase, create a forward declaration of the interface.
  2602. auto enclosing_specific_id =
  2603. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2604. std::tie(interface_id, interface_const_id) =
  2605. ImportInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2606. } else {
  2607. // On the third phase, compute the interface ID from the constant value of
  2608. // the declaration.
  2609. auto interface_const_inst = resolver.local_insts().Get(
  2610. resolver.local_constant_values().GetInstId(interface_const_id));
  2611. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2612. const SemIR::FacetTypeInfo& facet_type_info =
  2613. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2614. auto single = facet_type_info.TryAsSingleExtend();
  2615. CARBON_CHECK(single);
  2616. interface_id = std::get<SemIR::SpecificInterface>(*single).interface_id;
  2617. } else {
  2618. auto generic_interface_type =
  2619. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2620. interface_const_inst.type_id());
  2621. interface_id = generic_interface_type.interface_id;
  2622. }
  2623. }
  2624. auto parent_scope_id =
  2625. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2626. auto implicit_param_patterns = GetLocalInstBlockContents(
  2627. resolver, import_interface.implicit_param_patterns_id);
  2628. auto param_patterns =
  2629. GetLocalInstBlockContents(resolver, import_interface.param_patterns_id);
  2630. auto generic_data =
  2631. GetLocalGenericData(resolver, import_interface.generic_id);
  2632. auto require_impls = GetLocalRequireImplsBlockContents(
  2633. resolver, import_interface.require_impls_block_id);
  2634. std::optional<SemIR::InstId> self_param_id;
  2635. if (import_interface.is_complete()) {
  2636. // Note the TODO on ResolveLocalEvalBlock, the generic eval block is rebuilt
  2637. // instead of being imported. When it's imported maybe this should be an
  2638. // ImportRef?
  2639. self_param_id =
  2640. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2641. // Importing the `generic_with_self_id` imports the InterfaceWithSelfDecl
  2642. // which sets the associated constants in the interface (if it's complete)
  2643. // which marks the local interface as complete. The InterfaceWithSelfDecl
  2644. // also sets the `generic_with_self_id` field on the local interface.
  2645. GetLocalConstantId(resolver, import_interface.generic_with_self_id);
  2646. }
  2647. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2648. if (resolver.HasNewWork()) {
  2649. return ResolveResult::Retry(interface_const_id,
  2650. new_interface.first_decl_id());
  2651. }
  2652. new_interface.parent_scope_id = parent_scope_id;
  2653. new_interface.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2654. resolver, import_interface.implicit_param_patterns_id,
  2655. implicit_param_patterns);
  2656. new_interface.param_patterns_id = GetLocalCanonicalInstBlockId(
  2657. resolver, import_interface.param_patterns_id, param_patterns);
  2658. new_interface.require_impls_block_id = GetLocalCanonicalRequireImplsBlockId(
  2659. resolver, import_interface.require_impls_block_id, require_impls);
  2660. if (import_interface.is_complete()) {
  2661. CARBON_CHECK(self_param_id);
  2662. ImportInterfaceDefinition(resolver, import_interface, new_interface,
  2663. *self_param_id);
  2664. }
  2665. // The interface's `generic_with_self_id` is filled out and finished by
  2666. // importing the InterfaceWithSelfDecl instruction which we find inside the
  2667. // InterfaceDecl.
  2668. return ResolveResult::FinishGenericOrDone(
  2669. resolver, interface_const_id, new_interface.first_decl_id(),
  2670. import_interface.generic_id, new_interface.generic_id, generic_data);
  2671. }
  2672. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2673. SemIR::InterfaceWithSelfDecl inst,
  2674. SemIR::ConstantId const_id) -> ResolveResult {
  2675. auto interface_const_id = GetLocalConstantId(
  2676. resolver,
  2677. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2678. // These are set differently in each phase.
  2679. auto decl_id = SemIR::InstId::None;
  2680. auto local_interface_id = SemIR::InterfaceId::None;
  2681. auto generic_with_self_id = SemIR::GenericId::None;
  2682. // Note that InterfaceWithSelfDecl always occurs inside an InterfaceDecl, so
  2683. // the import here can rely on the `Interface` already existing.
  2684. auto import_generic_with_self_id =
  2685. resolver.import_interfaces().Get(inst.interface_id).generic_with_self_id;
  2686. if (!const_id.has_value()) {
  2687. if (resolver.HasNewWork()) {
  2688. // This is the end of the first phase. Don't make a new generic yet if we
  2689. // already have new work.
  2690. return ResolveResult::Retry();
  2691. }
  2692. // Get the local interface ID from the constant value of the interface decl,
  2693. // which is either a GenericInterfaceType (if generic) or a FacetType (if
  2694. // not).
  2695. if (auto struct_value =
  2696. resolver.local_constant_values().TryGetInstAs<SemIR::StructValue>(
  2697. interface_const_id)) {
  2698. auto generic_interface_type =
  2699. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2700. struct_value->type_id);
  2701. local_interface_id = generic_interface_type.interface_id;
  2702. } else {
  2703. auto local_facet_type =
  2704. resolver.local_constant_values().GetInstAs<SemIR::FacetType>(
  2705. interface_const_id);
  2706. const auto& local_facet_type_info =
  2707. resolver.local_facet_types().Get(local_facet_type.facet_type_id);
  2708. auto single_interface = *local_facet_type_info.TryAsSingleExtend();
  2709. CARBON_KIND_SWITCH(single_interface) {
  2710. case CARBON_KIND(SemIR::SpecificInterface specific_interface): {
  2711. local_interface_id = specific_interface.interface_id;
  2712. break;
  2713. }
  2714. case CARBON_KIND(SemIR::SpecificNamedConstraint _): {
  2715. CARBON_FATAL(
  2716. "Unexpected NamedConstraint in InterfaceDecl value's facet type");
  2717. }
  2718. }
  2719. }
  2720. // On the second phase, create a local decl instruction with a local generic
  2721. // ID. Store that generic ID in the local interface.
  2722. const auto& import_generic =
  2723. resolver.import_generics().Get(import_generic_with_self_id);
  2724. SemIR::InterfaceWithSelfDecl interface_with_self_decl = {
  2725. .interface_id = SemIR::InterfaceId::None};
  2726. decl_id = AddPlaceholderImportedInst(resolver, import_generic.decl_id,
  2727. interface_with_self_decl);
  2728. generic_with_self_id =
  2729. ImportIncompleteGeneric(resolver, decl_id, import_generic_with_self_id);
  2730. interface_with_self_decl.interface_id = local_interface_id;
  2731. const_id = ReplacePlaceholderImportedInst(resolver, decl_id,
  2732. interface_with_self_decl);
  2733. resolver.local_interfaces().Get(local_interface_id).generic_with_self_id =
  2734. generic_with_self_id;
  2735. } else {
  2736. // On the third phase, get the interface, decl and generic IDs from the
  2737. // constant value of the decl (which is itself) from the second phase.
  2738. auto decl = resolver.local_constant_values()
  2739. .GetInstAs<SemIR::InterfaceWithSelfDecl>(const_id);
  2740. local_interface_id = decl.interface_id;
  2741. generic_with_self_id = resolver.local_interfaces()
  2742. .Get(local_interface_id)
  2743. .generic_with_self_id;
  2744. decl_id = resolver.local_generics().Get(generic_with_self_id).decl_id;
  2745. }
  2746. auto generic_with_self_data =
  2747. GetLocalGenericData(resolver, import_generic_with_self_id);
  2748. if (resolver.HasNewWork()) {
  2749. return ResolveResult::Retry(const_id, decl_id);
  2750. }
  2751. auto& local_interface = resolver.local_interfaces().Get(
  2752. resolver.local_insts()
  2753. .GetAs<SemIR::InterfaceWithSelfDecl>(decl_id)
  2754. .interface_id);
  2755. const auto& import_interface =
  2756. resolver.import_interfaces().Get(inst.interface_id);
  2757. auto& new_scope =
  2758. resolver.local_name_scopes().Get(local_interface.scope_with_self_id);
  2759. const auto& import_scope =
  2760. resolver.import_name_scopes().Get(import_interface.scope_with_self_id);
  2761. // Push a block so that we can add scoped instructions to it.
  2762. resolver.local_context().inst_block_stack().Push();
  2763. InitializeNameScopeAndImportRefs(resolver, import_scope, new_scope, decl_id,
  2764. SemIR::NameId::None,
  2765. local_interface.scope_without_self_id);
  2766. new_scope.set_is_interface_definition();
  2767. local_interface.associated_entities_id =
  2768. AddAssociatedEntities(resolver, local_interface.scope_with_self_id,
  2769. import_interface.associated_entities_id);
  2770. local_interface.body_block_with_self_id =
  2771. resolver.local_context().inst_block_stack().Pop();
  2772. return ResolveResult::FinishGenericOrDone(
  2773. resolver, const_id, decl_id, import_generic_with_self_id,
  2774. generic_with_self_id, generic_with_self_data);
  2775. }
  2776. // Make a declaration of a named constraint. This is done as a separate step
  2777. // from importing the constraint definition in order to resolve cycles.
  2778. static auto ImportNamedConstraintDecl(
  2779. ImportContext& context,
  2780. const SemIR::NamedConstraint& import_named_constraint,
  2781. SemIR::SpecificId enclosing_specific_id)
  2782. -> std::pair<SemIR::NamedConstraintId, SemIR::ConstantId> {
  2783. SemIR::NamedConstraintDecl named_constraint_decl = {
  2784. .type_id = SemIR::TypeType::TypeId,
  2785. .named_constraint_id = SemIR::NamedConstraintId::None,
  2786. .decl_block_id = SemIR::InstBlockId::Empty};
  2787. auto named_constraint_decl_id = AddPlaceholderImportedInst(
  2788. context, import_named_constraint.first_owning_decl_id,
  2789. named_constraint_decl);
  2790. // Start with an incomplete named constraint.
  2791. //
  2792. // The generic_with_self_id is constructed by the NamedConstraintWithSelfDecl
  2793. // instruction inside the NamedConstraintDecl's body.
  2794. named_constraint_decl.named_constraint_id =
  2795. context.local_named_constraints().Add(
  2796. {GetIncompleteLocalEntityBase(context, named_constraint_decl_id,
  2797. import_named_constraint),
  2798. {.scope_without_self_id = import_named_constraint.is_complete()
  2799. ? AddPlaceholderNameScope(context)
  2800. : SemIR::NameScopeId::None,
  2801. .scope_with_self_id = import_named_constraint.is_complete()
  2802. ? AddPlaceholderNameScope(context)
  2803. : SemIR::NameScopeId::None}});
  2804. if (import_named_constraint.has_parameters()) {
  2805. named_constraint_decl.type_id = GetGenericNamedConstraintType(
  2806. context.local_context(), named_constraint_decl.named_constraint_id,
  2807. enclosing_specific_id);
  2808. }
  2809. // Write the named constraint ID into the NameConstraintDecl.
  2810. auto interface_const_id = ReplacePlaceholderImportedInst(
  2811. context, named_constraint_decl_id, named_constraint_decl);
  2812. return {named_constraint_decl.named_constraint_id, interface_const_id};
  2813. }
  2814. // Imports the definition for a named constraint that has been imported as a
  2815. // forward declaration.
  2816. static auto ImportNamedConstraintDefinition(
  2817. ImportContext& context,
  2818. const SemIR::NamedConstraint& import_named_constraint,
  2819. SemIR::NamedConstraint& new_named_constraint, SemIR::InstId self_param_id)
  2820. -> void {
  2821. auto& new_scope = context.local_name_scopes().Get(
  2822. new_named_constraint.scope_without_self_id);
  2823. const auto& import_scope = context.import_name_scopes().Get(
  2824. import_named_constraint.scope_without_self_id);
  2825. // Push a block so that we can add scoped instructions to it.
  2826. context.local_context().inst_block_stack().Push();
  2827. InitializeNameScopeAndImportRefs(context, import_scope, new_scope,
  2828. new_named_constraint.first_owning_decl_id,
  2829. SemIR::NameId::None,
  2830. new_named_constraint.parent_scope_id);
  2831. new_named_constraint.body_block_without_self_id =
  2832. context.local_context().inst_block_stack().Pop();
  2833. new_named_constraint.self_param_id = self_param_id;
  2834. }
  2835. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2836. SemIR::NamedConstraintDecl inst,
  2837. SemIR::ConstantId named_constraint_const_id)
  2838. -> ResolveResult {
  2839. const auto& import_named_constraint =
  2840. resolver.import_named_constraints().Get(inst.named_constraint_id);
  2841. auto named_constraint_id = SemIR::NamedConstraintId::None;
  2842. if (!named_constraint_const_id.has_value()) {
  2843. auto import_specific_id = SemIR::SpecificId::None;
  2844. if (auto import_generic_named_constraint_type =
  2845. resolver.import_types().TryGetAs<SemIR::GenericNamedConstraintType>(
  2846. inst.type_id)) {
  2847. import_specific_id =
  2848. import_generic_named_constraint_type->enclosing_specific_id;
  2849. }
  2850. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2851. if (resolver.HasNewWork()) {
  2852. // This is the end of the first phase. Don't make a new interface yet if
  2853. // we already have new work.
  2854. return ResolveResult::Retry();
  2855. }
  2856. // On the second phase, create a forward declaration of the interface.
  2857. auto enclosing_specific_id =
  2858. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2859. std::tie(named_constraint_id, named_constraint_const_id) =
  2860. ImportNamedConstraintDecl(resolver, import_named_constraint,
  2861. enclosing_specific_id);
  2862. } else {
  2863. // On the third phase, compute the interface ID from the constant value of
  2864. // the declaration.
  2865. auto named_constraint_const_inst = resolver.local_insts().Get(
  2866. resolver.local_constant_values().GetInstId(named_constraint_const_id));
  2867. if (auto facet_type =
  2868. named_constraint_const_inst.TryAs<SemIR::FacetType>()) {
  2869. const SemIR::FacetTypeInfo& facet_type_info =
  2870. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2871. auto single = facet_type_info.TryAsSingleExtend();
  2872. CARBON_CHECK(single);
  2873. named_constraint_id =
  2874. std::get<SemIR::SpecificNamedConstraint>(*single).named_constraint_id;
  2875. } else {
  2876. auto generic_named_constraint_type =
  2877. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  2878. named_constraint_const_inst.type_id());
  2879. named_constraint_id = generic_named_constraint_type.named_constraint_id;
  2880. }
  2881. }
  2882. auto parent_scope_id =
  2883. GetLocalNameScopeId(resolver, import_named_constraint.parent_scope_id);
  2884. auto implicit_param_patterns = GetLocalInstBlockContents(
  2885. resolver, import_named_constraint.implicit_param_patterns_id);
  2886. auto param_patterns = GetLocalInstBlockContents(
  2887. resolver, import_named_constraint.param_patterns_id);
  2888. auto generic_data =
  2889. GetLocalGenericData(resolver, import_named_constraint.generic_id);
  2890. auto require_impls = GetLocalRequireImplsBlockContents(
  2891. resolver, import_named_constraint.require_impls_block_id);
  2892. std::optional<SemIR::InstId> self_param_id;
  2893. if (import_named_constraint.is_complete()) {
  2894. self_param_id =
  2895. GetLocalConstantInstId(resolver, import_named_constraint.self_param_id);
  2896. // Importing the `generic_with_self_id` imports the
  2897. // NamedConstraintWithSelfDecl which (if it's complete) marks the local
  2898. // named constraint as complete. The NamedConstraintWithSelfDecl also sets
  2899. // the `generic_with_self_id` field on the local interface.
  2900. GetLocalConstantId(resolver, import_named_constraint.generic_with_self_id);
  2901. }
  2902. auto& new_named_constraint =
  2903. resolver.local_named_constraints().Get(named_constraint_id);
  2904. if (resolver.HasNewWork()) {
  2905. return ResolveResult::Retry(named_constraint_const_id,
  2906. new_named_constraint.first_decl_id());
  2907. }
  2908. new_named_constraint.parent_scope_id = parent_scope_id;
  2909. new_named_constraint.implicit_param_patterns_id =
  2910. GetLocalCanonicalInstBlockId(
  2911. resolver, import_named_constraint.implicit_param_patterns_id,
  2912. implicit_param_patterns);
  2913. new_named_constraint.param_patterns_id = GetLocalCanonicalInstBlockId(
  2914. resolver, import_named_constraint.param_patterns_id, param_patterns);
  2915. new_named_constraint.require_impls_block_id =
  2916. GetLocalCanonicalRequireImplsBlockId(
  2917. resolver, import_named_constraint.require_impls_block_id,
  2918. require_impls);
  2919. if (import_named_constraint.is_complete()) {
  2920. CARBON_CHECK(self_param_id);
  2921. ImportNamedConstraintDefinition(resolver, import_named_constraint,
  2922. new_named_constraint, *self_param_id);
  2923. }
  2924. // The named constraint's `generic_with_self_id` is filled out and finished by
  2925. // importing the NamedConstraintWithSelfDecl instruction which we find inside
  2926. // the NamedConstraintDecl.
  2927. return ResolveResult::FinishGenericOrDone(
  2928. resolver, named_constraint_const_id, new_named_constraint.first_decl_id(),
  2929. import_named_constraint.generic_id, new_named_constraint.generic_id,
  2930. generic_data);
  2931. }
  2932. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2933. SemIR::NamedConstraintWithSelfDecl inst,
  2934. SemIR::ConstantId const_id) -> ResolveResult {
  2935. auto constraint_const_id =
  2936. GetLocalConstantId(resolver, resolver.import_named_constraints()
  2937. .Get(inst.named_constraint_id)
  2938. .first_owning_decl_id);
  2939. // These are set differently in each phase.
  2940. auto decl_id = SemIR::InstId::None;
  2941. auto local_constraint_id = SemIR::NamedConstraintId::None;
  2942. auto generic_with_self_id = SemIR::GenericId::None;
  2943. // Note that NamedConstraintWithSelfDecl always occurs inside an
  2944. // NamedConstraintDecl, so the import here can rely on the `NamedConstraint`
  2945. // already existing.
  2946. auto import_generic_with_self_id = resolver.import_named_constraints()
  2947. .Get(inst.named_constraint_id)
  2948. .generic_with_self_id;
  2949. if (!const_id.has_value()) {
  2950. if (resolver.HasNewWork()) {
  2951. // This is the end of the first phase. Don't make a new generic yet if we
  2952. // already have new work.
  2953. return ResolveResult::Retry();
  2954. }
  2955. // Get the local named constraint ID from the constant value of the named
  2956. // constraint decl, which is either a GenericNamedConstraintType (if
  2957. // generic) or a FacetType (if not).
  2958. if (auto struct_value =
  2959. resolver.local_constant_values().TryGetInstAs<SemIR::StructValue>(
  2960. constraint_const_id)) {
  2961. auto generic_constraint_type =
  2962. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  2963. struct_value->type_id);
  2964. local_constraint_id = generic_constraint_type.named_constraint_id;
  2965. } else {
  2966. auto local_facet_type =
  2967. resolver.local_constant_values().GetInstAs<SemIR::FacetType>(
  2968. constraint_const_id);
  2969. const auto& local_facet_type_info =
  2970. resolver.local_facet_types().Get(local_facet_type.facet_type_id);
  2971. auto single_interface = *local_facet_type_info.TryAsSingleExtend();
  2972. CARBON_KIND_SWITCH(single_interface) {
  2973. case CARBON_KIND(SemIR::SpecificNamedConstraint specific_constraint): {
  2974. local_constraint_id = specific_constraint.named_constraint_id;
  2975. break;
  2976. }
  2977. case CARBON_KIND(SemIR::SpecificInterface _): {
  2978. CARBON_FATAL(
  2979. "Unexpected Interface in NamedConstraintDecl value's facet type");
  2980. }
  2981. }
  2982. }
  2983. // On the second phase, create a local decl instruction with a local generic
  2984. // ID. Store that generic ID in the local interface.
  2985. const auto& import_generic =
  2986. resolver.import_generics().Get(import_generic_with_self_id);
  2987. SemIR::NamedConstraintWithSelfDecl constraint_with_self_decl = {
  2988. .named_constraint_id = SemIR::NamedConstraintId::None};
  2989. decl_id = AddPlaceholderImportedInst(resolver, import_generic.decl_id,
  2990. constraint_with_self_decl);
  2991. generic_with_self_id =
  2992. ImportIncompleteGeneric(resolver, decl_id, import_generic_with_self_id);
  2993. constraint_with_self_decl.named_constraint_id = local_constraint_id;
  2994. const_id = ReplacePlaceholderImportedInst(resolver, decl_id,
  2995. constraint_with_self_decl);
  2996. resolver.local_named_constraints()
  2997. .Get(local_constraint_id)
  2998. .generic_with_self_id = generic_with_self_id;
  2999. } else {
  3000. // On the third phase, get the interface, decl and generic IDs from the
  3001. // constant value of the decl (which is itself) from the second phase.
  3002. auto decl = resolver.local_constant_values()
  3003. .GetInstAs<SemIR::NamedConstraintWithSelfDecl>(const_id);
  3004. local_constraint_id = decl.named_constraint_id;
  3005. generic_with_self_id = resolver.local_named_constraints()
  3006. .Get(local_constraint_id)
  3007. .generic_with_self_id;
  3008. decl_id = resolver.local_generics().Get(generic_with_self_id).decl_id;
  3009. }
  3010. auto generic_with_self_data =
  3011. GetLocalGenericData(resolver, import_generic_with_self_id);
  3012. if (resolver.HasNewWork()) {
  3013. return ResolveResult::Retry(const_id, decl_id);
  3014. }
  3015. auto& local_constraint = resolver.local_named_constraints().Get(
  3016. resolver.local_insts()
  3017. .GetAs<SemIR::NamedConstraintWithSelfDecl>(decl_id)
  3018. .named_constraint_id);
  3019. const auto& import_constraint =
  3020. resolver.import_named_constraints().Get(inst.named_constraint_id);
  3021. auto& new_scope =
  3022. resolver.local_name_scopes().Get(local_constraint.scope_with_self_id);
  3023. const auto& import_scope =
  3024. resolver.import_name_scopes().Get(import_constraint.scope_with_self_id);
  3025. // Push a block so that we can add scoped instructions to it.
  3026. resolver.local_context().inst_block_stack().Push();
  3027. InitializeNameScopeAndImportRefs(resolver, import_scope, new_scope, decl_id,
  3028. SemIR::NameId::None,
  3029. local_constraint.scope_without_self_id);
  3030. local_constraint.complete = import_constraint.complete;
  3031. local_constraint.body_block_with_self_id =
  3032. resolver.local_context().inst_block_stack().Pop();
  3033. return ResolveResult::FinishGenericOrDone(
  3034. resolver, const_id, decl_id, import_generic_with_self_id,
  3035. generic_with_self_id, generic_with_self_data);
  3036. }
  3037. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3038. SemIR::FacetAccessType inst) -> ResolveResult {
  3039. auto facet_value_inst_id =
  3040. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  3041. if (resolver.HasNewWork()) {
  3042. return ResolveResult::Retry();
  3043. }
  3044. return ResolveResult::Deduplicated<SemIR::FacetAccessType>(
  3045. resolver, {.type_id = SemIR::TypeType::TypeId,
  3046. .facet_value_inst_id = facet_value_inst_id});
  3047. }
  3048. // Collects and assigns constants for a `FacetTypeInfo`. Discards constants when
  3049. // `local_facet_type_info` is null.
  3050. static auto ResolveFacetTypeInfo(
  3051. ImportRefResolver& resolver,
  3052. const SemIR::FacetTypeInfo& import_facet_type_info,
  3053. SemIR::FacetTypeInfo* local_facet_type_info) -> void {
  3054. if (local_facet_type_info) {
  3055. local_facet_type_info->extend_constraints.reserve(
  3056. import_facet_type_info.extend_constraints.size());
  3057. }
  3058. for (auto interface : import_facet_type_info.extend_constraints) {
  3059. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  3060. if (local_facet_type_info) {
  3061. local_facet_type_info->extend_constraints.push_back(
  3062. GetLocalSpecificInterface(resolver, interface, data));
  3063. }
  3064. }
  3065. if (local_facet_type_info) {
  3066. local_facet_type_info->self_impls_constraints.reserve(
  3067. import_facet_type_info.self_impls_constraints.size());
  3068. }
  3069. for (auto interface : import_facet_type_info.self_impls_constraints) {
  3070. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  3071. if (local_facet_type_info) {
  3072. local_facet_type_info->self_impls_constraints.push_back(
  3073. GetLocalSpecificInterface(resolver, interface, data));
  3074. }
  3075. }
  3076. if (local_facet_type_info) {
  3077. local_facet_type_info->extend_named_constraints.reserve(
  3078. import_facet_type_info.extend_named_constraints.size());
  3079. }
  3080. for (auto constraint : import_facet_type_info.extend_named_constraints) {
  3081. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  3082. if (local_facet_type_info) {
  3083. local_facet_type_info->extend_named_constraints.push_back(
  3084. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  3085. }
  3086. }
  3087. if (local_facet_type_info) {
  3088. local_facet_type_info->self_impls_named_constraints.reserve(
  3089. import_facet_type_info.self_impls_named_constraints.size());
  3090. }
  3091. for (auto constraint : import_facet_type_info.self_impls_named_constraints) {
  3092. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  3093. if (local_facet_type_info) {
  3094. local_facet_type_info->self_impls_named_constraints.push_back(
  3095. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  3096. }
  3097. }
  3098. if (local_facet_type_info) {
  3099. local_facet_type_info->rewrite_constraints.reserve(
  3100. import_facet_type_info.rewrite_constraints.size());
  3101. }
  3102. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  3103. auto lhs_id = GetLocalConstantInstId(resolver, rewrite.lhs_id);
  3104. auto rhs_id = GetLocalConstantInstId(resolver, rewrite.rhs_id);
  3105. if (local_facet_type_info) {
  3106. local_facet_type_info->rewrite_constraints.push_back(
  3107. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  3108. }
  3109. }
  3110. }
  3111. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3112. SemIR::FacetType inst) -> ResolveResult {
  3113. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3114. const SemIR::FacetTypeInfo& import_facet_type_info =
  3115. resolver.import_facet_types().Get(inst.facet_type_id);
  3116. // Ensure values are imported, but discard them to avoid allocations.
  3117. ResolveFacetTypeInfo(resolver, import_facet_type_info,
  3118. /*local_facet_type_info=*/nullptr);
  3119. if (resolver.HasNewWork()) {
  3120. return ResolveResult::Retry();
  3121. }
  3122. SemIR::FacetTypeInfo local_facet_type_info = {
  3123. // TODO: Also process the other requirements.
  3124. .other_requirements = import_facet_type_info.other_requirements};
  3125. // Re-resolve and add values to the local `FacetTypeInfo`.
  3126. ResolveFacetTypeInfo(resolver, import_facet_type_info,
  3127. &local_facet_type_info);
  3128. SemIR::FacetTypeId facet_type_id =
  3129. resolver.local_facet_types().Add(std::move(local_facet_type_info));
  3130. return ResolveResult::Deduplicated<SemIR::FacetType>(
  3131. resolver,
  3132. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  3133. }
  3134. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3135. SemIR::FacetValue inst) -> ResolveResult {
  3136. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3137. auto type_inst_id = GetLocalTypeInstId(resolver, inst.type_inst_id);
  3138. auto witnesses = GetLocalInstBlockContents(resolver, inst.witnesses_block_id);
  3139. if (resolver.HasNewWork()) {
  3140. return ResolveResult::Retry();
  3141. }
  3142. auto witnesses_block_id = SemIR::InstBlockId::None;
  3143. if (inst.witnesses_block_id.has_value()) {
  3144. witnesses_block_id =
  3145. AddCanonicalWitnessesBlock(resolver.local_ir(), witnesses);
  3146. }
  3147. return ResolveResult::Deduplicated<SemIR::FacetValue>(
  3148. resolver,
  3149. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3150. .type_inst_id = type_inst_id,
  3151. .witnesses_block_id = witnesses_block_id});
  3152. }
  3153. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3154. SemIR::LookupImplWitness inst)
  3155. -> ResolveResult {
  3156. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3157. SemIR::WitnessType::TypeInstId);
  3158. auto query_self_inst_id =
  3159. GetLocalConstantInstId(resolver, inst.query_self_inst_id);
  3160. const auto& import_specific_interface =
  3161. resolver.import_specific_interfaces().Get(
  3162. inst.query_specific_interface_id);
  3163. auto data =
  3164. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  3165. if (resolver.HasNewWork()) {
  3166. return ResolveResult::Retry();
  3167. }
  3168. auto specific_interface =
  3169. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  3170. auto query_specific_interface_id =
  3171. resolver.local_specific_interfaces().Add(specific_interface);
  3172. return ResolveResult::Deduplicated<SemIR::LookupImplWitness>(
  3173. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3174. SemIR::WitnessType::TypeInstId),
  3175. .query_self_inst_id = query_self_inst_id,
  3176. .query_specific_interface_id = query_specific_interface_id});
  3177. }
  3178. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3179. SemIR::ImplWitness inst) -> ResolveResult {
  3180. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3181. SemIR::WitnessType::TypeInstId);
  3182. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3183. auto witness_table_id =
  3184. GetLocalConstantInstId(resolver, inst.witness_table_id);
  3185. if (resolver.HasNewWork()) {
  3186. return ResolveResult::Retry();
  3187. }
  3188. auto specific_id =
  3189. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3190. return ResolveResult::Deduplicated<SemIR::ImplWitness>(
  3191. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3192. SemIR::WitnessType::TypeInstId),
  3193. .witness_table_id = witness_table_id,
  3194. .specific_id = specific_id});
  3195. }
  3196. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3197. SemIR::ImplWitnessAccess inst)
  3198. -> ResolveResult {
  3199. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3200. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  3201. if (resolver.HasNewWork()) {
  3202. return ResolveResult::Retry();
  3203. }
  3204. return ResolveResult::Deduplicated<SemIR::ImplWitnessAccess>(
  3205. resolver,
  3206. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3207. .witness_id = witness_id,
  3208. .index = inst.index});
  3209. }
  3210. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3211. SemIR::ImplWitnessTable inst,
  3212. SemIR::InstId import_inst_id) -> ResolveResult {
  3213. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  3214. auto import_decl_inst_id = import_impl.first_decl_id();
  3215. auto local_decl_inst_id =
  3216. GetLocalConstantInstId(resolver, import_decl_inst_id);
  3217. if (resolver.HasNewWork()) {
  3218. return ResolveResult::Retry();
  3219. }
  3220. auto impl_decl =
  3221. resolver.local_insts().GetAs<SemIR::ImplDecl>(local_decl_inst_id);
  3222. auto impl_id = impl_decl.impl_id;
  3223. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  3224. // Create a corresponding instruction to represent the table.
  3225. return ResolveResult::Unique<SemIR::ImplWitnessTable>(
  3226. resolver, import_inst_id,
  3227. {.elements_id = elements_id, .impl_id = impl_id});
  3228. }
  3229. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3230. SemIR::InitForm inst) -> ResolveResult {
  3231. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3232. auto type_component_const_id =
  3233. GetLocalConstantId(resolver, inst.type_component_inst_id);
  3234. if (resolver.HasNewWork()) {
  3235. return ResolveResult::Retry();
  3236. }
  3237. return ResolveResult::Deduplicated<SemIR::InitForm>(
  3238. resolver,
  3239. SemIR::InitForm{
  3240. .type_id =
  3241. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3242. .type_component_inst_id = resolver.local_types().GetTypeInstId(
  3243. resolver.local_types().GetTypeIdForTypeConstantId(
  3244. type_component_const_id))});
  3245. }
  3246. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3247. SemIR::IntValue inst) -> ResolveResult {
  3248. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3249. if (resolver.HasNewWork()) {
  3250. return ResolveResult::Retry();
  3251. }
  3252. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  3253. // to add a new canonical int in this IR.
  3254. auto int_id = inst.int_id.is_embedded_value()
  3255. ? inst.int_id
  3256. : resolver.local_ints().AddSigned(
  3257. resolver.import_ints().Get(inst.int_id));
  3258. return ResolveResult::Deduplicated<SemIR::IntValue>(
  3259. resolver,
  3260. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3261. .int_id = int_id});
  3262. }
  3263. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3264. SemIR::IntType inst) -> ResolveResult {
  3265. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3266. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  3267. if (resolver.HasNewWork()) {
  3268. return ResolveResult::Retry();
  3269. }
  3270. return ResolveResult::Deduplicated<SemIR::IntType>(
  3271. resolver, {.type_id = SemIR::TypeType::TypeId,
  3272. .int_kind = inst.int_kind,
  3273. .bit_width_id = bit_width_id});
  3274. }
  3275. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3276. SemIR::Namespace inst,
  3277. SemIR::InstId import_inst_id) -> ResolveResult {
  3278. const auto& name_scope =
  3279. resolver.import_name_scopes().Get(inst.name_scope_id);
  3280. // A package from a different file becomes a child of the package here, as it
  3281. // would be if it were imported.
  3282. auto parent_scope_id =
  3283. inst.name_scope_id == SemIR::NameScopeId::Package
  3284. ? SemIR::NameScopeId::Package
  3285. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  3286. if (resolver.HasNewWork()) {
  3287. return ResolveResult::Retry();
  3288. }
  3289. auto namespace_type_id = GetSingletonType(resolver.local_context(),
  3290. SemIR::NamespaceType::TypeInstId);
  3291. auto namespace_decl =
  3292. SemIR::Namespace{.type_id = namespace_type_id,
  3293. .name_scope_id = SemIR::NameScopeId::None,
  3294. .import_id = SemIR::AbsoluteInstId::None};
  3295. auto inst_id =
  3296. AddPlaceholderImportedInst(resolver, import_inst_id, namespace_decl);
  3297. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  3298. namespace_decl.name_scope_id =
  3299. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  3300. // Namespaces from this package are eagerly imported, so anything we load here
  3301. // must be a closed import.
  3302. resolver.local_name_scopes()
  3303. .Get(namespace_decl.name_scope_id)
  3304. .set_is_closed_import(true);
  3305. auto namespace_const_id =
  3306. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  3307. return {.const_id = namespace_const_id};
  3308. }
  3309. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3310. SemIR::PatternType inst) -> ResolveResult {
  3311. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3312. auto scrutinee_type_inst_id =
  3313. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  3314. if (resolver.HasNewWork()) {
  3315. return ResolveResult::Retry();
  3316. }
  3317. return ResolveResult::Deduplicated<SemIR::PatternType>(
  3318. resolver, {.type_id = SemIR::TypeType::TypeId,
  3319. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  3320. }
  3321. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3322. SemIR::PointerType inst) -> ResolveResult {
  3323. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3324. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  3325. if (resolver.HasNewWork()) {
  3326. return ResolveResult::Retry();
  3327. }
  3328. return ResolveResult::Deduplicated<SemIR::PointerType>(
  3329. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  3330. }
  3331. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3332. SemIR::RefForm inst) -> ResolveResult {
  3333. auto type_component_inst_id =
  3334. GetLocalConstantId(resolver, inst.type_component_inst_id);
  3335. if (resolver.HasNewWork()) {
  3336. return ResolveResult::Retry();
  3337. }
  3338. return ResolveResult::Deduplicated<SemIR::RefForm>(
  3339. resolver, {.type_id = SemIR::TypeType::TypeId,
  3340. .type_component_inst_id = resolver.local_types().GetTypeInstId(
  3341. resolver.local_types().GetTypeIdForTypeConstantId(
  3342. type_component_inst_id))});
  3343. }
  3344. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3345. SemIR::RequireCompleteType inst)
  3346. -> ResolveResult {
  3347. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3348. SemIR::WitnessType::TypeInstId);
  3349. auto complete_type_inst_id =
  3350. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  3351. if (resolver.HasNewWork()) {
  3352. return ResolveResult::Retry();
  3353. }
  3354. return ResolveResult::Deduplicated<SemIR::RequireCompleteType>(
  3355. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3356. SemIR::WitnessType::TypeInstId),
  3357. .complete_type_inst_id = complete_type_inst_id});
  3358. }
  3359. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3360. SemIR::RequireSpecificDefinition inst)
  3361. -> ResolveResult {
  3362. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3363. SemIR::RequireSpecificDefinitionType::TypeInstId);
  3364. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3365. if (resolver.HasNewWork()) {
  3366. return ResolveResult::Retry();
  3367. }
  3368. auto specific_id =
  3369. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3370. return ResolveResult::Deduplicated<SemIR::RequireSpecificDefinition>(
  3371. resolver, {.type_id = GetSingletonType(
  3372. resolver.local_context(),
  3373. SemIR::RequireSpecificDefinitionType::TypeInstId),
  3374. .specific_id = specific_id});
  3375. }
  3376. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3377. SemIR::ReturnSlotPattern inst,
  3378. SemIR::InstId import_inst_id) -> ResolveResult {
  3379. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3380. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  3381. if (resolver.HasNewWork()) {
  3382. return ResolveResult::Retry();
  3383. }
  3384. return ResolveResult::Unique<SemIR::ReturnSlotPattern>(
  3385. resolver, import_inst_id,
  3386. {.type_id =
  3387. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3388. .subpattern_id = subpattern_id,
  3389. .type_inst_id = SemIR::TypeInstId::None});
  3390. }
  3391. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3392. SemIR::SpecificFunction inst) -> ResolveResult {
  3393. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3394. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3395. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3396. if (resolver.HasNewWork()) {
  3397. return ResolveResult::Retry();
  3398. }
  3399. auto type_id =
  3400. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id);
  3401. auto specific_id =
  3402. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3403. return ResolveResult::Deduplicated<SemIR::SpecificFunction>(
  3404. resolver,
  3405. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3406. }
  3407. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3408. SemIR::SpecificImplFunction inst)
  3409. -> ResolveResult {
  3410. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3411. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3412. if (resolver.HasNewWork()) {
  3413. return ResolveResult::Retry();
  3414. }
  3415. auto type_id = GetSingletonType(resolver.local_context(),
  3416. SemIR::SpecificFunctionType::TypeInstId);
  3417. auto specific_id =
  3418. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3419. return ResolveResult::Deduplicated<SemIR::SpecificImplFunction>(
  3420. resolver,
  3421. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3422. }
  3423. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3424. SemIR::StructAccess inst) -> ResolveResult {
  3425. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3426. auto struct_id = GetLocalConstantInstId(resolver, inst.struct_id);
  3427. if (resolver.HasNewWork()) {
  3428. return ResolveResult::Retry();
  3429. }
  3430. // A `struct_access` constant requires its struct operand to have a complete
  3431. // type.
  3432. CompleteTypeOrCheckFail(resolver.local_context(),
  3433. resolver.local_insts().Get(struct_id).type_id());
  3434. return ResolveResult::Deduplicated<SemIR::StructAccess>(
  3435. resolver,
  3436. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3437. .struct_id = struct_id,
  3438. .index = inst.index});
  3439. }
  3440. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3441. SemIR::StructType inst) -> ResolveResult {
  3442. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3443. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  3444. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  3445. field_type_inst_ids.reserve(orig_fields.size());
  3446. for (auto field : orig_fields) {
  3447. field_type_inst_ids.push_back(
  3448. GetLocalTypeInstId(resolver, field.type_inst_id));
  3449. }
  3450. if (resolver.HasNewWork()) {
  3451. return ResolveResult::Retry();
  3452. }
  3453. // Prepare a vector of fields for GetStructType.
  3454. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  3455. new_fields.reserve(orig_fields.size());
  3456. for (auto [orig_field, field_type_inst_id] :
  3457. llvm::zip_equal(orig_fields, field_type_inst_ids)) {
  3458. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  3459. new_fields.push_back(
  3460. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  3461. }
  3462. return ResolveResult::Deduplicated<SemIR::StructType>(
  3463. resolver, {.type_id = SemIR::TypeType::TypeId,
  3464. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  3465. new_fields)});
  3466. }
  3467. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3468. SemIR::StructValue inst) -> ResolveResult {
  3469. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3470. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3471. if (resolver.HasNewWork()) {
  3472. return ResolveResult::Retry();
  3473. }
  3474. return ResolveResult::Deduplicated<SemIR::StructValue>(
  3475. resolver,
  3476. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3477. .elements_id =
  3478. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3479. }
  3480. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3481. SemIR::SymbolicBindingType inst)
  3482. -> ResolveResult {
  3483. auto facet_value_inst_id =
  3484. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  3485. if (resolver.HasNewWork()) {
  3486. return ResolveResult::Retry();
  3487. }
  3488. auto entity_name_id =
  3489. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  3490. return ResolveResult::Deduplicated<SemIR::SymbolicBindingType>(
  3491. resolver, {.type_id = SemIR::TypeType::TypeId,
  3492. .entity_name_id = entity_name_id,
  3493. .facet_value_inst_id = facet_value_inst_id});
  3494. }
  3495. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3496. SemIR::Temporary inst) -> ResolveResult {
  3497. CARBON_CHECK(inst.storage_id == SemIR::InstId::None);
  3498. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3499. auto init_id = GetLocalConstantInstId(resolver, inst.init_id);
  3500. if (resolver.HasNewWork()) {
  3501. return ResolveResult::Retry();
  3502. }
  3503. return ResolveResult::Deduplicated<SemIR::Temporary>(
  3504. resolver,
  3505. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3506. .storage_id = SemIR::InstId::None,
  3507. .init_id = init_id});
  3508. }
  3509. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3510. SemIR::TupleAccess inst) -> ResolveResult {
  3511. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3512. auto tuple_id = GetLocalConstantInstId(resolver, inst.tuple_id);
  3513. if (resolver.HasNewWork()) {
  3514. return ResolveResult::Retry();
  3515. }
  3516. // A `tuple_access` constant requires its struct operand to have a complete
  3517. // type.
  3518. CompleteTypeOrCheckFail(resolver.local_context(),
  3519. resolver.local_insts().Get(tuple_id).type_id());
  3520. return ResolveResult::Deduplicated<SemIR::TupleAccess>(
  3521. resolver,
  3522. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3523. .tuple_id = tuple_id,
  3524. .index = inst.index});
  3525. }
  3526. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3527. SemIR::TuplePattern inst,
  3528. SemIR::InstId import_inst_id) -> ResolveResult {
  3529. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3530. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  3531. if (resolver.HasNewWork()) {
  3532. return ResolveResult::Retry();
  3533. }
  3534. return ResolveResult::Unique<SemIR::TuplePattern>(
  3535. resolver, import_inst_id,
  3536. {.type_id =
  3537. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3538. .elements_id =
  3539. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements)});
  3540. }
  3541. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3542. SemIR::TupleType inst) -> ResolveResult {
  3543. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3544. auto orig_type_inst_ids =
  3545. resolver.import_inst_blocks().Get(inst.type_elements_id);
  3546. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  3547. // type system that its holding `TypeInstId` elements.
  3548. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  3549. type_inst_ids.reserve(orig_type_inst_ids.size());
  3550. for (auto elem_type_inst_id :
  3551. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  3552. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  3553. }
  3554. if (resolver.HasNewWork()) {
  3555. return ResolveResult::Retry();
  3556. }
  3557. return ResolveResult::Deduplicated<SemIR::TupleType>(
  3558. resolver, {.type_id = SemIR::TypeType::TypeId,
  3559. .type_elements_id = GetLocalCanonicalInstBlockId(
  3560. resolver, inst.type_elements_id, type_inst_ids)});
  3561. }
  3562. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3563. SemIR::TupleValue inst) -> ResolveResult {
  3564. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3565. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3566. if (resolver.HasNewWork()) {
  3567. return ResolveResult::Retry();
  3568. }
  3569. return ResolveResult::Deduplicated<SemIR::TupleValue>(
  3570. resolver,
  3571. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3572. .elements_id =
  3573. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3574. }
  3575. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3576. SemIR::UnboundElementType inst)
  3577. -> ResolveResult {
  3578. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3579. auto class_const_inst_id =
  3580. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  3581. auto elem_const_inst_id =
  3582. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  3583. if (resolver.HasNewWork()) {
  3584. return ResolveResult::Retry();
  3585. }
  3586. return ResolveResult::Deduplicated<SemIR::UnboundElementType>(
  3587. resolver, {.type_id = SemIR::TypeType::TypeId,
  3588. .class_type_inst_id = class_const_inst_id,
  3589. .element_type_inst_id = elem_const_inst_id});
  3590. }
  3591. template <typename VarPatternT>
  3592. requires SemIR::Internal::HasInstCategory<SemIR::AnyVarPattern, VarPatternT>
  3593. static auto TryResolveTypedInst(ImportRefResolver& resolver, VarPatternT inst,
  3594. SemIR::InstId import_inst_id) -> ResolveResult {
  3595. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3596. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  3597. if (resolver.HasNewWork()) {
  3598. return ResolveResult::Retry();
  3599. }
  3600. return ResolveResult::Unique<VarPatternT>(
  3601. resolver, import_inst_id,
  3602. {.type_id =
  3603. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3604. .subpattern_id = subpattern_id});
  3605. }
  3606. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3607. SemIR::VarStorage inst,
  3608. SemIR::InstId import_inst_id) -> ResolveResult {
  3609. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3610. auto pattern_id = GetLocalConstantInstId(resolver, inst.pattern_id);
  3611. if (resolver.HasNewWork()) {
  3612. return ResolveResult::Retry();
  3613. }
  3614. return ResolveResult::Unique<SemIR::VarStorage>(
  3615. resolver, import_inst_id,
  3616. {.type_id =
  3617. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3618. .pattern_id = pattern_id});
  3619. }
  3620. // Tries to resolve the InstId, returning a canonical constant when ready, or
  3621. // `None` if more has been added to the stack. This is the same as
  3622. // TryResolveInst, except that it may resolve symbolic constants as canonical
  3623. // constants instead of as constants associated with a particular generic.
  3624. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  3625. SemIR::InstId inst_id,
  3626. SemIR::ConstantId const_id)
  3627. -> ResolveResult {
  3628. // These instruction types are imported across multiple phases to arrive at
  3629. // their constant value. We can't just import their constant value instruction
  3630. // directly.
  3631. auto untyped_inst = resolver.import_insts().GetWithAttachedType(inst_id);
  3632. CARBON_KIND_SWITCH(untyped_inst) {
  3633. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  3634. return TryResolveTypedInst(resolver, inst, const_id);
  3635. }
  3636. case CARBON_KIND(SemIR::ClassDecl inst): {
  3637. return TryResolveTypedInst(resolver, inst, const_id);
  3638. }
  3639. case CARBON_KIND(SemIR::FunctionDecl inst): {
  3640. return TryResolveTypedInst(resolver, inst, const_id);
  3641. }
  3642. case CARBON_KIND(SemIR::ImplDecl inst): {
  3643. return TryResolveTypedInst(resolver, inst, const_id);
  3644. }
  3645. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  3646. return TryResolveTypedInst(resolver, inst, const_id);
  3647. }
  3648. case CARBON_KIND(SemIR::InterfaceWithSelfDecl inst): {
  3649. return TryResolveTypedInst(resolver, inst, const_id);
  3650. }
  3651. case CARBON_KIND(SemIR::NamedConstraintDecl inst): {
  3652. return TryResolveTypedInst(resolver, inst, const_id);
  3653. }
  3654. case CARBON_KIND(SemIR::NamedConstraintWithSelfDecl inst): {
  3655. return TryResolveTypedInst(resolver, inst, const_id);
  3656. }
  3657. case CARBON_KIND(SemIR::RequireImplsDecl inst): {
  3658. return TryResolveTypedInst(resolver, inst, const_id);
  3659. }
  3660. default:
  3661. break;
  3662. }
  3663. // Other instructions are imported in a single phase (once their dependencies
  3664. // are all imported).
  3665. CARBON_CHECK(!const_id.has_value());
  3666. auto inst_constant_id = resolver.import_constant_values().Get(inst_id);
  3667. if (!inst_constant_id.is_constant()) {
  3668. // TODO: Import of non-constant BindNames happens when importing `let`
  3669. // declarations.
  3670. CARBON_CHECK(resolver.import_insts().Is<SemIR::AnyBinding>(inst_id),
  3671. "TryResolveInst on non-constant instruction {0}", inst_id);
  3672. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  3673. }
  3674. // Import the canonical constant value instruction for `inst_id` directly. We
  3675. // don't try to import the non-canonical `inst_id`.
  3676. auto constant_inst_id =
  3677. resolver.import_constant_values().GetInstId(inst_constant_id);
  3678. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  3679. constant_inst_id) == constant_inst_id,
  3680. "Constant value of constant instruction should refer to "
  3681. "the same instruction");
  3682. if (SemIR::IsSingletonInstId(constant_inst_id)) {
  3683. // Constants for builtins can be directly copied.
  3684. return ResolveResult::Done(
  3685. resolver.local_constant_values().Get(constant_inst_id));
  3686. }
  3687. auto untyped_constant_inst =
  3688. resolver.import_insts().GetWithAttachedType(constant_inst_id);
  3689. CARBON_KIND_SWITCH(untyped_constant_inst) {
  3690. case CARBON_KIND(SemIR::AdaptDecl inst): {
  3691. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3692. }
  3693. case CARBON_KIND(SemIR::ArrayType inst): {
  3694. return TryResolveTypedInst(resolver, inst);
  3695. }
  3696. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  3697. return TryResolveTypedInst(resolver, inst);
  3698. }
  3699. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  3700. return TryResolveTypedInst(resolver, inst);
  3701. }
  3702. case CARBON_KIND(SemIR::BaseDecl inst): {
  3703. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3704. }
  3705. case CARBON_KIND(SemIR::AliasBinding inst): {
  3706. return TryResolveTypedInst(resolver, inst);
  3707. }
  3708. case CARBON_KIND(SemIR::SymbolicBinding inst): {
  3709. return TryResolveTypedInst(resolver, inst);
  3710. }
  3711. case CARBON_KIND(SemIR::BoolLiteral inst): {
  3712. return TryResolveTypedInst(resolver, inst);
  3713. }
  3714. case CARBON_KIND(SemIR::BoundMethod inst): {
  3715. return TryResolveTypedInst(resolver, inst);
  3716. }
  3717. case CARBON_KIND(SemIR::Call inst): {
  3718. return TryResolveTypedInst(resolver, inst);
  3719. }
  3720. case CARBON_KIND(SemIR::CharLiteralValue inst): {
  3721. return TryResolveTypedInst(resolver, inst);
  3722. }
  3723. case CARBON_KIND(SemIR::ClassType inst): {
  3724. return TryResolveTypedInst(resolver, inst);
  3725. }
  3726. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  3727. return TryResolveTypedInst(resolver, inst);
  3728. }
  3729. case CARBON_KIND(SemIR::ConstType inst): {
  3730. return TryResolveTypedInst(resolver, inst);
  3731. }
  3732. case CARBON_KIND(SemIR::CppOverloadSetType inst): {
  3733. return TryResolveTypedInst(resolver, inst);
  3734. }
  3735. case CARBON_KIND(SemIR::CppOverloadSetValue inst): {
  3736. return TryResolveTypedInst(resolver, inst);
  3737. }
  3738. case CARBON_KIND(SemIR::CustomWitness inst): {
  3739. return TryResolveTypedInst(resolver, inst);
  3740. }
  3741. case CARBON_KIND(SemIR::ExportDecl inst): {
  3742. return TryResolveTypedInst(resolver, inst);
  3743. }
  3744. case CARBON_KIND(SemIR::FacetAccessType inst): {
  3745. return TryResolveTypedInst(resolver, inst);
  3746. }
  3747. case CARBON_KIND(SemIR::FacetType inst): {
  3748. return TryResolveTypedInst(resolver, inst);
  3749. }
  3750. case CARBON_KIND(SemIR::FacetValue inst): {
  3751. return TryResolveTypedInst(resolver, inst);
  3752. }
  3753. case CARBON_KIND(SemIR::FieldDecl inst): {
  3754. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3755. }
  3756. case CARBON_KIND(SemIR::FloatLiteralValue inst): {
  3757. return TryResolveTypedInst(resolver, inst);
  3758. }
  3759. case CARBON_KIND(SemIR::FloatType inst): {
  3760. return TryResolveTypedInst(resolver, inst);
  3761. }
  3762. case CARBON_KIND(SemIR::FloatValue inst): {
  3763. return TryResolveTypedInst(resolver, inst);
  3764. }
  3765. case CARBON_KIND(SemIR::FunctionType inst): {
  3766. return TryResolveTypedInst(resolver, inst);
  3767. }
  3768. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  3769. return TryResolveTypedInst(resolver, inst);
  3770. }
  3771. case CARBON_KIND(SemIR::GenericClassType inst): {
  3772. return TryResolveTypedInst(resolver, inst);
  3773. }
  3774. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  3775. return TryResolveTypedInst(resolver, inst);
  3776. }
  3777. case CARBON_KIND(SemIR::GenericNamedConstraintType inst): {
  3778. return TryResolveTypedInst(resolver, inst);
  3779. }
  3780. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  3781. return TryResolveTypedInst(resolver, inst);
  3782. }
  3783. case CARBON_KIND(SemIR::ImplWitness inst): {
  3784. return TryResolveTypedInst(resolver, inst);
  3785. }
  3786. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  3787. return TryResolveTypedInst(resolver, inst);
  3788. }
  3789. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  3790. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3791. }
  3792. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  3793. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3794. }
  3795. case CARBON_KIND(SemIR::InitForm inst): {
  3796. return TryResolveTypedInst(resolver, inst);
  3797. }
  3798. case CARBON_KIND(SemIR::IntValue inst): {
  3799. return TryResolveTypedInst(resolver, inst);
  3800. }
  3801. case CARBON_KIND(SemIR::IntType inst): {
  3802. return TryResolveTypedInst(resolver, inst);
  3803. }
  3804. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  3805. return TryResolveTypedInst(resolver, inst);
  3806. }
  3807. case CARBON_KIND(SemIR::Namespace inst): {
  3808. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3809. }
  3810. case CARBON_KIND(SemIR::OutParamPattern inst): {
  3811. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3812. }
  3813. case CARBON_KIND(SemIR::PartialType inst): {
  3814. return TryResolveTypedInst(resolver, inst);
  3815. }
  3816. case CARBON_KIND(SemIR::PatternType inst): {
  3817. return TryResolveTypedInst(resolver, inst);
  3818. }
  3819. case CARBON_KIND(SemIR::PointerType inst): {
  3820. return TryResolveTypedInst(resolver, inst);
  3821. }
  3822. case CARBON_KIND(SemIR::RefBindingPattern inst): {
  3823. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3824. }
  3825. case CARBON_KIND(SemIR::RefForm inst): {
  3826. return TryResolveTypedInst(resolver, inst);
  3827. }
  3828. case CARBON_KIND(SemIR::RefParamPattern inst): {
  3829. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3830. }
  3831. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  3832. return TryResolveTypedInst(resolver, inst);
  3833. }
  3834. case CARBON_KIND(SemIR::RequireSpecificDefinition inst): {
  3835. return TryResolveTypedInst(resolver, inst);
  3836. }
  3837. case CARBON_KIND(SemIR::ReturnSlotPattern inst): {
  3838. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3839. }
  3840. case CARBON_KIND(SemIR::SpecificFunction inst): {
  3841. return TryResolveTypedInst(resolver, inst);
  3842. }
  3843. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  3844. return TryResolveTypedInst(resolver, inst);
  3845. }
  3846. case CARBON_KIND(SemIR::StructAccess inst): {
  3847. return TryResolveTypedInst(resolver, inst);
  3848. }
  3849. case CARBON_KIND(SemIR::StructType inst): {
  3850. return TryResolveTypedInst(resolver, inst);
  3851. }
  3852. case CARBON_KIND(SemIR::StructValue inst): {
  3853. return TryResolveTypedInst(resolver, inst);
  3854. }
  3855. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  3856. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3857. }
  3858. case CARBON_KIND(SemIR::SymbolicBindingType inst): {
  3859. return TryResolveTypedInst(resolver, inst);
  3860. }
  3861. case CARBON_KIND(SemIR::Temporary inst): {
  3862. return TryResolveTypedInst(resolver, inst);
  3863. }
  3864. case CARBON_KIND(SemIR::TupleAccess inst): {
  3865. return TryResolveTypedInst(resolver, inst);
  3866. }
  3867. case CARBON_KIND(SemIR::TuplePattern inst): {
  3868. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3869. }
  3870. case CARBON_KIND(SemIR::TupleType inst): {
  3871. return TryResolveTypedInst(resolver, inst);
  3872. }
  3873. case CARBON_KIND(SemIR::TupleValue inst): {
  3874. return TryResolveTypedInst(resolver, inst);
  3875. }
  3876. case CARBON_KIND(SemIR::UnboundElementType inst): {
  3877. return TryResolveTypedInst(resolver, inst);
  3878. }
  3879. case CARBON_KIND(SemIR::ValueBindingPattern inst): {
  3880. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3881. }
  3882. case CARBON_KIND(SemIR::ValueParamPattern inst): {
  3883. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3884. }
  3885. case CARBON_KIND(SemIR::VarParamPattern inst): {
  3886. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3887. }
  3888. case CARBON_KIND(SemIR::VarPattern inst): {
  3889. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3890. }
  3891. case CARBON_KIND(SemIR::VarStorage inst): {
  3892. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3893. }
  3894. case CARBON_KIND(SemIR::VtableDecl inst): {
  3895. return TryResolveTypedInst(resolver, inst);
  3896. }
  3897. case CARBON_KIND(SemIR::VtablePtr inst): {
  3898. return TryResolveTypedInst(resolver, inst);
  3899. }
  3900. case CARBON_KIND(SemIR::WrapperBindingPattern inst): {
  3901. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3902. }
  3903. default:
  3904. // Found a canonical instruction which needs to be resolved, but which is
  3905. // not yet handled.
  3906. //
  3907. // TODO: Could we turn this into a compile-time error?
  3908. CARBON_FATAL(
  3909. "Missing case in TryResolveInstCanonical for instruction kind {0}",
  3910. untyped_constant_inst.kind());
  3911. }
  3912. }
  3913. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  3914. // more has been added to the stack. A similar API is followed for all
  3915. // following TryResolveTypedInst helper functions.
  3916. //
  3917. // `const_id` is `None` unless we've tried to resolve this instruction
  3918. // before, in which case it's the previous result.
  3919. //
  3920. // TODO: Error is returned when support is missing, but that should go away.
  3921. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  3922. SemIR::ConstantId const_id) -> ResolveResult {
  3923. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  3924. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  3925. return TryResolveInstCanonical(resolver, inst_id, const_id);
  3926. }
  3927. // Try to import the generic. This might add new work.
  3928. const auto& symbolic_const =
  3929. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  3930. auto generic_const_id =
  3931. GetLocalConstantId(resolver, symbolic_const.generic_id);
  3932. auto inner_const_id = SemIR::ConstantId::None;
  3933. if (const_id.has_value()) {
  3934. // For the third phase, extract the constant value that
  3935. // TryResolveInstCanonical produced previously.
  3936. inner_const_id = resolver.local_constant_values().GetAttached(
  3937. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  3938. }
  3939. // Import the constant and rebuild the symbolic constant data.
  3940. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  3941. if (!result.const_id.has_value()) {
  3942. // First phase: TryResolveInstCanoncial needs a retry.
  3943. return result;
  3944. }
  3945. if (!const_id.has_value()) {
  3946. // Second phase: we have created an unattached constant. Create a
  3947. // corresponding attached constant.
  3948. if (symbolic_const.generic_id.has_value()) {
  3949. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  3950. {.inst_id =
  3951. resolver.local_constant_values().GetInstId(result.const_id),
  3952. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  3953. .index = symbolic_const.index,
  3954. .dependence = symbolic_const.dependence});
  3955. if (result.decl_id.has_value()) {
  3956. // Overwrite the unattached symbolic constant given initially to the
  3957. // declaration with its final attached symbolic value.
  3958. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  3959. }
  3960. }
  3961. } else {
  3962. // Third phase: perform a consistency check and produce the constant we
  3963. // created in the second phase.
  3964. CARBON_CHECK(result.const_id == inner_const_id,
  3965. "Constant value changed in third phase.");
  3966. result.const_id = const_id;
  3967. }
  3968. return result;
  3969. }
  3970. auto ImportRefResolver::Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  3971. work_stack_.push_back(InstWork{.inst_id = inst_id});
  3972. while (!work_stack_.empty()) {
  3973. auto work_variant = work_stack_.back();
  3974. CARBON_KIND_SWITCH(work_variant) {
  3975. case CARBON_KIND(InstWork work): {
  3976. CARBON_CHECK(work.inst_id.has_value());
  3977. // Step 1: check for a constant value.
  3978. auto existing = FindResolvedConstId(work.inst_id);
  3979. if (existing.const_id.has_value() && !work.retry_with_constant_value) {
  3980. work_stack_.pop_back();
  3981. continue;
  3982. }
  3983. // Step 2: resolve the instruction.
  3984. initial_work_ = work_stack_.size();
  3985. auto result = TryResolveInst(*this, work.inst_id, existing.const_id);
  3986. CARBON_CHECK(!HasNewWork() || result.retry);
  3987. CARBON_CHECK(!existing.const_id.has_value() ||
  3988. existing.const_id == result.const_id,
  3989. "Constant value changed in third phase.");
  3990. if (!existing.const_id.has_value()) {
  3991. SetResolvedConstId(work.inst_id, existing.indirect_insts,
  3992. result.const_id);
  3993. }
  3994. // Step 3: pop or retry.
  3995. if (result.retry) {
  3996. std::get<InstWork>(work_stack_[initial_work_ - 1])
  3997. .retry_with_constant_value = result.const_id.has_value();
  3998. } else {
  3999. work_stack_.pop_back();
  4000. for (const auto& resolve : result.resolve_generic) {
  4001. if (resolve.import_generic_id.has_value()) {
  4002. work_stack_.push_back(
  4003. GenericWork{.import_id = resolve.import_generic_id,
  4004. .local_id = resolve.local_generic_id});
  4005. }
  4006. }
  4007. }
  4008. break;
  4009. }
  4010. case CARBON_KIND(GenericWork generic_work): {
  4011. // Generics may require 2 steps to finish, similar to step 2 and step 3
  4012. // of instructions.
  4013. initial_work_ = work_stack_.size();
  4014. if (TryFinishGeneric(*this, generic_work.import_id,
  4015. generic_work.local_id)) {
  4016. work_stack_.pop_back();
  4017. }
  4018. break;
  4019. }
  4020. case CARBON_KIND(SpecificWork specific_work): {
  4021. // Specifics may require 2 steps to finish, similar to step 2 and step 3
  4022. // of instructions.
  4023. initial_work_ = work_stack_.size();
  4024. if (TryFinishSpecific(*this, specific_work.import_id,
  4025. specific_work.local_id)) {
  4026. work_stack_.pop_back();
  4027. }
  4028. break;
  4029. }
  4030. }
  4031. }
  4032. auto constant_id =
  4033. local_constant_values_for_import_insts().GetAttached(inst_id);
  4034. CARBON_CHECK(constant_id.has_value());
  4035. return constant_id;
  4036. }
  4037. auto ImportRefResolver::ResolveConstant(SemIR::ConstantId import_const_id)
  4038. -> SemIR::ConstantId {
  4039. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  4040. }
  4041. auto ImportRefResolver::ResolveType(SemIR::TypeId import_type_id)
  4042. -> SemIR::TypeId {
  4043. if (!import_type_id.has_value()) {
  4044. return import_type_id;
  4045. }
  4046. auto import_type_const_id = import_ir().types().GetConstantId(import_type_id);
  4047. CARBON_CHECK(import_type_const_id.has_value());
  4048. if (auto import_type_inst_id = import_ir().types().GetAsTypeInstId(
  4049. import_ir().constant_values().GetInstId(import_type_const_id));
  4050. SemIR::IsSingletonInstId(import_type_inst_id)) {
  4051. // Builtins don't require constant resolution; we can use them directly.
  4052. return GetSingletonType(local_context(), import_type_inst_id);
  4053. } else {
  4054. return local_types().GetTypeIdForTypeConstantId(
  4055. ResolveConstant(import_type_id.AsConstantId()));
  4056. }
  4057. }
  4058. auto ImportRefResolver::HasNewWork() -> bool {
  4059. CARBON_CHECK(initial_work_ <= work_stack_.size(), "Work shouldn't decrease");
  4060. return initial_work_ < work_stack_.size();
  4061. }
  4062. auto ImportRefResolver::PushSpecific(SemIR::SpecificId import_id,
  4063. SemIR::SpecificId local_id) -> void {
  4064. // Insert before the current instruction.
  4065. work_stack_.insert(
  4066. work_stack_.begin() + initial_work_ - 1,
  4067. SpecificWork{.import_id = import_id, .local_id = local_id});
  4068. ++initial_work_;
  4069. }
  4070. auto ImportRefResolver::GetLocalConstantValueOrPush(SemIR::InstId inst_id)
  4071. -> SemIR::ConstantId {
  4072. if (!inst_id.has_value()) {
  4073. return SemIR::ConstantId::None;
  4074. }
  4075. auto const_id = local_constant_values_for_import_insts().GetAttached(inst_id);
  4076. if (!const_id.has_value()) {
  4077. work_stack_.push_back(InstWork{.inst_id = inst_id});
  4078. }
  4079. return const_id;
  4080. }
  4081. auto ImportRefResolver::FindResolvedConstId(SemIR::InstId inst_id)
  4082. -> ResolvedConstId {
  4083. ResolvedConstId result;
  4084. if (auto existing_const_id =
  4085. local_constant_values_for_import_insts().GetAttached(inst_id);
  4086. existing_const_id.has_value()) {
  4087. result.const_id = existing_const_id;
  4088. return result;
  4089. }
  4090. const auto* cursor_ir = &import_ir();
  4091. auto cursor_inst_id = inst_id;
  4092. while (true) {
  4093. auto import_ir_inst_id = cursor_ir->insts().GetImportSource(cursor_inst_id);
  4094. if (!import_ir_inst_id.has_value()) {
  4095. return result;
  4096. }
  4097. auto ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
  4098. if (ir_inst.ir_id() == SemIR::ImportIRId::Cpp) {
  4099. local_context().TODO(SemIR::LocId::None,
  4100. "Unsupported: Importing C++ indirectly");
  4101. SetResolvedConstId(inst_id, result.indirect_insts,
  4102. SemIR::ErrorInst::ConstantId);
  4103. result.const_id = SemIR::ErrorInst::ConstantId;
  4104. result.indirect_insts.clear();
  4105. return result;
  4106. }
  4107. const auto* prev_ir = cursor_ir;
  4108. auto prev_inst_id = cursor_inst_id;
  4109. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id()).sem_ir;
  4110. auto cursor_ir_id =
  4111. AddImportIR(local_context(), {.decl_id = SemIR::InstId::None,
  4112. .is_export = false,
  4113. .sem_ir = cursor_ir});
  4114. cursor_inst_id = ir_inst.inst_id();
  4115. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id, "{0}",
  4116. cursor_ir->insts().Get(cursor_inst_id));
  4117. if (auto const_id =
  4118. local_context()
  4119. .import_ir_constant_values()
  4120. [local_ir().import_irs().GetRawIndex(cursor_ir_id)]
  4121. .GetAttached(cursor_inst_id);
  4122. const_id.has_value()) {
  4123. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  4124. result.const_id = const_id;
  4125. result.indirect_insts.clear();
  4126. return result;
  4127. } else {
  4128. result.indirect_insts.push_back(
  4129. SemIR::ImportIRInst(cursor_ir_id, cursor_inst_id));
  4130. }
  4131. }
  4132. }
  4133. auto ImportRefResolver::SetResolvedConstId(
  4134. SemIR::InstId inst_id, llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  4135. SemIR::ConstantId const_id) -> void {
  4136. local_constant_values_for_import_insts().Set(inst_id, const_id);
  4137. SetIndirectConstantValues(local_context(), indirect_insts, const_id);
  4138. }
  4139. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  4140. // loaded (including the one pointed at directly by the ImportRef), and the
  4141. // final instruction's type ID.
  4142. //
  4143. // This addresses cases where an ImportRefUnloaded may point at another
  4144. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  4145. // constant-evaluated version of the instruction to work with.
  4146. static auto GetInstForLoad(Context& context,
  4147. SemIR::ImportIRInstId import_ir_inst_id)
  4148. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  4149. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  4150. {}, SemIR::TypeId::None};
  4151. auto& [import_ir_insts, type_id] = result;
  4152. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  4153. // The first ImportIRInst is added directly because the IR doesn't need to be
  4154. // localized.
  4155. import_ir_insts.push_back(import_ir_inst);
  4156. const auto* cursor_ir =
  4157. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  4158. while (true) {
  4159. auto cursor_inst =
  4160. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  4161. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  4162. if (!import_ref) {
  4163. type_id = cursor_inst.type_id();
  4164. return result;
  4165. }
  4166. import_ir_inst =
  4167. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  4168. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  4169. import_ir_insts.push_back(SemIR::ImportIRInst(
  4170. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  4171. .is_export = false,
  4172. .sem_ir = cursor_ir}),
  4173. import_ir_inst.inst_id()));
  4174. }
  4175. }
  4176. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  4177. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  4178. if (!inst) {
  4179. return;
  4180. }
  4181. auto [indirect_insts, load_type_id] =
  4182. GetInstForLoad(context, inst->import_ir_inst_id);
  4183. // The last indirect instruction is the one to resolve. Pop it here because
  4184. // Resolve will assign the constant.
  4185. auto load_ir_inst = indirect_insts.pop_back_val();
  4186. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  4187. // Loading an import ref creates local constants from the import ones, but
  4188. // shouldn't be generating novel instructions in the semir as a side effect of
  4189. // that process. Doing so in a generic context would also cause them to end up
  4190. // in the eval block, which would be doubly wrong.
  4191. context.inst_block_stack().Push();
  4192. auto type_id = resolver.ResolveType(load_type_id);
  4193. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  4194. CARBON_CHECK(
  4195. context.inst_block_stack().PeekCurrentBlockContents().empty(),
  4196. "Importing an instruction shouldn't add new instructions to the "
  4197. "local inst block. Found {0} new instructions, first is {1}: {2}.",
  4198. context.inst_block_stack().PeekCurrentBlockContents().size(),
  4199. context.inst_block_stack().PeekCurrentBlockContents().front(),
  4200. context.insts().Get(
  4201. context.inst_block_stack().PeekCurrentBlockContents().front()));
  4202. context.inst_block_stack().PopAndDiscard();
  4203. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  4204. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  4205. // TryEvalInst, which we want to avoid with ImportRefs.
  4206. context.sem_ir().insts().Set(
  4207. inst_id,
  4208. SemIR::ImportRefLoaded{.type_id = type_id,
  4209. .import_ir_inst_id = inst->import_ir_inst_id,
  4210. .entity_name_id = inst->entity_name_id});
  4211. // Store the constant for both the ImportRefLoaded and indirect instructions.
  4212. context.constant_values().Set(inst_id, constant_id);
  4213. SetIndirectConstantValues(context, indirect_insts, constant_id);
  4214. }
  4215. auto ImportImplsFromApiFile(Context& context) -> void {
  4216. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  4217. auto& import_ir = context.import_irs().Get(import_ir_id);
  4218. if (!import_ir.sem_ir) {
  4219. return;
  4220. }
  4221. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  4222. // Resolve the imported impl to a local impl ID.
  4223. ImportImpl(context, import_ir_id, impl_id);
  4224. }
  4225. }
  4226. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  4227. SemIR::ImplId impl_id) -> void {
  4228. ImportRefResolver resolver(&context, import_ir_id);
  4229. resolver.Resolve(resolver.import_impls().Get(impl_id).first_decl_id());
  4230. }
  4231. auto ImportInterface(Context& context, SemIR::ImportIRId import_ir_id,
  4232. SemIR::InterfaceId interface_id) -> SemIR::InterfaceId {
  4233. ImportRefResolver resolver(&context, import_ir_id);
  4234. auto local_id = resolver.Resolve(
  4235. resolver.import_interfaces().Get(interface_id).first_decl_id());
  4236. auto local_inst =
  4237. context.insts().Get(context.constant_values().GetInstId(local_id));
  4238. // A non-generic interface will import as a facet type for that single
  4239. // interface.
  4240. if (auto facet_type = local_inst.TryAs<SemIR::FacetType>()) {
  4241. auto single = context.facet_types()
  4242. .Get(facet_type->facet_type_id)
  4243. .TryAsSingleExtend();
  4244. CARBON_CHECK(single,
  4245. "Importing an interface didn't produce a single interface");
  4246. return std::get<SemIR::SpecificInterface>(*single).interface_id;
  4247. }
  4248. // A generic interface will import as a constant of generic interface type.
  4249. auto generic_interface_type =
  4250. context.types().GetAs<SemIR::GenericInterfaceType>(local_inst.type_id());
  4251. return generic_interface_type.interface_id;
  4252. }
  4253. } // namespace Carbon::Check