import_ref.cpp 179 KB

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