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