import_ref.cpp 197 KB

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