import_ref.cpp 198 KB

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