import_ref.cpp 197 KB

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