import_ref.cpp 197 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754
  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. static auto TryResolveTypedInst(ImportRefResolver& resolver, ParamPatternT inst,
  1433. SemIR::InstId import_inst_id) -> ResolveResult {
  1434. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1435. auto name_id = GetLocalNameId(resolver, inst.pretty_name_id);
  1436. if (resolver.HasNewWork()) {
  1437. return ResolveResult::Retry();
  1438. }
  1439. return ResolveResult::Unique<ParamPatternT>(
  1440. resolver, import_inst_id,
  1441. {.type_id =
  1442. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1443. .pretty_name_id = name_id});
  1444. }
  1445. template <typename ReturnPatternT>
  1446. requires SemIR::Internal::HasInstCategory<SemIR::AnyReturnPattern,
  1447. ReturnPatternT>
  1448. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1449. ReturnPatternT inst,
  1450. SemIR::InstId import_inst_id) -> ResolveResult {
  1451. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1452. if (resolver.HasNewWork()) {
  1453. return ResolveResult::Retry();
  1454. }
  1455. return ResolveResult::Unique<ReturnPatternT>(
  1456. resolver, import_inst_id,
  1457. {.type_id =
  1458. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id)});
  1459. }
  1460. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1461. SemIR::ArrayType inst) -> ResolveResult {
  1462. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1463. auto element_type_inst_id =
  1464. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  1465. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1466. if (resolver.HasNewWork()) {
  1467. return ResolveResult::Retry();
  1468. }
  1469. return ResolveResult::Deduplicated<SemIR::ArrayType>(
  1470. resolver, {.type_id = SemIR::TypeType::TypeId,
  1471. .bound_id = bound_id,
  1472. .element_type_inst_id = element_type_inst_id});
  1473. }
  1474. static auto ImportAssociatedConstant(
  1475. ImportContext& context, const SemIR::AssociatedConstant& import_assoc_const,
  1476. SemIR::TypeId type_id)
  1477. -> std::pair<SemIR::AssociatedConstantId, SemIR::ConstantId> {
  1478. SemIR::AssociatedConstantDecl assoc_const_decl = {
  1479. .type_id = type_id,
  1480. .assoc_const_id = SemIR::AssociatedConstantId::None,
  1481. .decl_block_id = SemIR::InstBlockId::Empty};
  1482. auto assoc_const_decl_id = AddPlaceholderImportedInst(
  1483. context, import_assoc_const.decl_id, assoc_const_decl);
  1484. assoc_const_decl.assoc_const_id = context.local_associated_constants().Add({
  1485. .name_id = GetLocalNameId(context, import_assoc_const.name_id),
  1486. .parent_scope_id = SemIR::NameScopeId::None,
  1487. .decl_id = assoc_const_decl_id,
  1488. .default_value_id =
  1489. import_assoc_const.default_value_id.has_value()
  1490. ? AddImportRef(context, import_assoc_const.default_value_id)
  1491. : SemIR::InstId::None,
  1492. });
  1493. // Write the associated constant ID into the AssociatedConstantDecl.
  1494. auto const_id = ReplacePlaceholderImportedInst(context, assoc_const_decl_id,
  1495. assoc_const_decl);
  1496. return {assoc_const_decl.assoc_const_id, const_id};
  1497. }
  1498. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1499. SemIR::AssociatedConstantDecl inst,
  1500. SemIR::ConstantId const_id) -> ResolveResult {
  1501. const auto& import_assoc_const =
  1502. resolver.import_associated_constants().Get(inst.assoc_const_id);
  1503. SemIR::AssociatedConstantId assoc_const_id =
  1504. SemIR::AssociatedConstantId::None;
  1505. if (!const_id.has_value()) {
  1506. // In the first phase, import the type of the associated constant.
  1507. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1508. if (resolver.HasNewWork()) {
  1509. return ResolveResult::Retry();
  1510. }
  1511. // In the second phase, create the associated constant and its declaration.
  1512. auto type_id =
  1513. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id);
  1514. std::tie(assoc_const_id, const_id) =
  1515. ImportAssociatedConstant(resolver, import_assoc_const, type_id);
  1516. } else {
  1517. // In the third phase, compute the associated constant ID from the constant
  1518. // value of the declaration.
  1519. assoc_const_id = resolver.local_constant_values()
  1520. .GetInstAs<SemIR::AssociatedConstantDecl>(const_id)
  1521. .assoc_const_id;
  1522. }
  1523. // Load the values to populate the entity with.
  1524. auto parent_scope_id =
  1525. GetLocalNameScopeId(resolver, import_assoc_const.parent_scope_id);
  1526. auto& new_assoc_const =
  1527. resolver.local_associated_constants().Get(assoc_const_id);
  1528. if (resolver.HasNewWork()) {
  1529. return ResolveResult::Retry(const_id, new_assoc_const.decl_id);
  1530. }
  1531. // Populate the entity.
  1532. new_assoc_const.parent_scope_id = parent_scope_id;
  1533. return ResolveResult::Done(const_id, new_assoc_const.decl_id);
  1534. }
  1535. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1536. SemIR::AssociatedEntity inst) -> ResolveResult {
  1537. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1538. if (resolver.HasNewWork()) {
  1539. return ResolveResult::Retry();
  1540. }
  1541. // Add a lazy reference to the target declaration.
  1542. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1543. return ResolveResult::Deduplicated<SemIR::AssociatedEntity>(
  1544. resolver, {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(
  1545. type_const_id),
  1546. .index = inst.index,
  1547. .decl_id = decl_id});
  1548. }
  1549. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1550. SemIR::AssociatedEntityType inst)
  1551. -> ResolveResult {
  1552. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1553. auto data =
  1554. GetLocalSpecificInterfaceData(resolver, inst.GetSpecificInterface());
  1555. if (resolver.HasNewWork()) {
  1556. return ResolveResult::Retry();
  1557. }
  1558. auto specific_interface =
  1559. GetLocalSpecificInterface(resolver, inst.GetSpecificInterface(), data);
  1560. return ResolveResult::Deduplicated<SemIR::AssociatedEntityType>(
  1561. resolver,
  1562. {.type_id = SemIR::TypeType::TypeId,
  1563. .interface_id = specific_interface.interface_id,
  1564. .interface_without_self_specific_id = specific_interface.specific_id});
  1565. }
  1566. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1567. SemIR::BaseDecl inst,
  1568. SemIR::InstId import_inst_id) -> ResolveResult {
  1569. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1570. auto base_type_const_id =
  1571. GetLocalConstantId(resolver, inst.base_type_inst_id);
  1572. if (resolver.HasNewWork()) {
  1573. return ResolveResult::Retry();
  1574. }
  1575. auto base_type_inst_id = AddLoadedImportRefForType(
  1576. resolver, inst.base_type_inst_id, base_type_const_id);
  1577. // Create a corresponding instruction to represent the declaration.
  1578. return ResolveResult::Unique<SemIR::BaseDecl>(
  1579. resolver, import_inst_id,
  1580. {.type_id =
  1581. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1582. .base_type_inst_id = base_type_inst_id,
  1583. .index = inst.index});
  1584. }
  1585. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1586. SemIR::AliasBinding inst) -> ResolveResult {
  1587. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1588. return ResolveResult::RetryOrDone(resolver, value_id);
  1589. }
  1590. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1591. SemIR::SymbolicBinding inst) -> ResolveResult {
  1592. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1593. if (resolver.HasNewWork()) {
  1594. return ResolveResult::Retry();
  1595. }
  1596. auto entity_name_id =
  1597. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  1598. return ResolveResult::Deduplicated<SemIR::SymbolicBinding>(
  1599. resolver,
  1600. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  1601. .entity_name_id = entity_name_id,
  1602. .value_id = SemIR::InstId::None});
  1603. }
  1604. template <typename BindingPatternT>
  1605. requires SemIR::Internal::HasInstCategory<SemIR::AnyBindingPattern,
  1606. BindingPatternT>
  1607. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1608. BindingPatternT inst,
  1609. SemIR::InstId import_inst_id) -> ResolveResult {
  1610. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1611. const auto& import_entity_name =
  1612. resolver.import_entity_names().Get(inst.entity_name_id);
  1613. auto parent_scope_id =
  1614. GetLocalNameScopeId(resolver, import_entity_name.parent_scope_id);
  1615. auto subpattern_id = SemIR::InstId::None;
  1616. if constexpr (std::is_same_v<BindingPatternT, SemIR::WrapperBindingPattern>) {
  1617. subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  1618. }
  1619. if (resolver.HasNewWork()) {
  1620. return ResolveResult::Retry();
  1621. }
  1622. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1623. auto entity_name_id = resolver.local_entity_names().Add(
  1624. {.name_id = name_id,
  1625. .parent_scope_id = parent_scope_id,
  1626. .bind_index_value = import_entity_name.bind_index().index,
  1627. .is_template = import_entity_name.is_template});
  1628. // We use AnyBindingPattern here so that we can initialize it uniformly,
  1629. // regardless of whether BindingPatternT has a subpattern_id field.
  1630. SemIR::AnyBindingPattern result = {
  1631. .kind = BindingPatternT::Kind,
  1632. .type_id =
  1633. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  1634. .entity_name_id = entity_name_id,
  1635. .subpattern_id = subpattern_id};
  1636. return ResolveResult::Unique<BindingPatternT>(
  1637. resolver, import_inst_id, SemIR::Inst(result).As<BindingPatternT>());
  1638. }
  1639. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1640. SemIR::BoolLiteral inst) -> ResolveResult {
  1641. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1642. SemIR::BoolType::TypeInstId);
  1643. CARBON_CHECK(!resolver.HasNewWork());
  1644. return ResolveResult::Deduplicated<SemIR::BoolLiteral>(
  1645. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1646. SemIR::BoolType::TypeInstId),
  1647. .value = inst.value});
  1648. }
  1649. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1650. SemIR::BoundMethod inst) -> ResolveResult {
  1651. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1652. SemIR::BoundMethodType::TypeInstId);
  1653. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1654. auto function_decl_id =
  1655. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1656. if (resolver.HasNewWork()) {
  1657. return ResolveResult::Retry();
  1658. }
  1659. return ResolveResult::Deduplicated<SemIR::BoundMethod>(
  1660. resolver,
  1661. {.type_id = GetSingletonType(resolver.local_context(),
  1662. SemIR::BoundMethodType::TypeInstId),
  1663. .object_id = object_id,
  1664. .function_decl_id = function_decl_id});
  1665. }
  1666. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1667. -> ResolveResult {
  1668. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1669. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1670. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1671. if (resolver.HasNewWork()) {
  1672. return ResolveResult::Retry();
  1673. }
  1674. return ResolveResult::Deduplicated<SemIR::Call>(
  1675. resolver,
  1676. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  1677. .callee_id = callee_id,
  1678. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1679. }
  1680. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1681. SemIR::CharLiteralValue inst) -> ResolveResult {
  1682. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1683. SemIR::CharLiteralType::TypeInstId);
  1684. CARBON_CHECK(!resolver.HasNewWork());
  1685. return ResolveResult::Deduplicated<SemIR::CharLiteralValue>(
  1686. resolver,
  1687. {.type_id = GetSingletonType(resolver.local_context(),
  1688. SemIR::CharLiteralType::TypeInstId),
  1689. .value = inst.value});
  1690. }
  1691. static auto AddPlaceholderNameScope(ImportContext& context)
  1692. -> SemIR::NameScopeId {
  1693. return context.local_name_scopes().Add(
  1694. SemIR::InstId::None, SemIR::NameId::None, SemIR::NameScopeId::None);
  1695. }
  1696. // Makes an incomplete class. This is necessary even with classes with a
  1697. // complete declaration, because things such as `Self` may refer back to the
  1698. // type.
  1699. static auto ImportIncompleteClass(ImportContext& context,
  1700. const SemIR::Class& import_class,
  1701. SemIR::SpecificId enclosing_specific_id)
  1702. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1703. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::TypeId,
  1704. .class_id = SemIR::ClassId::None,
  1705. .decl_block_id = SemIR::InstBlockId::Empty};
  1706. auto class_decl_id = AddPlaceholderImportedInst(
  1707. context, import_class.latest_decl_id(), class_decl);
  1708. // Regardless of whether ClassDecl is a complete type, we first need an
  1709. // incomplete type so that any references have something to point at.
  1710. class_decl.class_id = context.local_classes().Add(
  1711. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1712. {.self_type_id = SemIR::TypeId::None,
  1713. .inheritance_kind = import_class.inheritance_kind,
  1714. .is_dynamic = import_class.is_dynamic,
  1715. .scope_id = import_class.is_complete()
  1716. ? AddPlaceholderNameScope(context)
  1717. : SemIR::NameScopeId::None}});
  1718. if (import_class.has_parameters()) {
  1719. class_decl.type_id = GetGenericClassType(
  1720. context.local_context(), class_decl.class_id, enclosing_specific_id);
  1721. }
  1722. // Write the class ID into the ClassDecl.
  1723. auto self_const_id =
  1724. ReplacePlaceholderImportedInst(context, class_decl_id, class_decl);
  1725. return {class_decl.class_id, self_const_id};
  1726. }
  1727. static auto InitializeNameScopeAndImportRefs(
  1728. ImportContext& context, const SemIR::NameScope& import_scope,
  1729. SemIR::NameScope& new_scope, SemIR::InstId decl_id, SemIR::NameId name_id,
  1730. SemIR::NameScopeId parent_scope_id) {
  1731. new_scope.Set(decl_id, name_id, parent_scope_id);
  1732. AddNameScopeImportRefs(context, import_scope, new_scope);
  1733. }
  1734. // Fills out the class definition for an incomplete class.
  1735. static auto ImportClassDefinition(ImportContext& context,
  1736. const SemIR::Class& import_class,
  1737. SemIR::Class& new_class,
  1738. SemIR::InstId complete_type_witness_id,
  1739. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1740. SemIR::InstId vtable_decl_id) -> void {
  1741. new_class.definition_id = new_class.first_owning_decl_id;
  1742. new_class.complete_type_witness_id = complete_type_witness_id;
  1743. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1744. const auto& import_scope =
  1745. context.import_name_scopes().Get(import_class.scope_id);
  1746. // Push a block so that we can add scoped instructions to it.
  1747. context.local_context().inst_block_stack().Push();
  1748. InitializeNameScopeAndImportRefs(
  1749. context, import_scope, new_scope, new_class.first_owning_decl_id,
  1750. SemIR::NameId::None, new_class.parent_scope_id);
  1751. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1752. if (import_class.base_id.has_value()) {
  1753. new_class.base_id = base_id;
  1754. }
  1755. if (import_class.adapt_id.has_value()) {
  1756. new_class.adapt_id = adapt_id;
  1757. }
  1758. if (import_class.vtable_decl_id.has_value()) {
  1759. new_class.vtable_decl_id = vtable_decl_id;
  1760. }
  1761. }
  1762. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1763. SemIR::ClassDecl inst,
  1764. SemIR::ConstantId class_const_id)
  1765. -> ResolveResult {
  1766. // TODO: The handling of interfaces repeats a lot with the handling of
  1767. // classes, and will likely also be repeated for named constraints and
  1768. // choice types. Factor out some of this functionality.
  1769. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1770. SemIR::ClassId class_id = SemIR::ClassId::None;
  1771. if (!class_const_id.has_value()) {
  1772. auto import_specific_id = SemIR::SpecificId::None;
  1773. if (auto import_generic_class_type =
  1774. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1775. inst.type_id)) {
  1776. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1777. }
  1778. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1779. if (resolver.HasNewWork()) {
  1780. // This is the end of the first phase. Don't make a new class yet if
  1781. // we already have new work.
  1782. return ResolveResult::Retry();
  1783. }
  1784. // On the second phase, create a forward declaration of the class for any
  1785. // recursive references.
  1786. auto enclosing_specific_id =
  1787. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1788. std::tie(class_id, class_const_id) =
  1789. ImportIncompleteClass(resolver, import_class, enclosing_specific_id);
  1790. } else {
  1791. // On the third phase, compute the class ID from the constant
  1792. // value of the declaration.
  1793. auto class_const_inst = resolver.local_insts().Get(
  1794. resolver.local_constant_values().GetInstId(class_const_id));
  1795. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1796. class_id = class_type->class_id;
  1797. } else {
  1798. auto generic_class_type =
  1799. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1800. class_const_inst.type_id());
  1801. class_id = generic_class_type.class_id;
  1802. }
  1803. }
  1804. // Load constants for the definition.
  1805. auto parent_scope_id =
  1806. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1807. auto implicit_param_patterns = GetLocalInstBlockContents(
  1808. resolver, import_class.implicit_param_patterns_id);
  1809. auto param_patterns =
  1810. GetLocalInstBlockContents(resolver, import_class.param_patterns_id);
  1811. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1812. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1813. auto complete_type_witness_const_id =
  1814. import_class.complete_type_witness_id.has_value()
  1815. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1816. : SemIR::ConstantId::None;
  1817. auto base_id = import_class.base_id.has_value()
  1818. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1819. : SemIR::InstId::None;
  1820. auto adapt_id = import_class.adapt_id.has_value()
  1821. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1822. : SemIR::InstId::None;
  1823. auto vtable_decl_id =
  1824. import_class.vtable_decl_id.has_value()
  1825. ? AddImportRef(resolver, import_class.vtable_decl_id)
  1826. : SemIR::InstId::None;
  1827. auto& new_class = resolver.local_classes().Get(class_id);
  1828. if (resolver.HasNewWork()) {
  1829. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1830. }
  1831. new_class.parent_scope_id = parent_scope_id;
  1832. new_class.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1833. resolver, import_class.implicit_param_patterns_id,
  1834. implicit_param_patterns);
  1835. new_class.param_patterns_id = GetLocalCanonicalInstBlockId(
  1836. resolver, import_class.param_patterns_id, param_patterns);
  1837. new_class.self_type_id =
  1838. resolver.local_types().GetTypeIdForTypeConstantId(self_const_id);
  1839. if (import_class.is_complete()) {
  1840. auto complete_type_witness_id = AddLoadedImportRef(
  1841. resolver,
  1842. GetSingletonType(resolver.local_context(),
  1843. SemIR::WitnessType::TypeInstId),
  1844. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1845. ImportClassDefinition(resolver, import_class, new_class,
  1846. complete_type_witness_id, base_id, adapt_id,
  1847. vtable_decl_id);
  1848. }
  1849. return ResolveResult::FinishGenericOrDone(
  1850. resolver, class_const_id, new_class.first_decl_id(),
  1851. import_class.generic_id, new_class.generic_id, generic_data);
  1852. }
  1853. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1854. SemIR::ClassType inst) -> ResolveResult {
  1855. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1856. auto class_const_id = GetLocalConstantId(
  1857. resolver,
  1858. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1859. if (class_const_id == SemIR::ErrorInst::ConstantId) {
  1860. // TODO: It should be possible to remove this once C++ imports work.
  1861. return ResolveResult::Done(class_const_id);
  1862. }
  1863. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1864. if (resolver.HasNewWork()) {
  1865. return ResolveResult::Retry();
  1866. }
  1867. // Find the corresponding class type. For a non-generic class, this is the
  1868. // type of the class declaration. For a generic class, build a class type
  1869. // referencing this specialization of the generic class.
  1870. auto class_const_inst = resolver.local_insts().Get(
  1871. resolver.local_constant_values().GetInstId(class_const_id));
  1872. if (class_const_inst.Is<SemIR::ClassType>()) {
  1873. return ResolveResult::Done(class_const_id);
  1874. } else {
  1875. auto generic_class_type =
  1876. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1877. class_const_inst.type_id());
  1878. auto specific_id =
  1879. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1880. return ResolveResult::Deduplicated<SemIR::ClassType>(
  1881. resolver, {.type_id = SemIR::TypeType::TypeId,
  1882. .class_id = generic_class_type.class_id,
  1883. .specific_id = specific_id});
  1884. }
  1885. }
  1886. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1887. SemIR::CompleteTypeWitness inst)
  1888. -> ResolveResult {
  1889. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1890. SemIR::WitnessType::TypeInstId);
  1891. auto object_repr_type_inst_id =
  1892. GetLocalTypeInstId(resolver, inst.object_repr_type_inst_id);
  1893. if (resolver.HasNewWork()) {
  1894. return ResolveResult::Retry();
  1895. }
  1896. return ResolveResult::Deduplicated<SemIR::CompleteTypeWitness>(
  1897. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1898. SemIR::WitnessType::TypeInstId),
  1899. .object_repr_type_inst_id = object_repr_type_inst_id});
  1900. }
  1901. template <typename InstT>
  1902. requires SemIR::Internal::HasInstCategory<SemIR::AnyQualifiedType, InstT>
  1903. static auto TryResolveTypedInst(ImportRefResolver& resolver, InstT inst)
  1904. -> ResolveResult {
  1905. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1906. auto inner_id = GetLocalTypeInstId(resolver, inst.inner_id);
  1907. if (resolver.HasNewWork()) {
  1908. return ResolveResult::Retry();
  1909. }
  1910. return ResolveResult::Deduplicated<InstT>(
  1911. resolver, {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_id});
  1912. }
  1913. static auto HandleUnsupportedCppOverloadSet(ImportRefResolver& resolver,
  1914. SemIR::CppOverloadSetId id) {
  1915. // Supporting C++ overload resolution of imported functions is a large task,
  1916. // which might require serializing and deserializing AST for using decl ids,
  1917. // using modules and/or linking ASTs.
  1918. resolver.local_context().TODO(
  1919. SemIR::LocId::None,
  1920. llvm::formatv(
  1921. "Unsupported: Importing C++ function `{0}` indirectly",
  1922. resolver.import_ir().names().GetAsStringIfIdentifier(
  1923. resolver.import_ir().cpp_overload_sets().Get(id).name_id)));
  1924. return ResolveResult::Done(SemIR::ErrorInst::ConstantId,
  1925. SemIR::ErrorInst::InstId);
  1926. }
  1927. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1928. SemIR::CppOverloadSetType inst)
  1929. -> ResolveResult {
  1930. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1931. }
  1932. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1933. SemIR::CppOverloadSetValue inst)
  1934. -> ResolveResult {
  1935. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1936. }
  1937. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1938. SemIR::CustomWitness inst) -> ResolveResult {
  1939. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1940. SemIR::WitnessType::TypeInstId);
  1941. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  1942. const auto& import_specific_interface =
  1943. resolver.import_specific_interfaces().Get(
  1944. inst.query_specific_interface_id);
  1945. auto data =
  1946. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  1947. if (resolver.HasNewWork()) {
  1948. return ResolveResult::Retry();
  1949. }
  1950. auto elements_id =
  1951. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements);
  1952. auto specific_interface =
  1953. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  1954. auto query_specific_interface_id =
  1955. resolver.local_specific_interfaces().Add(specific_interface);
  1956. return ResolveResult::Deduplicated<SemIR::CustomWitness>(
  1957. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1958. SemIR::WitnessType::TypeInstId),
  1959. .elements_id = elements_id,
  1960. .query_specific_interface_id = query_specific_interface_id});
  1961. }
  1962. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1963. SemIR::ExportDecl inst) -> ResolveResult {
  1964. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1965. return ResolveResult::RetryOrDone(resolver, value_id);
  1966. }
  1967. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1968. SemIR::FieldDecl inst,
  1969. SemIR::InstId import_inst_id) -> ResolveResult {
  1970. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1971. if (resolver.HasNewWork()) {
  1972. return ResolveResult::Retry();
  1973. }
  1974. return ResolveResult::Unique<SemIR::FieldDecl>(
  1975. resolver, import_inst_id,
  1976. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(const_id),
  1977. .name_id = GetLocalNameId(resolver, inst.name_id),
  1978. .index = inst.index});
  1979. }
  1980. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1981. SemIR::FloatLiteralValue inst)
  1982. -> ResolveResult {
  1983. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  1984. SemIR::FloatLiteralType::TypeInstId);
  1985. CARBON_CHECK(!resolver.HasNewWork());
  1986. auto real_id = resolver.local_ir().reals().Add(
  1987. resolver.import_ir().reals().Get(inst.real_id));
  1988. return ResolveResult::Deduplicated<SemIR::FloatLiteralValue>(
  1989. resolver,
  1990. {.type_id = GetSingletonType(resolver.local_context(),
  1991. SemIR::FloatLiteralType::TypeInstId),
  1992. .real_id = real_id});
  1993. }
  1994. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1995. SemIR::FloatType inst) -> ResolveResult {
  1996. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1997. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  1998. if (resolver.HasNewWork()) {
  1999. return ResolveResult::Retry();
  2000. }
  2001. return ResolveResult::Deduplicated<SemIR::FloatType>(
  2002. resolver, {.type_id = SemIR::TypeType::TypeId,
  2003. .bit_width_id = bit_width_id,
  2004. .float_kind = inst.float_kind});
  2005. }
  2006. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2007. SemIR::FloatValue inst) -> ResolveResult {
  2008. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2009. if (resolver.HasNewWork()) {
  2010. return ResolveResult::Retry();
  2011. }
  2012. auto float_id = resolver.local_ir().floats().Add(
  2013. resolver.import_ir().floats().Get(inst.float_id));
  2014. return ResolveResult::Deduplicated<SemIR::FloatValue>(
  2015. resolver,
  2016. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  2017. .float_id = float_id});
  2018. }
  2019. // Make a declaration of a function. This is done as a separate step from
  2020. // importing the function declaration in order to resolve cycles.
  2021. static auto ImportFunctionDecl(ImportContext& context,
  2022. const SemIR::Function& import_function,
  2023. SemIR::SpecificId specific_id)
  2024. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  2025. SemIR::FunctionDecl function_decl = {
  2026. .type_id = SemIR::TypeId::None,
  2027. .function_id = SemIR::FunctionId::None,
  2028. .decl_block_id = SemIR::InstBlockId::Empty};
  2029. auto function_decl_id = AddPlaceholderImportedInst(
  2030. context, import_function.first_decl_id(), function_decl);
  2031. // Start with an incomplete function.
  2032. function_decl.function_id = context.local_functions().Add(
  2033. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  2034. {.call_param_patterns_id = SemIR::InstBlockId::None,
  2035. .call_params_id = SemIR::InstBlockId::None,
  2036. .call_param_ranges = import_function.call_param_ranges,
  2037. .return_type_inst_id = SemIR::TypeInstId::None,
  2038. .return_form_inst_id = SemIR::InstId::None,
  2039. .return_pattern_id = SemIR::InstId::None,
  2040. .virtual_modifier = import_function.virtual_modifier,
  2041. .virtual_index = import_function.virtual_index,
  2042. .evaluation_mode = import_function.evaluation_mode}});
  2043. // Directly add the function type constant. Don't use `GetFunctionType`
  2044. // because that will evaluate the function type, which we can't do if the
  2045. // specific's value block is still pending.
  2046. auto type_const_id = AddImportedConstant(
  2047. context.local_context(),
  2048. SemIR::FunctionType{.type_id = SemIR::TypeType::TypeId,
  2049. .function_id = function_decl.function_id,
  2050. .specific_id = specific_id});
  2051. function_decl.type_id =
  2052. context.local_types().GetTypeIdForTypeConstantId(type_const_id);
  2053. // Write the function ID and type into the FunctionDecl.
  2054. auto function_const_id =
  2055. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  2056. return {function_decl.function_id, function_const_id};
  2057. }
  2058. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2059. SemIR::FunctionDecl inst,
  2060. SemIR::ConstantId function_const_id)
  2061. -> ResolveResult {
  2062. const auto& import_function =
  2063. resolver.import_functions().Get(inst.function_id);
  2064. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  2065. if (!function_const_id.has_value()) {
  2066. auto import_specific_id = resolver.import_types()
  2067. .GetAs<SemIR::FunctionType>(inst.type_id)
  2068. .specific_id;
  2069. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2070. if (resolver.HasNewWork()) {
  2071. // This is the end of the first phase. Don't make a new function yet if
  2072. // we already have new work.
  2073. return ResolveResult::Retry();
  2074. }
  2075. // On the second phase, create a forward declaration of the function.
  2076. auto specific_id =
  2077. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2078. std::tie(function_id, function_const_id) =
  2079. ImportFunctionDecl(resolver, import_function, specific_id);
  2080. } else {
  2081. // On the third phase, compute the function ID from the constant value of
  2082. // the declaration.
  2083. auto function_const_inst = resolver.local_insts().Get(
  2084. resolver.local_constant_values().GetInstId(function_const_id));
  2085. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  2086. function_const_inst.type_id());
  2087. function_id = function_type.function_id;
  2088. }
  2089. auto call_param_patterns = GetLocalInstBlockContents(
  2090. resolver, import_function.call_param_patterns_id);
  2091. auto return_type_const_id = SemIR::ConstantId::None;
  2092. if (import_function.return_type_inst_id.has_value()) {
  2093. return_type_const_id =
  2094. GetLocalConstantId(resolver, import_function.return_type_inst_id);
  2095. }
  2096. auto return_form_const_id = SemIR::ConstantId::None;
  2097. if (import_function.return_form_inst_id.has_value()) {
  2098. return_form_const_id =
  2099. GetLocalConstantId(resolver, import_function.return_form_inst_id);
  2100. }
  2101. auto parent_scope_id =
  2102. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  2103. auto implicit_param_patterns = GetLocalInstBlockContents(
  2104. resolver, import_function.implicit_param_patterns_id);
  2105. auto param_patterns =
  2106. GetLocalInstBlockContents(resolver, import_function.param_patterns_id);
  2107. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  2108. auto self_param_id =
  2109. GetLocalConstantInstId(resolver, import_function.self_param_id);
  2110. auto return_pattern_id =
  2111. GetLocalConstantInstId(resolver, import_function.return_pattern_id);
  2112. auto& new_function = resolver.local_functions().Get(function_id);
  2113. if (resolver.HasNewWork()) {
  2114. return ResolveResult::Retry(function_const_id,
  2115. new_function.first_decl_id());
  2116. }
  2117. // Add the function declaration.
  2118. new_function.call_param_patterns_id = GetLocalCanonicalInstBlockId(
  2119. resolver, import_function.call_param_patterns_id, call_param_patterns);
  2120. new_function.parent_scope_id = parent_scope_id;
  2121. new_function.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2122. resolver, import_function.implicit_param_patterns_id,
  2123. implicit_param_patterns);
  2124. new_function.self_param_id = self_param_id;
  2125. new_function.param_patterns_id = GetLocalCanonicalInstBlockId(
  2126. resolver, import_function.param_patterns_id, param_patterns);
  2127. new_function.return_type_inst_id = SemIR::TypeInstId::None;
  2128. if (import_function.return_type_inst_id.has_value()) {
  2129. new_function.return_type_inst_id = AddLoadedImportRefForType(
  2130. resolver, import_function.return_type_inst_id, return_type_const_id);
  2131. }
  2132. new_function.return_form_inst_id = SemIR::InstId::None;
  2133. if (import_function.return_form_inst_id.has_value()) {
  2134. new_function.return_form_inst_id = AddLoadedImportRef(
  2135. resolver, SemIR::FormType::TypeId, import_function.return_form_inst_id,
  2136. return_form_const_id);
  2137. }
  2138. new_function.return_pattern_id = return_pattern_id;
  2139. if (import_function.definition_id.has_value()) {
  2140. new_function.definition_id = new_function.first_owning_decl_id;
  2141. }
  2142. switch (import_function.special_function_kind) {
  2143. case SemIR::Function::SpecialFunctionKind::CppThunk:
  2144. case SemIR::Function::SpecialFunctionKind::None: {
  2145. break;
  2146. }
  2147. case SemIR::Function::SpecialFunctionKind::Builtin: {
  2148. new_function.SetBuiltinFunction(import_function.builtin_function_kind());
  2149. break;
  2150. }
  2151. case SemIR::Function::SpecialFunctionKind::CoreWitness: {
  2152. new_function.SetCoreWitness(import_function.builtin_function_kind());
  2153. break;
  2154. }
  2155. case SemIR::Function::SpecialFunctionKind::Thunk: {
  2156. auto entity_name_id = resolver.local_entity_names().AddCanonical(
  2157. {.name_id = new_function.name_id,
  2158. .parent_scope_id = new_function.parent_scope_id});
  2159. new_function.SetThunk(AddImportRef(
  2160. resolver, import_function.thunk_decl_id(), entity_name_id));
  2161. break;
  2162. }
  2163. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  2164. resolver.local_context().TODO(SemIR::LocId::None,
  2165. "Unsupported: Importing C++ functions that "
  2166. "require thunks indirectly");
  2167. }
  2168. }
  2169. return ResolveResult::FinishGenericOrDone(
  2170. resolver, function_const_id, new_function.first_decl_id(),
  2171. import_function.generic_id, new_function.generic_id, generic_data);
  2172. }
  2173. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2174. SemIR::VtableDecl inst) -> ResolveResult {
  2175. const auto& import_vtable = resolver.import_vtables().Get(inst.vtable_id);
  2176. auto class_const_id =
  2177. GetLocalConstantId(resolver, resolver.import_classes()
  2178. .Get(import_vtable.class_id)
  2179. .first_owning_decl_id);
  2180. auto class_const_inst = resolver.local_insts().Get(
  2181. resolver.local_constant_values().GetInstId(class_const_id));
  2182. // TODO: Ensure the vtable is only imported once, in eg: if there's distinct
  2183. // vtable constants (imported from multiple libraries using the vtable) that
  2184. // refer to the same vtable, the vtable should still be singular.
  2185. auto virtual_functions =
  2186. resolver.import_inst_blocks().Get(import_vtable.virtual_functions_id);
  2187. llvm::SmallVector<SemIR::InstId> lazy_virtual_functions;
  2188. lazy_virtual_functions.reserve(virtual_functions.size());
  2189. for (auto vtable_entry_id : virtual_functions) {
  2190. auto local_attached_constant_id =
  2191. GetLocalConstantId(resolver, vtable_entry_id);
  2192. lazy_virtual_functions.push_back(
  2193. resolver.local_constant_values().GetInstIdIfValid(
  2194. local_attached_constant_id));
  2195. }
  2196. if (resolver.HasNewWork()) {
  2197. return ResolveResult::Retry();
  2198. }
  2199. for (auto [import_vtable_entry_inst_id, local_vtable_entry_inst_id] :
  2200. llvm::zip_equal(virtual_functions, lazy_virtual_functions)) {
  2201. // Use LoadedImportRef for imported symbolic constant vtable entries so they
  2202. // can carry attached constants necessary for applying specifics to these
  2203. // constants when they are used.
  2204. auto local_attached_constant_id =
  2205. resolver.local_constant_values().GetAttached(
  2206. local_vtable_entry_inst_id);
  2207. if (local_attached_constant_id.is_symbolic()) {
  2208. local_vtable_entry_inst_id = AddLoadedImportRef(
  2209. resolver,
  2210. GetSingletonType(resolver.local_context(),
  2211. SemIR::SpecificFunctionType::TypeInstId),
  2212. import_vtable_entry_inst_id, local_attached_constant_id);
  2213. }
  2214. }
  2215. auto class_id = SemIR::ClassId::None;
  2216. if (class_const_inst.Is<SemIR::ClassType>()) {
  2217. class_id = class_const_inst.As<SemIR::ClassType>().class_id;
  2218. } else {
  2219. auto generic_class_type =
  2220. resolver.local_types().GetAs<SemIR::GenericClassType>(
  2221. class_const_inst.type_id());
  2222. class_id = generic_class_type.class_id;
  2223. }
  2224. auto new_vtable_id = resolver.local_vtables().Add(
  2225. {{.class_id = class_id,
  2226. .virtual_functions_id =
  2227. resolver.local_inst_blocks().Add(lazy_virtual_functions)}});
  2228. return ResolveResult::Deduplicated<SemIR::VtableDecl>(
  2229. resolver, {.type_id = GetPointerType(resolver.local_context(),
  2230. SemIR::VtableType::TypeInstId),
  2231. .vtable_id = new_vtable_id});
  2232. }
  2233. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2234. SemIR::VtablePtr inst) -> ResolveResult {
  2235. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2236. auto vtable_const_id = GetLocalConstantId(
  2237. resolver, resolver.import_classes()
  2238. .Get(resolver.import_vtables().Get(inst.vtable_id).class_id)
  2239. .vtable_decl_id);
  2240. if (resolver.HasNewWork()) {
  2241. return ResolveResult::Retry();
  2242. }
  2243. auto vtable_const_inst = resolver.local_insts().Get(
  2244. resolver.local_constant_values().GetInstId(vtable_const_id));
  2245. return ResolveResult::Deduplicated<SemIR::VtablePtr>(
  2246. resolver,
  2247. {.type_id = GetPointerType(resolver.local_context(),
  2248. SemIR::VtableType::TypeInstId),
  2249. .vtable_id = vtable_const_inst.As<SemIR::VtableDecl>().vtable_id,
  2250. .specific_id =
  2251. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data)});
  2252. }
  2253. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2254. SemIR::FunctionType inst) -> ResolveResult {
  2255. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2256. auto fn_val_id = GetLocalConstantInstId(
  2257. resolver,
  2258. resolver.import_functions().Get(inst.function_id).first_decl_id());
  2259. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2260. if (resolver.HasNewWork()) {
  2261. return ResolveResult::Retry();
  2262. }
  2263. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  2264. return ResolveResult::Deduplicated<SemIR::FunctionType>(
  2265. resolver, {.type_id = SemIR::TypeType::TypeId,
  2266. .function_id = resolver.local_types()
  2267. .GetAs<SemIR::FunctionType>(fn_type_id)
  2268. .function_id,
  2269. .specific_id = GetOrAddLocalSpecific(
  2270. resolver, inst.specific_id, specific_data)});
  2271. }
  2272. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2273. SemIR::FunctionTypeWithSelfType inst)
  2274. -> ResolveResult {
  2275. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2276. auto interface_function_type_id =
  2277. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  2278. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  2279. if (resolver.HasNewWork()) {
  2280. return ResolveResult::Retry();
  2281. }
  2282. return ResolveResult::Deduplicated<SemIR::FunctionTypeWithSelfType>(
  2283. resolver, {.type_id = SemIR::TypeType::TypeId,
  2284. .interface_function_type_id = interface_function_type_id,
  2285. .self_id = self_id});
  2286. }
  2287. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2288. SemIR::GenericClassType inst) -> ResolveResult {
  2289. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2290. auto class_val_id = GetLocalConstantInstId(
  2291. resolver,
  2292. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  2293. if (resolver.HasNewWork()) {
  2294. return ResolveResult::Retry();
  2295. }
  2296. auto class_val = resolver.local_insts().Get(class_val_id);
  2297. CARBON_CHECK(
  2298. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  2299. return ResolveResult::Done(
  2300. resolver.local_types().GetConstantId(class_val.type_id()));
  2301. }
  2302. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2303. SemIR::GenericInterfaceType inst)
  2304. -> ResolveResult {
  2305. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2306. auto interface_val_id = GetLocalConstantInstId(
  2307. resolver,
  2308. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2309. if (resolver.HasNewWork()) {
  2310. return ResolveResult::Retry();
  2311. }
  2312. auto interface_val = resolver.local_insts().Get(interface_val_id);
  2313. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  2314. interface_val.type_id()));
  2315. return ResolveResult::Done(
  2316. resolver.local_types().GetConstantId(interface_val.type_id()));
  2317. }
  2318. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2319. SemIR::GenericNamedConstraintType inst)
  2320. -> ResolveResult {
  2321. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2322. auto constraint_val_id =
  2323. GetLocalConstantInstId(resolver, resolver.import_named_constraints()
  2324. .Get(inst.named_constraint_id)
  2325. .first_owning_decl_id);
  2326. if (resolver.HasNewWork()) {
  2327. return ResolveResult::Retry();
  2328. }
  2329. auto constraint_val = resolver.local_insts().Get(constraint_val_id);
  2330. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericNamedConstraintType>(
  2331. constraint_val.type_id()));
  2332. return ResolveResult::Done(
  2333. resolver.local_types().GetConstantId(constraint_val.type_id()));
  2334. }
  2335. // Make a declaration of an impl. This is done as a separate step from
  2336. // importing the impl definition in order to resolve cycles.
  2337. static auto ImportImplDecl(ImportContext& context,
  2338. const SemIR::Impl& import_impl,
  2339. SemIR::InstId witness_id)
  2340. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  2341. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  2342. .decl_block_id = SemIR::InstBlockId::Empty};
  2343. auto impl_decl_id = AddPlaceholderImportedInst(
  2344. context, import_impl.latest_decl_id(), impl_decl);
  2345. impl_decl.impl_id = context.local_impls().Add(
  2346. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  2347. {.self_id = SemIR::TypeInstId::None,
  2348. .constraint_id = SemIR::TypeInstId::None,
  2349. .interface = SemIR::SpecificInterface::None,
  2350. .witness_id = witness_id,
  2351. .scope_id = import_impl.is_complete() ? AddPlaceholderNameScope(context)
  2352. : SemIR::NameScopeId::None,
  2353. .is_final = import_impl.is_final}});
  2354. // Write the impl ID into the ImplDecl.
  2355. auto impl_const_id =
  2356. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  2357. return {impl_decl.impl_id, impl_const_id};
  2358. }
  2359. // Imports the definition of an impl.
  2360. static auto ImportImplDefinition(ImportContext& context,
  2361. const SemIR::Impl& import_impl,
  2362. SemIR::Impl& new_impl) -> void {
  2363. new_impl.definition_id = new_impl.first_owning_decl_id;
  2364. new_impl.defined = true;
  2365. if (import_impl.scope_id.has_value()) {
  2366. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  2367. new_scope.Set(new_impl.first_owning_decl_id, SemIR::NameId::None,
  2368. new_impl.parent_scope_id);
  2369. // Import the contents of the definition scope, if we might need it. Name
  2370. // lookup is never performed into this scope by a user of the impl, so
  2371. // this is only necessary in the same library that defined the impl, in
  2372. // order to support defining members of the impl out of line in the impl
  2373. // file when the impl is defined in the API file.
  2374. // TODO: Check to see if this impl is owned by the API file, rather than
  2375. // merely being imported into it.
  2376. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2377. const auto& import_scope =
  2378. context.import_name_scopes().Get(import_impl.scope_id);
  2379. // Push a block so that we can add scoped instructions to it.
  2380. context.local_context().inst_block_stack().Push();
  2381. AddNameScopeImportRefs(context, import_scope, new_scope);
  2382. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  2383. }
  2384. }
  2385. }
  2386. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2387. SemIR::ImplDecl inst,
  2388. SemIR::ConstantId impl_const_id)
  2389. -> ResolveResult {
  2390. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  2391. // functions. Factor out the commonality.
  2392. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2393. auto specific_interface_data =
  2394. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  2395. SemIR::ImplId impl_id = SemIR::ImplId::None;
  2396. if (!impl_const_id.has_value()) {
  2397. if (resolver.HasNewWork()) {
  2398. // This is the end of the first phase. Don't make a new impl yet if we
  2399. // already have new work.
  2400. return ResolveResult::Retry();
  2401. }
  2402. // On the second phase, create a forward declaration of the impl for any
  2403. // recursive references.
  2404. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  2405. std::tie(impl_id, impl_const_id) =
  2406. ImportImplDecl(resolver, import_impl, witness_id);
  2407. } else {
  2408. // On the third phase, compute the impl ID from the "constant value" of
  2409. // the declaration, which is a reference to the created ImplDecl.
  2410. auto impl_const_inst =
  2411. resolver.local_constant_values().GetInstAs<SemIR::ImplDecl>(
  2412. impl_const_id);
  2413. impl_id = impl_const_inst.impl_id;
  2414. }
  2415. // Load constants for the definition.
  2416. auto parent_scope_id =
  2417. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  2418. auto implicit_param_patterns = GetLocalInstBlockContents(
  2419. resolver, import_impl.implicit_param_patterns_id);
  2420. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  2421. auto self_const_id = GetLocalConstantId(resolver, import_impl.self_id);
  2422. auto constraint_const_id =
  2423. GetLocalConstantId(resolver, import_impl.constraint_id);
  2424. auto& new_impl = resolver.local_impls().Get(impl_id);
  2425. if (resolver.HasNewWork()) {
  2426. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2427. }
  2428. new_impl.parent_scope_id = parent_scope_id;
  2429. new_impl.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2430. resolver, import_impl.implicit_param_patterns_id,
  2431. implicit_param_patterns);
  2432. // Create instructions for self and constraint to hold the symbolic constant
  2433. // value for a generic impl.
  2434. new_impl.self_id =
  2435. AddLoadedImportRefForType(resolver, import_impl.self_id, self_const_id);
  2436. new_impl.constraint_id = AddLoadedImportRefForType(
  2437. resolver, import_impl.constraint_id, constraint_const_id);
  2438. new_impl.interface = GetLocalSpecificInterface(
  2439. resolver, import_impl.interface, specific_interface_data);
  2440. // Create a local IdentifiedFacetType for the imported facet type, since impl
  2441. // declarations always identify the facet type.
  2442. if (auto facet_type =
  2443. resolver.local_constant_values().TryGetInstAs<SemIR::FacetType>(
  2444. constraint_const_id)) {
  2445. // Lookups later will be with the unattached constant, whereas
  2446. // GetLocalConstantId gave us an attached constant.
  2447. auto unattached_self_const_id =
  2448. resolver.local_constant_values().GetUnattachedConstant(self_const_id);
  2449. RequireIdentifiedFacetType(
  2450. resolver.local_context(), SemIR::LocId::None, unattached_self_const_id,
  2451. *facet_type, []([[maybe_unused]] auto& builder) {
  2452. CARBON_FATAL("Imported impl constraint can't be identified");
  2453. });
  2454. }
  2455. if (import_impl.is_complete()) {
  2456. ImportImplDefinition(resolver, import_impl, new_impl);
  2457. }
  2458. // If the `impl` is declared in the API file corresponding to the current
  2459. // file, add this to impl lookup so that it can be found by redeclarations
  2460. // in the current file.
  2461. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2462. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2463. }
  2464. return ResolveResult::FinishGenericOrDone(
  2465. resolver, impl_const_id, new_impl.first_decl_id(), import_impl.generic_id,
  2466. new_impl.generic_id, generic_data);
  2467. }
  2468. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2469. SemIR::RequireImplsDecl inst,
  2470. SemIR::ConstantId require_decl_const_id)
  2471. -> ResolveResult {
  2472. const auto& import_require =
  2473. resolver.import_require_impls().Get(inst.require_impls_id);
  2474. auto require_decl_id = SemIR::InstId::None;
  2475. auto require_impls_id = SemIR::RequireImplsId::None;
  2476. if (!require_decl_const_id.has_value()) {
  2477. // Phase one: Make the decl and structure with placeholder values to be
  2478. // filled in. Begin the generic so instructions can be attached to it.
  2479. SemIR::RequireImplsDecl require_decl = {
  2480. .require_impls_id = SemIR::RequireImplsId::None,
  2481. .decl_block_id = SemIR::InstBlockId::Empty};
  2482. auto require_decl_id = AddPlaceholderImportedInst(
  2483. resolver, import_require.decl_id, require_decl);
  2484. require_impls_id = resolver.local_require_impls().Add(
  2485. {.self_id = SemIR::TypeInstId::None,
  2486. .facet_type_inst_id = SemIR::TypeInstId::None,
  2487. .decl_id = require_decl_id,
  2488. .parent_scope_id = SemIR::NameScopeId::None,
  2489. .generic_id = ImportIncompleteGeneric(resolver, require_decl_id,
  2490. import_require.generic_id)});
  2491. // Write the RequireImplsId into the RequireImplsDecl.
  2492. require_decl.require_impls_id = require_impls_id;
  2493. require_decl_const_id =
  2494. ReplacePlaceholderImportedInst(resolver, require_decl_id, require_decl);
  2495. } else {
  2496. // Phase two: Get the `require_decl_id` and `require_impls_id` from the
  2497. // RequireImplsDecl constructed in phase one.
  2498. require_decl_id =
  2499. resolver.local_constant_values().GetInstId(require_decl_const_id);
  2500. require_impls_id = resolver.local_insts()
  2501. .GetAs<SemIR::RequireImplsDecl>(require_decl_id)
  2502. .require_impls_id;
  2503. }
  2504. // Load dependent constants.
  2505. auto parent_scope_id =
  2506. GetLocalNameScopeId(resolver, import_require.parent_scope_id);
  2507. auto generic_data = GetLocalGenericData(resolver, import_require.generic_id);
  2508. auto self_const_id = GetLocalConstantId(resolver, import_require.self_id);
  2509. auto facet_type_const_id =
  2510. GetLocalConstantId(resolver, import_require.facet_type_inst_id);
  2511. if (resolver.HasNewWork()) {
  2512. return ResolveResult::Retry(require_decl_const_id, require_decl_id);
  2513. }
  2514. // Fill in the RequireImpls structure.
  2515. auto& new_require = resolver.local_require_impls().Get(require_impls_id);
  2516. new_require.self_id = AddLoadedImportRefForType(
  2517. resolver, import_require.self_id, self_const_id);
  2518. new_require.facet_type_inst_id = AddLoadedImportRefForType(
  2519. resolver, import_require.facet_type_inst_id, facet_type_const_id);
  2520. new_require.extend_self = import_require.extend_self;
  2521. new_require.parent_scope_id = parent_scope_id;
  2522. return ResolveResult::FinishGenericOrDone(
  2523. resolver, require_decl_const_id, require_decl_id,
  2524. import_require.generic_id, new_require.generic_id, generic_data);
  2525. }
  2526. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2527. SemIR::ImportRefLoaded /*inst*/,
  2528. SemIR::InstId inst_id) -> ResolveResult {
  2529. // Return the constant for the instruction of the imported constant.
  2530. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2531. CARBON_CHECK(constant_id.has_value(),
  2532. "Loaded import ref has no constant value");
  2533. if (!constant_id.is_constant()) {
  2534. resolver.local_context().TODO(
  2535. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2536. return ResolveResult::Done(constant_id);
  2537. }
  2538. auto new_constant_id = GetLocalConstantId(resolver, constant_id);
  2539. return ResolveResult::RetryOrDone(resolver, new_constant_id);
  2540. }
  2541. // Make a declaration of an interface. This is done as a separate step from
  2542. // importing the interface definition in order to resolve cycles.
  2543. static auto ImportInterfaceDecl(ImportContext& context,
  2544. const SemIR::Interface& import_interface,
  2545. SemIR::SpecificId enclosing_specific_id)
  2546. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2547. SemIR::InterfaceDecl interface_decl = {
  2548. .type_id = SemIR::TypeType::TypeId,
  2549. .interface_id = SemIR::InterfaceId::None,
  2550. .decl_block_id = SemIR::InstBlockId::Empty};
  2551. auto interface_decl_id = AddPlaceholderImportedInst(
  2552. context, import_interface.first_owning_decl_id, interface_decl);
  2553. // Start with an incomplete interface.
  2554. //
  2555. // The generic_with_self_id is constructed by the InterfaceWithSelfDecl
  2556. // instruction inside the InterfaceDecl's body.
  2557. interface_decl.interface_id = context.local_interfaces().Add(
  2558. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2559. import_interface),
  2560. {.scope_without_self_id = import_interface.is_complete()
  2561. ? AddPlaceholderNameScope(context)
  2562. : SemIR::NameScopeId::None,
  2563. .scope_with_self_id = import_interface.is_complete()
  2564. ? AddPlaceholderNameScope(context)
  2565. : SemIR::NameScopeId::None,
  2566. .core_interface = import_interface.core_interface}});
  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. auto& local_scope =
  3346. resolver.local_name_scopes().Get(namespace_decl.name_scope_id);
  3347. // Namespaces from this package are eagerly imported, so anything we load here
  3348. // must be a closed import.
  3349. local_scope.set_is_closed_import(true);
  3350. // If this was a C++ namespace, connect it to the corresponding C++
  3351. // declaration in this file.
  3352. if (name_scope.is_cpp_scope()) {
  3353. if (auto key = FindCorrespondingClangDeclKey(
  3354. resolver.local_context(), SemIR::LocId(inst_id),
  3355. resolver.import_ir(), name_scope.clang_decl_context_id())) {
  3356. auto clang_decl_id = resolver.local_context().clang_decls().Add(
  3357. {.key = *key, .inst_id = inst_id});
  3358. local_scope.set_clang_decl_context_id(clang_decl_id, true);
  3359. }
  3360. }
  3361. auto namespace_const_id =
  3362. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  3363. return {.const_id = namespace_const_id};
  3364. }
  3365. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3366. SemIR::PatternType inst) -> ResolveResult {
  3367. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3368. auto scrutinee_type_inst_id =
  3369. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  3370. if (resolver.HasNewWork()) {
  3371. return ResolveResult::Retry();
  3372. }
  3373. return ResolveResult::Deduplicated<SemIR::PatternType>(
  3374. resolver, {.type_id = SemIR::TypeType::TypeId,
  3375. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  3376. }
  3377. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3378. SemIR::PointerType inst) -> ResolveResult {
  3379. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3380. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  3381. if (resolver.HasNewWork()) {
  3382. return ResolveResult::Retry();
  3383. }
  3384. return ResolveResult::Deduplicated<SemIR::PointerType>(
  3385. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  3386. }
  3387. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3388. SemIR::RefForm inst) -> ResolveResult {
  3389. auto type_component_inst_id =
  3390. GetLocalConstantId(resolver, inst.type_component_inst_id);
  3391. if (resolver.HasNewWork()) {
  3392. return ResolveResult::Retry();
  3393. }
  3394. return ResolveResult::Deduplicated<SemIR::RefForm>(
  3395. resolver, {.type_id = SemIR::TypeType::TypeId,
  3396. .type_component_inst_id = resolver.local_types().GetTypeInstId(
  3397. resolver.local_types().GetTypeIdForTypeConstantId(
  3398. type_component_inst_id))});
  3399. }
  3400. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3401. SemIR::RequireCompleteType inst)
  3402. -> ResolveResult {
  3403. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3404. SemIR::WitnessType::TypeInstId);
  3405. auto complete_type_inst_id =
  3406. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  3407. if (resolver.HasNewWork()) {
  3408. return ResolveResult::Retry();
  3409. }
  3410. return ResolveResult::Deduplicated<SemIR::RequireCompleteType>(
  3411. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3412. SemIR::WitnessType::TypeInstId),
  3413. .complete_type_inst_id = complete_type_inst_id});
  3414. }
  3415. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3416. SemIR::RequireSpecificDefinition inst)
  3417. -> ResolveResult {
  3418. CARBON_CHECK(resolver.import_types().GetTypeInstId(inst.type_id) ==
  3419. SemIR::RequireSpecificDefinitionType::TypeInstId);
  3420. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3421. if (resolver.HasNewWork()) {
  3422. return ResolveResult::Retry();
  3423. }
  3424. auto specific_id =
  3425. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3426. return ResolveResult::Deduplicated<SemIR::RequireSpecificDefinition>(
  3427. resolver, {.type_id = GetSingletonType(
  3428. resolver.local_context(),
  3429. SemIR::RequireSpecificDefinitionType::TypeInstId),
  3430. .specific_id = specific_id});
  3431. }
  3432. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3433. SemIR::ReturnSlotPattern inst,
  3434. SemIR::InstId import_inst_id) -> ResolveResult {
  3435. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3436. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  3437. if (resolver.HasNewWork()) {
  3438. return ResolveResult::Retry();
  3439. }
  3440. return ResolveResult::Unique<SemIR::ReturnSlotPattern>(
  3441. resolver, import_inst_id,
  3442. {.type_id =
  3443. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3444. .subpattern_id = subpattern_id,
  3445. .type_inst_id = SemIR::TypeInstId::None});
  3446. }
  3447. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3448. SemIR::SpecificFunction inst) -> ResolveResult {
  3449. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3450. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3451. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3452. if (resolver.HasNewWork()) {
  3453. return ResolveResult::Retry();
  3454. }
  3455. auto type_id =
  3456. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id);
  3457. auto specific_id =
  3458. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3459. return ResolveResult::Deduplicated<SemIR::SpecificFunction>(
  3460. resolver,
  3461. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3462. }
  3463. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3464. SemIR::SpecificImplFunction inst)
  3465. -> ResolveResult {
  3466. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3467. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3468. if (resolver.HasNewWork()) {
  3469. return ResolveResult::Retry();
  3470. }
  3471. auto type_id = GetSingletonType(resolver.local_context(),
  3472. SemIR::SpecificFunctionType::TypeInstId);
  3473. auto specific_id =
  3474. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3475. return ResolveResult::Deduplicated<SemIR::SpecificImplFunction>(
  3476. resolver,
  3477. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3478. }
  3479. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3480. SemIR::StructAccess inst) -> ResolveResult {
  3481. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3482. auto struct_id = GetLocalConstantInstId(resolver, inst.struct_id);
  3483. if (resolver.HasNewWork()) {
  3484. return ResolveResult::Retry();
  3485. }
  3486. // A `struct_access` constant requires its struct operand to have a complete
  3487. // type.
  3488. CompleteTypeOrCheckFail(resolver.local_context(),
  3489. resolver.local_insts().Get(struct_id).type_id());
  3490. return ResolveResult::Deduplicated<SemIR::StructAccess>(
  3491. resolver,
  3492. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3493. .struct_id = struct_id,
  3494. .index = inst.index});
  3495. }
  3496. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3497. SemIR::StructType inst) -> ResolveResult {
  3498. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3499. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  3500. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  3501. field_type_inst_ids.reserve(orig_fields.size());
  3502. for (auto field : orig_fields) {
  3503. field_type_inst_ids.push_back(
  3504. GetLocalTypeInstId(resolver, field.type_inst_id));
  3505. }
  3506. if (resolver.HasNewWork()) {
  3507. return ResolveResult::Retry();
  3508. }
  3509. // Prepare a vector of fields for GetStructType.
  3510. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  3511. new_fields.reserve(orig_fields.size());
  3512. for (auto [orig_field, field_type_inst_id] :
  3513. llvm::zip_equal(orig_fields, field_type_inst_ids)) {
  3514. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  3515. new_fields.push_back(
  3516. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  3517. }
  3518. return ResolveResult::Deduplicated<SemIR::StructType>(
  3519. resolver, {.type_id = SemIR::TypeType::TypeId,
  3520. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  3521. new_fields)});
  3522. }
  3523. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3524. SemIR::StructValue inst) -> ResolveResult {
  3525. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3526. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3527. if (resolver.HasNewWork()) {
  3528. return ResolveResult::Retry();
  3529. }
  3530. return ResolveResult::Deduplicated<SemIR::StructValue>(
  3531. resolver,
  3532. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3533. .elements_id =
  3534. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3535. }
  3536. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3537. SemIR::Temporary inst) -> ResolveResult {
  3538. CARBON_CHECK(inst.storage_id == SemIR::InstId::None);
  3539. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3540. auto init_id = GetLocalConstantInstId(resolver, inst.init_id);
  3541. if (resolver.HasNewWork()) {
  3542. return ResolveResult::Retry();
  3543. }
  3544. return ResolveResult::Deduplicated<SemIR::Temporary>(
  3545. resolver,
  3546. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3547. .storage_id = SemIR::InstId::None,
  3548. .init_id = init_id});
  3549. }
  3550. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3551. SemIR::TupleAccess inst) -> ResolveResult {
  3552. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3553. auto tuple_id = GetLocalConstantInstId(resolver, inst.tuple_id);
  3554. if (resolver.HasNewWork()) {
  3555. return ResolveResult::Retry();
  3556. }
  3557. // A `tuple_access` constant requires its struct operand to have a complete
  3558. // type.
  3559. CompleteTypeOrCheckFail(resolver.local_context(),
  3560. resolver.local_insts().Get(tuple_id).type_id());
  3561. return ResolveResult::Deduplicated<SemIR::TupleAccess>(
  3562. resolver,
  3563. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3564. .tuple_id = tuple_id,
  3565. .index = inst.index});
  3566. }
  3567. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3568. SemIR::TuplePattern inst,
  3569. SemIR::InstId import_inst_id) -> ResolveResult {
  3570. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3571. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  3572. if (resolver.HasNewWork()) {
  3573. return ResolveResult::Retry();
  3574. }
  3575. return ResolveResult::Unique<SemIR::TuplePattern>(
  3576. resolver, import_inst_id,
  3577. {.type_id =
  3578. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3579. .elements_id =
  3580. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements)});
  3581. }
  3582. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3583. SemIR::TupleType inst) -> ResolveResult {
  3584. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3585. auto orig_type_inst_ids =
  3586. resolver.import_inst_blocks().Get(inst.type_elements_id);
  3587. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  3588. // type system that its holding `TypeInstId` elements.
  3589. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  3590. type_inst_ids.reserve(orig_type_inst_ids.size());
  3591. for (auto elem_type_inst_id :
  3592. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  3593. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  3594. }
  3595. if (resolver.HasNewWork()) {
  3596. return ResolveResult::Retry();
  3597. }
  3598. return ResolveResult::Deduplicated<SemIR::TupleType>(
  3599. resolver, {.type_id = SemIR::TypeType::TypeId,
  3600. .type_elements_id = GetLocalCanonicalInstBlockId(
  3601. resolver, inst.type_elements_id, type_inst_ids)});
  3602. }
  3603. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3604. SemIR::TupleValue inst) -> ResolveResult {
  3605. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3606. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3607. if (resolver.HasNewWork()) {
  3608. return ResolveResult::Retry();
  3609. }
  3610. return ResolveResult::Deduplicated<SemIR::TupleValue>(
  3611. resolver,
  3612. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3613. .elements_id =
  3614. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3615. }
  3616. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3617. SemIR::UnboundElementType inst)
  3618. -> ResolveResult {
  3619. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3620. auto class_const_inst_id =
  3621. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  3622. auto elem_const_inst_id =
  3623. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  3624. if (resolver.HasNewWork()) {
  3625. return ResolveResult::Retry();
  3626. }
  3627. return ResolveResult::Deduplicated<SemIR::UnboundElementType>(
  3628. resolver, {.type_id = SemIR::TypeType::TypeId,
  3629. .class_type_inst_id = class_const_inst_id,
  3630. .element_type_inst_id = elem_const_inst_id});
  3631. }
  3632. template <typename VarPatternT>
  3633. requires SemIR::Internal::HasInstCategory<SemIR::AnyVarPattern, VarPatternT>
  3634. static auto TryResolveTypedInst(ImportRefResolver& resolver, VarPatternT inst,
  3635. SemIR::InstId import_inst_id) -> ResolveResult {
  3636. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3637. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  3638. if (resolver.HasNewWork()) {
  3639. return ResolveResult::Retry();
  3640. }
  3641. return ResolveResult::Unique<VarPatternT>(
  3642. resolver, import_inst_id,
  3643. {.type_id =
  3644. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3645. .subpattern_id = subpattern_id});
  3646. }
  3647. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3648. SemIR::VarStorage inst,
  3649. SemIR::InstId import_inst_id) -> ResolveResult {
  3650. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3651. auto pattern_id = GetLocalConstantInstId(resolver, inst.pattern_id);
  3652. if (resolver.HasNewWork()) {
  3653. return ResolveResult::Retry();
  3654. }
  3655. return ResolveResult::Unique<SemIR::VarStorage>(
  3656. resolver, import_inst_id,
  3657. {.type_id =
  3658. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3659. .pattern_id = pattern_id});
  3660. }
  3661. // Tries to resolve the InstId, returning a canonical constant when ready, or
  3662. // `None` if more has been added to the stack. This is the same as
  3663. // TryResolveInst, except that it may resolve symbolic constants as canonical
  3664. // constants instead of as constants associated with a particular generic.
  3665. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  3666. SemIR::InstId inst_id,
  3667. SemIR::ConstantId const_id)
  3668. -> ResolveResult {
  3669. // These instruction types are imported across multiple phases to arrive at
  3670. // their constant value. We can't just import their constant value instruction
  3671. // directly.
  3672. auto untyped_inst = resolver.import_insts().GetWithAttachedType(inst_id);
  3673. CARBON_KIND_SWITCH(untyped_inst) {
  3674. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  3675. return TryResolveTypedInst(resolver, inst, const_id);
  3676. }
  3677. case CARBON_KIND(SemIR::ClassDecl inst): {
  3678. return TryResolveTypedInst(resolver, inst, const_id);
  3679. }
  3680. case CARBON_KIND(SemIR::FunctionDecl inst): {
  3681. return TryResolveTypedInst(resolver, inst, const_id);
  3682. }
  3683. case CARBON_KIND(SemIR::ImplDecl inst): {
  3684. return TryResolveTypedInst(resolver, inst, const_id);
  3685. }
  3686. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  3687. return TryResolveTypedInst(resolver, inst, const_id);
  3688. }
  3689. case CARBON_KIND(SemIR::InterfaceWithSelfDecl inst): {
  3690. return TryResolveTypedInst(resolver, inst, const_id);
  3691. }
  3692. case CARBON_KIND(SemIR::NamedConstraintDecl inst): {
  3693. return TryResolveTypedInst(resolver, inst, const_id);
  3694. }
  3695. case CARBON_KIND(SemIR::NamedConstraintWithSelfDecl inst): {
  3696. return TryResolveTypedInst(resolver, inst, const_id);
  3697. }
  3698. case CARBON_KIND(SemIR::RequireImplsDecl inst): {
  3699. return TryResolveTypedInst(resolver, inst, const_id);
  3700. }
  3701. default:
  3702. break;
  3703. }
  3704. // Other instructions are imported in a single phase (once their dependencies
  3705. // are all imported).
  3706. CARBON_CHECK(!const_id.has_value());
  3707. auto inst_constant_id = resolver.import_constant_values().Get(inst_id);
  3708. if (!inst_constant_id.is_constant()) {
  3709. // TODO: Import of non-constant BindNames happens when importing `let`
  3710. // declarations.
  3711. CARBON_CHECK(resolver.import_insts().Is<SemIR::AnyBinding>(inst_id),
  3712. "TryResolveInst on non-constant instruction {0}", inst_id);
  3713. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  3714. }
  3715. // Import the canonical constant value instruction for `inst_id` directly. We
  3716. // don't try to import the non-canonical `inst_id`.
  3717. auto constant_inst_id =
  3718. resolver.import_constant_values().GetInstId(inst_constant_id);
  3719. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  3720. constant_inst_id) == constant_inst_id,
  3721. "Constant value of constant instruction should refer to "
  3722. "the same instruction");
  3723. if (SemIR::IsSingletonInstId(constant_inst_id)) {
  3724. // Constants for builtins can be directly copied.
  3725. return ResolveResult::Done(
  3726. resolver.local_constant_values().Get(constant_inst_id));
  3727. }
  3728. auto untyped_constant_inst =
  3729. resolver.import_insts().GetWithAttachedType(constant_inst_id);
  3730. CARBON_KIND_SWITCH(untyped_constant_inst) {
  3731. case CARBON_KIND(SemIR::AdaptDecl inst): {
  3732. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3733. }
  3734. case CARBON_KIND(SemIR::ArrayType inst): {
  3735. return TryResolveTypedInst(resolver, inst);
  3736. }
  3737. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  3738. return TryResolveTypedInst(resolver, inst);
  3739. }
  3740. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  3741. return TryResolveTypedInst(resolver, inst);
  3742. }
  3743. case CARBON_KIND(SemIR::BaseDecl inst): {
  3744. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3745. }
  3746. case CARBON_KIND(SemIR::AliasBinding inst): {
  3747. return TryResolveTypedInst(resolver, inst);
  3748. }
  3749. case CARBON_KIND(SemIR::SymbolicBinding inst): {
  3750. return TryResolveTypedInst(resolver, inst);
  3751. }
  3752. case CARBON_KIND(SemIR::BoolLiteral inst): {
  3753. return TryResolveTypedInst(resolver, inst);
  3754. }
  3755. case CARBON_KIND(SemIR::BoundMethod inst): {
  3756. return TryResolveTypedInst(resolver, inst);
  3757. }
  3758. case CARBON_KIND(SemIR::Call inst): {
  3759. return TryResolveTypedInst(resolver, inst);
  3760. }
  3761. case CARBON_KIND(SemIR::CharLiteralValue inst): {
  3762. return TryResolveTypedInst(resolver, inst);
  3763. }
  3764. case CARBON_KIND(SemIR::ClassType inst): {
  3765. return TryResolveTypedInst(resolver, inst);
  3766. }
  3767. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  3768. return TryResolveTypedInst(resolver, inst);
  3769. }
  3770. case CARBON_KIND(SemIR::ConstType inst): {
  3771. return TryResolveTypedInst(resolver, inst);
  3772. }
  3773. case CARBON_KIND(SemIR::CppOverloadSetType inst): {
  3774. return TryResolveTypedInst(resolver, inst);
  3775. }
  3776. case CARBON_KIND(SemIR::CppOverloadSetValue inst): {
  3777. return TryResolveTypedInst(resolver, inst);
  3778. }
  3779. case CARBON_KIND(SemIR::CustomWitness inst): {
  3780. return TryResolveTypedInst(resolver, inst);
  3781. }
  3782. case CARBON_KIND(SemIR::ExportDecl inst): {
  3783. return TryResolveTypedInst(resolver, inst);
  3784. }
  3785. case CARBON_KIND(SemIR::FacetAccessType inst): {
  3786. return TryResolveTypedInst(resolver, inst);
  3787. }
  3788. case CARBON_KIND(SemIR::FacetType inst): {
  3789. return TryResolveTypedInst(resolver, inst);
  3790. }
  3791. case CARBON_KIND(SemIR::FacetValue inst): {
  3792. return TryResolveTypedInst(resolver, inst);
  3793. }
  3794. case CARBON_KIND(SemIR::FieldDecl inst): {
  3795. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3796. }
  3797. case CARBON_KIND(SemIR::FloatLiteralValue inst): {
  3798. return TryResolveTypedInst(resolver, inst);
  3799. }
  3800. case CARBON_KIND(SemIR::FloatType inst): {
  3801. return TryResolveTypedInst(resolver, inst);
  3802. }
  3803. case CARBON_KIND(SemIR::FloatValue inst): {
  3804. return TryResolveTypedInst(resolver, inst);
  3805. }
  3806. case CARBON_KIND(SemIR::FunctionType inst): {
  3807. return TryResolveTypedInst(resolver, inst);
  3808. }
  3809. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  3810. return TryResolveTypedInst(resolver, inst);
  3811. }
  3812. case CARBON_KIND(SemIR::GenericClassType inst): {
  3813. return TryResolveTypedInst(resolver, inst);
  3814. }
  3815. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  3816. return TryResolveTypedInst(resolver, inst);
  3817. }
  3818. case CARBON_KIND(SemIR::GenericNamedConstraintType inst): {
  3819. return TryResolveTypedInst(resolver, inst);
  3820. }
  3821. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  3822. return TryResolveTypedInst(resolver, inst);
  3823. }
  3824. case CARBON_KIND(SemIR::ImplWitness inst): {
  3825. return TryResolveTypedInst(resolver, inst);
  3826. }
  3827. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  3828. return TryResolveTypedInst(resolver, inst);
  3829. }
  3830. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  3831. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3832. }
  3833. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  3834. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3835. }
  3836. case CARBON_KIND(SemIR::InitForm inst): {
  3837. return TryResolveTypedInst(resolver, inst);
  3838. }
  3839. case CARBON_KIND(SemIR::IntValue inst): {
  3840. return TryResolveTypedInst(resolver, inst);
  3841. }
  3842. case CARBON_KIND(SemIR::IntType inst): {
  3843. return TryResolveTypedInst(resolver, inst);
  3844. }
  3845. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  3846. return TryResolveTypedInst(resolver, inst);
  3847. }
  3848. case CARBON_KIND(SemIR::Namespace inst): {
  3849. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3850. }
  3851. case CARBON_KIND(SemIR::OutParamPattern inst): {
  3852. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3853. }
  3854. case CARBON_KIND(SemIR::PartialType inst): {
  3855. return TryResolveTypedInst(resolver, inst);
  3856. }
  3857. case CARBON_KIND(SemIR::PatternType inst): {
  3858. return TryResolveTypedInst(resolver, inst);
  3859. }
  3860. case CARBON_KIND(SemIR::PointerType inst): {
  3861. return TryResolveTypedInst(resolver, inst);
  3862. }
  3863. case CARBON_KIND(SemIR::RefBindingPattern inst): {
  3864. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3865. }
  3866. case CARBON_KIND(SemIR::RefForm inst): {
  3867. return TryResolveTypedInst(resolver, inst);
  3868. }
  3869. case CARBON_KIND(SemIR::RefParamPattern inst): {
  3870. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3871. }
  3872. case CARBON_KIND(SemIR::RefReturnPattern inst): {
  3873. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3874. }
  3875. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  3876. return TryResolveTypedInst(resolver, inst);
  3877. }
  3878. case CARBON_KIND(SemIR::RequireSpecificDefinition inst): {
  3879. return TryResolveTypedInst(resolver, inst);
  3880. }
  3881. case CARBON_KIND(SemIR::ReturnSlotPattern inst): {
  3882. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3883. }
  3884. case CARBON_KIND(SemIR::SpecificFunction inst): {
  3885. return TryResolveTypedInst(resolver, inst);
  3886. }
  3887. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  3888. return TryResolveTypedInst(resolver, inst);
  3889. }
  3890. case CARBON_KIND(SemIR::StructAccess inst): {
  3891. return TryResolveTypedInst(resolver, inst);
  3892. }
  3893. case CARBON_KIND(SemIR::StructType inst): {
  3894. return TryResolveTypedInst(resolver, inst);
  3895. }
  3896. case CARBON_KIND(SemIR::StructValue inst): {
  3897. return TryResolveTypedInst(resolver, inst);
  3898. }
  3899. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  3900. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3901. }
  3902. case CARBON_KIND(SemIR::Temporary inst): {
  3903. return TryResolveTypedInst(resolver, inst);
  3904. }
  3905. case CARBON_KIND(SemIR::TupleAccess inst): {
  3906. return TryResolveTypedInst(resolver, inst);
  3907. }
  3908. case CARBON_KIND(SemIR::TuplePattern inst): {
  3909. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3910. }
  3911. case CARBON_KIND(SemIR::TupleType inst): {
  3912. return TryResolveTypedInst(resolver, inst);
  3913. }
  3914. case CARBON_KIND(SemIR::TupleValue inst): {
  3915. return TryResolveTypedInst(resolver, inst);
  3916. }
  3917. case CARBON_KIND(SemIR::UnboundElementType inst): {
  3918. return TryResolveTypedInst(resolver, inst);
  3919. }
  3920. case CARBON_KIND(SemIR::ValueBindingPattern inst): {
  3921. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3922. }
  3923. case CARBON_KIND(SemIR::ValueParamPattern inst): {
  3924. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3925. }
  3926. case CARBON_KIND(SemIR::ValueReturnPattern inst): {
  3927. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3928. }
  3929. case CARBON_KIND(SemIR::VarParamPattern inst): {
  3930. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3931. }
  3932. case CARBON_KIND(SemIR::VarPattern inst): {
  3933. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3934. }
  3935. case CARBON_KIND(SemIR::VarStorage inst): {
  3936. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3937. }
  3938. case CARBON_KIND(SemIR::VtableDecl inst): {
  3939. return TryResolveTypedInst(resolver, inst);
  3940. }
  3941. case CARBON_KIND(SemIR::VtablePtr inst): {
  3942. return TryResolveTypedInst(resolver, inst);
  3943. }
  3944. case CARBON_KIND(SemIR::WrapperBindingPattern inst): {
  3945. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3946. }
  3947. default:
  3948. // Found a canonical instruction which needs to be resolved, but which is
  3949. // not yet handled.
  3950. //
  3951. // TODO: Could we turn this into a compile-time error?
  3952. CARBON_FATAL(
  3953. "Missing case in TryResolveInstCanonical for instruction kind {0}",
  3954. untyped_constant_inst.kind());
  3955. }
  3956. }
  3957. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  3958. // more has been added to the stack. A similar API is followed for all
  3959. // following TryResolveTypedInst helper functions.
  3960. //
  3961. // `const_id` is `None` unless we've tried to resolve this instruction
  3962. // before, in which case it's the previous result.
  3963. //
  3964. // TODO: Error is returned when support is missing, but that should go away.
  3965. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  3966. SemIR::ConstantId const_id) -> ResolveResult {
  3967. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  3968. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  3969. return TryResolveInstCanonical(resolver, inst_id, const_id);
  3970. }
  3971. // Try to import the generic. This might add new work.
  3972. const auto& symbolic_const =
  3973. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  3974. auto generic_const_id =
  3975. GetLocalConstantId(resolver, symbolic_const.generic_id);
  3976. auto inner_const_id = SemIR::ConstantId::None;
  3977. if (const_id.has_value()) {
  3978. // For the third phase, extract the constant value that
  3979. // TryResolveInstCanonical produced previously.
  3980. inner_const_id = resolver.local_constant_values().GetAttached(
  3981. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  3982. }
  3983. // Import the constant and rebuild the symbolic constant data.
  3984. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  3985. if (!result.const_id.has_value()) {
  3986. // First phase: TryResolveInstCanoncial needs a retry.
  3987. return result;
  3988. }
  3989. if (!const_id.has_value()) {
  3990. // Second phase: we have created an unattached constant. Create a
  3991. // corresponding attached constant.
  3992. if (symbolic_const.generic_id.has_value()) {
  3993. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  3994. {.inst_id =
  3995. resolver.local_constant_values().GetInstId(result.const_id),
  3996. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  3997. .index = symbolic_const.index,
  3998. .dependence = symbolic_const.dependence});
  3999. if (result.decl_id.has_value()) {
  4000. // Overwrite the unattached symbolic constant given initially to the
  4001. // declaration with its final attached symbolic value.
  4002. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  4003. }
  4004. }
  4005. } else {
  4006. // Third phase: perform a consistency check and produce the constant we
  4007. // created in the second phase.
  4008. CARBON_CHECK(result.const_id == inner_const_id,
  4009. "Constant value changed in third phase.");
  4010. result.const_id = const_id;
  4011. }
  4012. return result;
  4013. }
  4014. auto ImportRefResolver::Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  4015. work_stack_.push_back(InstWork{.inst_id = inst_id});
  4016. while (!work_stack_.empty()) {
  4017. auto work_variant = work_stack_.back();
  4018. CARBON_KIND_SWITCH(work_variant) {
  4019. case CARBON_KIND(InstWork work): {
  4020. CARBON_CHECK(work.inst_id.has_value());
  4021. // Step 1: check for a constant value.
  4022. auto existing = FindResolvedConstId(work.inst_id);
  4023. if (existing.const_id.has_value() && !work.retry_with_constant_value) {
  4024. work_stack_.pop_back();
  4025. continue;
  4026. }
  4027. // Step 2: resolve the instruction.
  4028. initial_work_ = work_stack_.size();
  4029. auto result = TryResolveInst(*this, work.inst_id, existing.const_id);
  4030. CARBON_CHECK(!HasNewWork() || result.retry);
  4031. CARBON_CHECK(!existing.const_id.has_value() ||
  4032. existing.const_id == result.const_id,
  4033. "Constant value changed in third phase.");
  4034. if (!existing.const_id.has_value()) {
  4035. SetResolvedConstId(work.inst_id, existing.indirect_insts,
  4036. result.const_id);
  4037. }
  4038. // Step 3: pop or retry.
  4039. if (result.retry) {
  4040. std::get<InstWork>(work_stack_[initial_work_ - 1])
  4041. .retry_with_constant_value = result.const_id.has_value();
  4042. } else {
  4043. work_stack_.pop_back();
  4044. for (const auto& resolve : result.resolve_generic) {
  4045. if (resolve.import_generic_id.has_value()) {
  4046. work_stack_.push_back(
  4047. GenericWork{.import_id = resolve.import_generic_id,
  4048. .local_id = resolve.local_generic_id});
  4049. }
  4050. }
  4051. }
  4052. break;
  4053. }
  4054. case CARBON_KIND(GenericWork generic_work): {
  4055. // Generics may require 2 steps to finish, similar to step 2 and step 3
  4056. // of instructions.
  4057. initial_work_ = work_stack_.size();
  4058. if (TryFinishGeneric(*this, generic_work.import_id,
  4059. generic_work.local_id)) {
  4060. work_stack_.pop_back();
  4061. }
  4062. break;
  4063. }
  4064. case CARBON_KIND(SpecificWork specific_work): {
  4065. // Specifics may require 2 steps to finish, similar to step 2 and step 3
  4066. // of instructions.
  4067. initial_work_ = work_stack_.size();
  4068. if (TryFinishSpecific(*this, specific_work.import_id,
  4069. specific_work.local_id)) {
  4070. work_stack_.pop_back();
  4071. }
  4072. break;
  4073. }
  4074. }
  4075. }
  4076. auto constant_id =
  4077. local_constant_values_for_import_insts().GetAttached(inst_id);
  4078. CARBON_CHECK(constant_id.has_value());
  4079. return constant_id;
  4080. }
  4081. auto ImportRefResolver::ResolveConstant(SemIR::ConstantId import_const_id)
  4082. -> SemIR::ConstantId {
  4083. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  4084. }
  4085. auto ImportRefResolver::ResolveType(SemIR::TypeId import_type_id)
  4086. -> SemIR::TypeId {
  4087. if (!import_type_id.has_value()) {
  4088. return import_type_id;
  4089. }
  4090. auto import_type_const_id = import_ir().types().GetConstantId(import_type_id);
  4091. CARBON_CHECK(import_type_const_id.has_value());
  4092. if (auto import_type_inst_id = import_ir().types().GetAsTypeInstId(
  4093. import_ir().constant_values().GetInstId(import_type_const_id));
  4094. SemIR::IsSingletonInstId(import_type_inst_id)) {
  4095. // Builtins don't require constant resolution; we can use them directly.
  4096. return GetSingletonType(local_context(), import_type_inst_id);
  4097. } else {
  4098. return local_types().GetTypeIdForTypeConstantId(
  4099. ResolveConstant(import_type_id.AsConstantId()));
  4100. }
  4101. }
  4102. auto ImportRefResolver::HasNewWork() -> bool {
  4103. CARBON_CHECK(initial_work_ <= work_stack_.size(), "Work shouldn't decrease");
  4104. return initial_work_ < work_stack_.size();
  4105. }
  4106. auto ImportRefResolver::PushSpecific(SemIR::SpecificId import_id,
  4107. SemIR::SpecificId local_id) -> void {
  4108. // Insert before the current instruction.
  4109. work_stack_.insert(
  4110. work_stack_.begin() + initial_work_ - 1,
  4111. SpecificWork{.import_id = import_id, .local_id = local_id});
  4112. ++initial_work_;
  4113. }
  4114. auto ImportRefResolver::GetLocalConstantValueOrPush(SemIR::InstId inst_id)
  4115. -> SemIR::ConstantId {
  4116. if (!inst_id.has_value()) {
  4117. return SemIR::ConstantId::None;
  4118. }
  4119. auto const_id = local_constant_values_for_import_insts().GetAttached(inst_id);
  4120. if (!const_id.has_value()) {
  4121. work_stack_.push_back(InstWork{.inst_id = inst_id});
  4122. }
  4123. return const_id;
  4124. }
  4125. auto ImportRefResolver::FindResolvedConstId(SemIR::InstId inst_id)
  4126. -> ResolvedConstId {
  4127. ResolvedConstId result;
  4128. if (auto existing_const_id =
  4129. local_constant_values_for_import_insts().GetAttached(inst_id);
  4130. existing_const_id.has_value()) {
  4131. result.const_id = existing_const_id;
  4132. return result;
  4133. }
  4134. const auto* cursor_ir = &import_ir();
  4135. auto cursor_inst_id = inst_id;
  4136. while (true) {
  4137. auto import_ir_inst_id = cursor_ir->insts().GetImportSource(cursor_inst_id);
  4138. if (!import_ir_inst_id.has_value()) {
  4139. return result;
  4140. }
  4141. auto ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
  4142. if (ir_inst.ir_id() == SemIR::ImportIRId::Cpp) {
  4143. auto loc_id = SemIR::LocId(AddImportIRInst(*this, inst_id));
  4144. result.const_id = ImportCppConstantFromFile(local_context(), loc_id,
  4145. *cursor_ir, cursor_inst_id);
  4146. SetResolvedConstId(inst_id, result.indirect_insts, result.const_id);
  4147. result.indirect_insts.clear();
  4148. return result;
  4149. }
  4150. const auto* prev_ir = cursor_ir;
  4151. auto prev_inst_id = cursor_inst_id;
  4152. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id()).sem_ir;
  4153. auto cursor_ir_id =
  4154. AddImportIR(local_context(), {.decl_id = SemIR::InstId::None,
  4155. .is_export = false,
  4156. .sem_ir = cursor_ir});
  4157. cursor_inst_id = ir_inst.inst_id();
  4158. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id, "{0}",
  4159. cursor_ir->insts().Get(cursor_inst_id));
  4160. if (auto const_id =
  4161. local_context()
  4162. .import_ir_constant_values()
  4163. [local_ir().import_irs().GetRawIndex(cursor_ir_id)]
  4164. .GetAttached(cursor_inst_id);
  4165. const_id.has_value()) {
  4166. result.const_id = const_id;
  4167. SetResolvedConstId(inst_id, result.indirect_insts, result.const_id);
  4168. result.indirect_insts.clear();
  4169. return result;
  4170. } else {
  4171. result.indirect_insts.push_back(
  4172. SemIR::ImportIRInst(cursor_ir_id, cursor_inst_id));
  4173. }
  4174. }
  4175. }
  4176. auto ImportRefResolver::SetResolvedConstId(
  4177. SemIR::InstId inst_id, llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  4178. SemIR::ConstantId const_id) -> void {
  4179. local_constant_values_for_import_insts().Set(inst_id, const_id);
  4180. SetIndirectConstantValues(local_context(), indirect_insts, const_id);
  4181. }
  4182. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  4183. // loaded (including the one pointed at directly by the ImportRef), and the
  4184. // final instruction's type ID.
  4185. //
  4186. // This addresses cases where an ImportRefUnloaded may point at another
  4187. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  4188. // constant-evaluated version of the instruction to work with.
  4189. static auto GetInstForLoad(Context& context,
  4190. SemIR::ImportIRInstId import_ir_inst_id)
  4191. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  4192. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  4193. {}, SemIR::TypeId::None};
  4194. auto& [import_ir_insts, type_id] = result;
  4195. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  4196. // The first ImportIRInst is added directly because the IR doesn't need to be
  4197. // localized.
  4198. import_ir_insts.push_back(import_ir_inst);
  4199. const auto* cursor_ir =
  4200. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  4201. while (true) {
  4202. auto cursor_inst =
  4203. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  4204. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  4205. if (!import_ref) {
  4206. type_id = cursor_inst.type_id();
  4207. return result;
  4208. }
  4209. import_ir_inst =
  4210. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  4211. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  4212. import_ir_insts.push_back(SemIR::ImportIRInst(
  4213. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  4214. .is_export = false,
  4215. .sem_ir = cursor_ir}),
  4216. import_ir_inst.inst_id()));
  4217. }
  4218. }
  4219. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  4220. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  4221. if (!inst) {
  4222. return;
  4223. }
  4224. auto [indirect_insts, load_type_id] =
  4225. GetInstForLoad(context, inst->import_ir_inst_id);
  4226. // The last indirect instruction is the one to resolve. Pop it here because
  4227. // Resolve will assign the constant.
  4228. auto load_ir_inst = indirect_insts.pop_back_val();
  4229. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  4230. // Loading an import ref creates local constants from the import ones, but
  4231. // shouldn't be generating novel instructions in the semir as a side effect of
  4232. // that process. Doing so in a generic context would also cause them to end up
  4233. // in the eval block, which would be doubly wrong.
  4234. context.inst_block_stack().Push();
  4235. auto type_id = resolver.ResolveType(load_type_id);
  4236. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  4237. CARBON_CHECK(
  4238. context.inst_block_stack().PeekCurrentBlockContents().empty(),
  4239. "Importing an instruction shouldn't add new instructions to the "
  4240. "local inst block. Found {0} new instructions, first is {1}: {2}.",
  4241. context.inst_block_stack().PeekCurrentBlockContents().size(),
  4242. context.inst_block_stack().PeekCurrentBlockContents().front(),
  4243. context.insts().Get(
  4244. context.inst_block_stack().PeekCurrentBlockContents().front()));
  4245. context.inst_block_stack().PopAndDiscard();
  4246. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  4247. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  4248. // TryEvalInst, which we want to avoid with ImportRefs.
  4249. context.sem_ir().insts().Set(
  4250. inst_id,
  4251. SemIR::ImportRefLoaded{.type_id = type_id,
  4252. .import_ir_inst_id = inst->import_ir_inst_id,
  4253. .entity_name_id = inst->entity_name_id});
  4254. // Store the constant for both the ImportRefLoaded and indirect instructions.
  4255. context.constant_values().Set(inst_id, constant_id);
  4256. SetIndirectConstantValues(context, indirect_insts, constant_id);
  4257. }
  4258. auto ImportImplsFromApiFile(Context& context) -> void {
  4259. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  4260. auto& import_ir = context.import_irs().Get(import_ir_id);
  4261. if (!import_ir.sem_ir) {
  4262. return;
  4263. }
  4264. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  4265. // Resolve the imported impl to a local impl ID.
  4266. ImportImpl(context, import_ir_id, impl_id);
  4267. }
  4268. }
  4269. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  4270. SemIR::ImplId impl_id) -> void {
  4271. ImportRefResolver resolver(&context, import_ir_id);
  4272. resolver.Resolve(resolver.import_impls().Get(impl_id).first_decl_id());
  4273. }
  4274. auto ImportInterface(Context& context, SemIR::ImportIRId import_ir_id,
  4275. SemIR::InterfaceId interface_id) -> SemIR::InterfaceId {
  4276. ImportRefResolver resolver(&context, import_ir_id);
  4277. auto local_id = resolver.Resolve(
  4278. resolver.import_interfaces().Get(interface_id).first_decl_id());
  4279. auto local_inst =
  4280. context.insts().Get(context.constant_values().GetInstId(local_id));
  4281. // A non-generic interface will import as a facet type for that single
  4282. // interface.
  4283. if (auto facet_type = local_inst.TryAs<SemIR::FacetType>()) {
  4284. auto single = context.facet_types()
  4285. .Get(facet_type->facet_type_id)
  4286. .TryAsSingleExtend();
  4287. CARBON_CHECK(single,
  4288. "Importing an interface didn't produce a single interface");
  4289. return std::get<SemIR::SpecificInterface>(*single).interface_id;
  4290. }
  4291. // A generic interface will import as a constant of generic interface type.
  4292. auto generic_interface_type =
  4293. context.types().GetAs<SemIR::GenericInterfaceType>(local_inst.type_id());
  4294. return generic_interface_type.interface_id;
  4295. }
  4296. } // namespace Carbon::Check