import_ref.cpp 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322
  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_params_id = SemIR::InstBlockId::None,
  1981. .return_type_inst_id = SemIR::TypeInstId::None,
  1982. .return_patterns_id = SemIR::InstBlockId::None,
  1983. .virtual_modifier = import_function.virtual_modifier,
  1984. .virtual_index = import_function.virtual_index}});
  1985. // Directly add the function type constant. Don't use `GetFunctionType`
  1986. // because that will evaluate the function type, which we can't do if the
  1987. // specific's value block is still pending.
  1988. auto type_const_id = AddImportedConstant(
  1989. context.local_context(),
  1990. SemIR::FunctionType{.type_id = SemIR::TypeType::TypeId,
  1991. .function_id = function_decl.function_id,
  1992. .specific_id = specific_id});
  1993. function_decl.type_id =
  1994. context.local_types().GetTypeIdForTypeConstantId(type_const_id);
  1995. // Write the function ID and type into the FunctionDecl.
  1996. auto function_const_id =
  1997. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  1998. return {function_decl.function_id, function_const_id};
  1999. }
  2000. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2001. SemIR::FunctionDecl inst,
  2002. SemIR::ConstantId function_const_id)
  2003. -> ResolveResult {
  2004. const auto& import_function =
  2005. resolver.import_functions().Get(inst.function_id);
  2006. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  2007. if (!function_const_id.has_value()) {
  2008. auto import_specific_id = resolver.import_types()
  2009. .GetAs<SemIR::FunctionType>(inst.type_id)
  2010. .specific_id;
  2011. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2012. if (resolver.HasNewWork()) {
  2013. // This is the end of the first phase. Don't make a new function yet if
  2014. // we already have new work.
  2015. return ResolveResult::Retry();
  2016. }
  2017. // On the second phase, create a forward declaration of the interface.
  2018. auto specific_id =
  2019. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2020. std::tie(function_id, function_const_id) =
  2021. MakeFunctionDecl(resolver, import_function, specific_id);
  2022. } else {
  2023. // On the third phase, compute the function ID from the constant value of
  2024. // the declaration.
  2025. auto function_const_inst = resolver.local_insts().Get(
  2026. resolver.local_constant_values().GetInstId(function_const_id));
  2027. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  2028. function_const_inst.type_id());
  2029. function_id = function_type.function_id;
  2030. }
  2031. auto return_type_const_id = SemIR::ConstantId::None;
  2032. if (import_function.return_type_inst_id.has_value()) {
  2033. return_type_const_id =
  2034. GetLocalConstantId(resolver, import_function.return_type_inst_id);
  2035. }
  2036. auto parent_scope_id =
  2037. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  2038. auto implicit_param_patterns = GetLocalInstBlockContents(
  2039. resolver, import_function.implicit_param_patterns_id);
  2040. auto param_patterns =
  2041. GetLocalInstBlockContents(resolver, import_function.param_patterns_id);
  2042. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  2043. auto self_param_id =
  2044. GetLocalConstantInstId(resolver, import_function.self_param_id);
  2045. auto return_patterns =
  2046. GetLocalInstBlockContents(resolver, import_function.return_patterns_id);
  2047. auto& new_function = resolver.local_functions().Get(function_id);
  2048. if (resolver.HasNewWork()) {
  2049. return ResolveResult::Retry(function_const_id,
  2050. new_function.first_decl_id());
  2051. }
  2052. // Add the function declaration.
  2053. new_function.parent_scope_id = parent_scope_id;
  2054. new_function.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2055. resolver, import_function.implicit_param_patterns_id,
  2056. implicit_param_patterns);
  2057. new_function.self_param_id = self_param_id;
  2058. new_function.param_patterns_id = GetLocalCanonicalInstBlockId(
  2059. resolver, import_function.param_patterns_id, param_patterns);
  2060. new_function.return_type_inst_id = SemIR::TypeInstId::None;
  2061. if (import_function.return_type_inst_id.has_value()) {
  2062. new_function.return_type_inst_id = AddLoadedImportRefForType(
  2063. resolver, import_function.return_type_inst_id, return_type_const_id);
  2064. }
  2065. new_function.return_patterns_id = GetLocalCanonicalInstBlockId(
  2066. resolver, import_function.return_patterns_id, return_patterns);
  2067. if (import_function.definition_id.has_value()) {
  2068. new_function.definition_id = new_function.first_owning_decl_id;
  2069. }
  2070. switch (import_function.special_function_kind) {
  2071. case SemIR::Function::SpecialFunctionKind::None: {
  2072. break;
  2073. }
  2074. case SemIR::Function::SpecialFunctionKind::Builtin: {
  2075. new_function.SetBuiltinFunction(import_function.builtin_function_kind());
  2076. break;
  2077. }
  2078. case SemIR::Function::SpecialFunctionKind::Thunk: {
  2079. auto entity_name_id = resolver.local_entity_names().AddCanonical(
  2080. {.name_id = new_function.name_id,
  2081. .parent_scope_id = new_function.parent_scope_id});
  2082. new_function.SetThunk(AddImportRef(
  2083. resolver, import_function.thunk_decl_id(), entity_name_id));
  2084. break;
  2085. }
  2086. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  2087. resolver.local_context().TODO(SemIR::LocId::None,
  2088. "Unsupported: Importing C++ functions that "
  2089. "require thunks indirectly");
  2090. }
  2091. }
  2092. return ResolveResult::FinishGenericOrDone(
  2093. resolver, function_const_id, new_function.first_decl_id(),
  2094. import_function.generic_id, new_function.generic_id, generic_data);
  2095. }
  2096. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2097. SemIR::VtableDecl inst) -> ResolveResult {
  2098. const auto& import_vtable = resolver.import_vtables().Get(inst.vtable_id);
  2099. auto class_const_id =
  2100. GetLocalConstantId(resolver, resolver.import_classes()
  2101. .Get(import_vtable.class_id)
  2102. .first_owning_decl_id);
  2103. auto class_const_inst = resolver.local_insts().Get(
  2104. resolver.local_constant_values().GetInstId(class_const_id));
  2105. // TODO: Ensure the vtable is only imported once, in eg: if there's distinct
  2106. // vtable constants (imported from multiple libraries using the vtable) that
  2107. // refer to the same vtable, the vtable should still be singular.
  2108. auto virtual_functions =
  2109. resolver.import_inst_blocks().Get(import_vtable.virtual_functions_id);
  2110. llvm::SmallVector<SemIR::InstId> lazy_virtual_functions;
  2111. lazy_virtual_functions.reserve(virtual_functions.size());
  2112. for (auto vtable_entry_id : virtual_functions) {
  2113. auto local_attached_constant_id =
  2114. GetLocalConstantId(resolver, vtable_entry_id);
  2115. lazy_virtual_functions.push_back(
  2116. resolver.local_constant_values().GetInstIdIfValid(
  2117. local_attached_constant_id));
  2118. }
  2119. if (resolver.HasNewWork()) {
  2120. return ResolveResult::Retry();
  2121. }
  2122. for (auto [import_vtable_entry_inst_id, local_vtable_entry_inst_id] :
  2123. llvm::zip_equal(virtual_functions, lazy_virtual_functions)) {
  2124. // Use LoadedImportRef for imported symbolic constant vtable entries so they
  2125. // can carry attached constants necessary for applying specifics to these
  2126. // constants when they are used.
  2127. auto local_attached_constant_id =
  2128. resolver.local_constant_values().GetAttached(
  2129. local_vtable_entry_inst_id);
  2130. if (local_attached_constant_id.is_symbolic()) {
  2131. local_vtable_entry_inst_id = AddLoadedImportRef(
  2132. resolver,
  2133. GetSingletonType(resolver.local_context(),
  2134. SemIR::SpecificFunctionType::TypeInstId),
  2135. import_vtable_entry_inst_id, local_attached_constant_id);
  2136. }
  2137. }
  2138. auto class_id = SemIR::ClassId::None;
  2139. if (class_const_inst.Is<SemIR::ClassType>()) {
  2140. class_id = class_const_inst.As<SemIR::ClassType>().class_id;
  2141. } else {
  2142. auto generic_class_type =
  2143. resolver.local_types().GetAs<SemIR::GenericClassType>(
  2144. class_const_inst.type_id());
  2145. class_id = generic_class_type.class_id;
  2146. }
  2147. auto new_vtable_id = resolver.local_vtables().Add(
  2148. {{.class_id = class_id,
  2149. .virtual_functions_id =
  2150. resolver.local_inst_blocks().Add(lazy_virtual_functions)}});
  2151. return ResolveResult::Deduplicated<SemIR::VtableDecl>(
  2152. resolver, {.type_id = GetPointerType(resolver.local_context(),
  2153. SemIR::VtableType::TypeInstId),
  2154. .vtable_id = new_vtable_id});
  2155. }
  2156. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2157. SemIR::VtablePtr inst) -> ResolveResult {
  2158. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2159. auto vtable_const_id = GetLocalConstantId(
  2160. resolver, resolver.import_classes()
  2161. .Get(resolver.import_vtables().Get(inst.vtable_id).class_id)
  2162. .vtable_decl_id);
  2163. auto vtable_const_inst = resolver.local_insts().Get(
  2164. resolver.local_constant_values().GetInstId(vtable_const_id));
  2165. if (resolver.HasNewWork()) {
  2166. return ResolveResult::Retry();
  2167. }
  2168. return ResolveResult::Deduplicated<SemIR::VtablePtr>(
  2169. resolver,
  2170. {.type_id = GetPointerType(resolver.local_context(),
  2171. SemIR::VtableType::TypeInstId),
  2172. .vtable_id = vtable_const_inst.As<SemIR::VtableDecl>().vtable_id,
  2173. .specific_id =
  2174. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data)});
  2175. }
  2176. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2177. SemIR::FunctionType inst) -> ResolveResult {
  2178. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2179. auto fn_val_id = GetLocalConstantInstId(
  2180. resolver,
  2181. resolver.import_functions().Get(inst.function_id).first_decl_id());
  2182. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2183. if (resolver.HasNewWork()) {
  2184. return ResolveResult::Retry();
  2185. }
  2186. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  2187. return ResolveResult::Deduplicated<SemIR::FunctionType>(
  2188. resolver, {.type_id = SemIR::TypeType::TypeId,
  2189. .function_id = resolver.local_types()
  2190. .GetAs<SemIR::FunctionType>(fn_type_id)
  2191. .function_id,
  2192. .specific_id = GetOrAddLocalSpecific(
  2193. resolver, inst.specific_id, specific_data)});
  2194. }
  2195. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2196. SemIR::FunctionTypeWithSelfType inst)
  2197. -> ResolveResult {
  2198. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2199. auto interface_function_type_id =
  2200. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  2201. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  2202. if (resolver.HasNewWork()) {
  2203. return ResolveResult::Retry();
  2204. }
  2205. return ResolveResult::Deduplicated<SemIR::FunctionTypeWithSelfType>(
  2206. resolver, {.type_id = SemIR::TypeType::TypeId,
  2207. .interface_function_type_id = interface_function_type_id,
  2208. .self_id = self_id});
  2209. }
  2210. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2211. SemIR::GenericClassType inst) -> ResolveResult {
  2212. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2213. auto class_val_id = GetLocalConstantInstId(
  2214. resolver,
  2215. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  2216. if (resolver.HasNewWork()) {
  2217. return ResolveResult::Retry();
  2218. }
  2219. auto class_val = resolver.local_insts().Get(class_val_id);
  2220. CARBON_CHECK(
  2221. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  2222. return ResolveResult::Done(
  2223. resolver.local_types().GetConstantId(class_val.type_id()));
  2224. }
  2225. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2226. SemIR::GenericInterfaceType inst)
  2227. -> ResolveResult {
  2228. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2229. auto interface_val_id = GetLocalConstantInstId(
  2230. resolver,
  2231. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2232. if (resolver.HasNewWork()) {
  2233. return ResolveResult::Retry();
  2234. }
  2235. auto interface_val = resolver.local_insts().Get(interface_val_id);
  2236. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  2237. interface_val.type_id()));
  2238. return ResolveResult::Done(
  2239. resolver.local_types().GetConstantId(interface_val.type_id()));
  2240. }
  2241. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2242. SemIR::GenericNamedConstraintType inst)
  2243. -> ResolveResult {
  2244. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2245. auto constraint_val_id =
  2246. GetLocalConstantInstId(resolver, resolver.import_named_constraints()
  2247. .Get(inst.named_constraint_id)
  2248. .first_owning_decl_id);
  2249. if (resolver.HasNewWork()) {
  2250. return ResolveResult::Retry();
  2251. }
  2252. auto constraint_val = resolver.local_insts().Get(constraint_val_id);
  2253. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericNamedConstraintType>(
  2254. constraint_val.type_id()));
  2255. return ResolveResult::Done(
  2256. resolver.local_types().GetConstantId(constraint_val.type_id()));
  2257. }
  2258. // Make a declaration of an impl. This is done as a separate step from
  2259. // importing the impl definition in order to resolve cycles.
  2260. static auto MakeImplDeclaration(ImportContext& context,
  2261. const SemIR::Impl& import_impl,
  2262. SemIR::InstId witness_id)
  2263. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  2264. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  2265. .decl_block_id = SemIR::InstBlockId::Empty};
  2266. auto impl_decl_id = AddPlaceholderImportedInst(
  2267. context, import_impl.latest_decl_id(), impl_decl);
  2268. impl_decl.impl_id = context.local_impls().Add(
  2269. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  2270. {.self_id = SemIR::TypeInstId::None,
  2271. .constraint_id = SemIR::TypeInstId::None,
  2272. .interface = SemIR::SpecificInterface::None,
  2273. .witness_id = witness_id,
  2274. .scope_id = import_impl.is_complete() ? AddPlaceholderNameScope(context)
  2275. : SemIR::NameScopeId::None,
  2276. .is_final = import_impl.is_final}});
  2277. // Write the impl ID into the ImplDecl.
  2278. auto impl_const_id =
  2279. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  2280. return {impl_decl.impl_id, impl_const_id};
  2281. }
  2282. // Imports the definition of an impl.
  2283. static auto AddImplDefinition(ImportContext& context,
  2284. const SemIR::Impl& import_impl,
  2285. SemIR::Impl& new_impl) -> void {
  2286. new_impl.definition_id = new_impl.first_owning_decl_id;
  2287. new_impl.defined = true;
  2288. if (import_impl.scope_id.has_value()) {
  2289. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  2290. new_scope.Set(new_impl.first_owning_decl_id, SemIR::NameId::None,
  2291. new_impl.parent_scope_id);
  2292. // Import the contents of the definition scope, if we might need it. Name
  2293. // lookup is never performed into this scope by a user of the impl, so
  2294. // this is only necessary in the same library that defined the impl, in
  2295. // order to support defining members of the impl out of line in the impl
  2296. // file when the impl is defined in the API file.
  2297. // TODO: Check to see if this impl is owned by the API file, rather than
  2298. // merely being imported into it.
  2299. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2300. const auto& import_scope =
  2301. context.import_name_scopes().Get(import_impl.scope_id);
  2302. // Push a block so that we can add scoped instructions to it.
  2303. context.local_context().inst_block_stack().Push();
  2304. AddNameScopeImportRefs(context, import_scope, new_scope);
  2305. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  2306. }
  2307. }
  2308. }
  2309. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2310. SemIR::ImplDecl inst,
  2311. SemIR::ConstantId impl_const_id)
  2312. -> ResolveResult {
  2313. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  2314. // functions. Factor out the commonality.
  2315. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2316. auto specific_interface_data =
  2317. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  2318. SemIR::ImplId impl_id = SemIR::ImplId::None;
  2319. if (!impl_const_id.has_value()) {
  2320. if (resolver.HasNewWork()) {
  2321. // This is the end of the first phase. Don't make a new impl yet if we
  2322. // already have new work.
  2323. return ResolveResult::Retry();
  2324. }
  2325. // On the second phase, create a forward declaration of the impl for any
  2326. // recursive references.
  2327. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  2328. std::tie(impl_id, impl_const_id) =
  2329. MakeImplDeclaration(resolver, import_impl, witness_id);
  2330. } else {
  2331. // On the third phase, compute the impl ID from the "constant value" of
  2332. // the declaration, which is a reference to the created ImplDecl.
  2333. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  2334. resolver.local_constant_values().GetInstId(impl_const_id));
  2335. impl_id = impl_const_inst.impl_id;
  2336. }
  2337. // Load constants for the definition.
  2338. auto parent_scope_id =
  2339. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  2340. auto implicit_param_patterns = GetLocalInstBlockContents(
  2341. resolver, import_impl.implicit_param_patterns_id);
  2342. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  2343. auto self_const_id = GetLocalConstantId(resolver, import_impl.self_id);
  2344. auto constraint_const_id =
  2345. GetLocalConstantId(resolver, import_impl.constraint_id);
  2346. auto& new_impl = resolver.local_impls().Get(impl_id);
  2347. if (resolver.HasNewWork()) {
  2348. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2349. }
  2350. new_impl.parent_scope_id = parent_scope_id;
  2351. new_impl.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2352. resolver, import_impl.implicit_param_patterns_id,
  2353. implicit_param_patterns);
  2354. // Create instructions for self and constraint to hold the symbolic constant
  2355. // value for a generic impl.
  2356. new_impl.self_id =
  2357. AddLoadedImportRefForType(resolver, import_impl.self_id, self_const_id);
  2358. new_impl.constraint_id = AddLoadedImportRefForType(
  2359. resolver, import_impl.constraint_id, constraint_const_id);
  2360. new_impl.interface = GetLocalSpecificInterface(
  2361. resolver, import_impl.interface, specific_interface_data);
  2362. // Create a local IdentifiedFacetType for the imported facet type, since impl
  2363. // declarations always identify the facet type.
  2364. if (auto facet_type = resolver.local_insts().TryGetAs<SemIR::FacetType>(
  2365. resolver.local_constant_values().GetInstId(constraint_const_id))) {
  2366. RequireIdentifiedFacetType(resolver.local_context(), SemIR::LocId::None,
  2367. *facet_type, nullptr);
  2368. }
  2369. if (import_impl.is_complete()) {
  2370. AddImplDefinition(resolver, import_impl, new_impl);
  2371. }
  2372. // If the `impl` is declared in the API file corresponding to the current
  2373. // file, add this to impl lookup so that it can be found by redeclarations
  2374. // in the current file.
  2375. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2376. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2377. }
  2378. return ResolveResult::FinishGenericOrDone(
  2379. resolver, impl_const_id, new_impl.first_decl_id(), import_impl.generic_id,
  2380. new_impl.generic_id, generic_data);
  2381. }
  2382. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2383. SemIR::RequireImplsDecl inst,
  2384. SemIR::ConstantId require_decl_const_id)
  2385. -> ResolveResult {
  2386. const auto& import_require =
  2387. resolver.import_require_impls().Get(inst.require_impls_id);
  2388. auto require_decl_id = SemIR::InstId::None;
  2389. auto require_impls_id = SemIR::RequireImplsId::None;
  2390. if (!require_decl_const_id.has_value()) {
  2391. // Phase one: Make the decl and structure with placeholder values to be
  2392. // filled in. Begin the generic so instructions can be attached to it.
  2393. SemIR::RequireImplsDecl require_decl = {
  2394. .require_impls_id = SemIR::RequireImplsId::None,
  2395. .decl_block_id = SemIR::InstBlockId::Empty};
  2396. auto require_decl_id = AddPlaceholderImportedInst(
  2397. resolver, import_require.decl_id, require_decl);
  2398. require_impls_id = resolver.local_require_impls().Add(
  2399. {.self_id = SemIR::TypeInstId::None,
  2400. .facet_type_inst_id = SemIR::TypeInstId::None,
  2401. .decl_id = require_decl_id,
  2402. .parent_scope_id = SemIR::NameScopeId::None,
  2403. .generic_id = MakeIncompleteGeneric(resolver, require_decl_id,
  2404. import_require.generic_id)});
  2405. // Write the RequireImplsId into the RequireImplsDecl.
  2406. require_decl.require_impls_id = require_impls_id;
  2407. require_decl_const_id =
  2408. ReplacePlaceholderImportedInst(resolver, require_decl_id, require_decl);
  2409. } else {
  2410. // Phase two: Get the `require_decl_id` and `require_impls_id` from the
  2411. // RequireImplsDecl constructed in phase one.
  2412. require_decl_id =
  2413. resolver.local_constant_values().GetInstId(require_decl_const_id);
  2414. require_impls_id = resolver.local_insts()
  2415. .GetAs<SemIR::RequireImplsDecl>(require_decl_id)
  2416. .require_impls_id;
  2417. }
  2418. // Load dependent constants.
  2419. auto parent_scope_id =
  2420. GetLocalNameScopeId(resolver, import_require.parent_scope_id);
  2421. auto generic_data = GetLocalGenericData(resolver, import_require.generic_id);
  2422. auto self_const_id = GetLocalConstantId(resolver, import_require.self_id);
  2423. auto facet_type_const_id =
  2424. GetLocalConstantId(resolver, import_require.facet_type_inst_id);
  2425. if (resolver.HasNewWork()) {
  2426. return ResolveResult::Retry(require_decl_const_id, require_decl_id);
  2427. }
  2428. // Fill in the RequireImpls structure.
  2429. auto& new_require = resolver.local_require_impls().Get(require_impls_id);
  2430. new_require.self_id = AddLoadedImportRefForType(
  2431. resolver, import_require.self_id, self_const_id);
  2432. new_require.facet_type_inst_id = AddLoadedImportRefForType(
  2433. resolver, import_require.facet_type_inst_id, facet_type_const_id);
  2434. new_require.extend_self = import_require.extend_self;
  2435. new_require.parent_scope_id = parent_scope_id;
  2436. return ResolveResult::FinishGenericOrDone(
  2437. resolver, require_decl_const_id, require_decl_id,
  2438. import_require.generic_id, new_require.generic_id, generic_data);
  2439. }
  2440. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2441. SemIR::ImportRefLoaded /*inst*/,
  2442. SemIR::InstId inst_id) -> ResolveResult {
  2443. // Return the constant for the instruction of the imported constant.
  2444. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2445. CARBON_CHECK(constant_id.has_value(),
  2446. "Loaded import ref has no constant value");
  2447. if (!constant_id.is_constant()) {
  2448. resolver.local_context().TODO(
  2449. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2450. return ResolveResult::Done(constant_id);
  2451. }
  2452. auto new_constant_id = GetLocalConstantId(resolver, constant_id);
  2453. return ResolveResult::RetryOrDone(resolver, new_constant_id);
  2454. }
  2455. // Make a declaration of an interface. This is done as a separate step from
  2456. // importing the interface definition in order to resolve cycles.
  2457. static auto MakeInterfaceDecl(ImportContext& context,
  2458. const SemIR::Interface& import_interface,
  2459. SemIR::SpecificId enclosing_specific_id)
  2460. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2461. SemIR::InterfaceDecl interface_decl = {
  2462. .type_id = SemIR::TypeType::TypeId,
  2463. .interface_id = SemIR::InterfaceId::None,
  2464. .decl_block_id = SemIR::InstBlockId::Empty};
  2465. auto interface_decl_id = AddPlaceholderImportedInst(
  2466. context, import_interface.first_owning_decl_id, interface_decl);
  2467. // Start with an incomplete interface.
  2468. interface_decl.interface_id = context.local_interfaces().Add(
  2469. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2470. import_interface),
  2471. {.scope_id = import_interface.is_complete()
  2472. ? AddPlaceholderNameScope(context)
  2473. : SemIR::NameScopeId::None}});
  2474. if (import_interface.has_parameters()) {
  2475. interface_decl.type_id = GetGenericInterfaceType(
  2476. context.local_context(), interface_decl.interface_id,
  2477. enclosing_specific_id);
  2478. }
  2479. // Write the interface ID into the InterfaceDecl.
  2480. auto interface_const_id = ReplacePlaceholderImportedInst(
  2481. context, interface_decl_id, interface_decl);
  2482. return {interface_decl.interface_id, interface_const_id};
  2483. }
  2484. // Imports the definition for an interface that has been imported as a forward
  2485. // declaration.
  2486. static auto AddInterfaceDefinition(ImportContext& context,
  2487. const SemIR::Interface& import_interface,
  2488. SemIR::Interface& new_interface,
  2489. SemIR::InstId self_param_id) -> void {
  2490. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  2491. const auto& import_scope =
  2492. context.import_name_scopes().Get(import_interface.scope_id);
  2493. // Push a block so that we can add scoped instructions to it.
  2494. context.local_context().inst_block_stack().Push();
  2495. InitializeNameScopeAndImportRefs(
  2496. context, import_scope, new_scope, new_interface.first_owning_decl_id,
  2497. SemIR::NameId::None, new_interface.parent_scope_id);
  2498. new_scope.set_is_interface_definition();
  2499. new_interface.associated_entities_id = AddAssociatedEntities(
  2500. context, new_interface.scope_id, import_interface.associated_entities_id);
  2501. new_interface.body_block_id =
  2502. context.local_context().inst_block_stack().Pop();
  2503. new_interface.self_param_id = self_param_id;
  2504. CARBON_CHECK(import_scope.extended_scopes().empty(),
  2505. "Interfaces don't currently have extended scopes to support.");
  2506. }
  2507. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2508. SemIR::InterfaceDecl inst,
  2509. SemIR::ConstantId interface_const_id)
  2510. -> ResolveResult {
  2511. const auto& import_interface =
  2512. resolver.import_interfaces().Get(inst.interface_id);
  2513. auto interface_id = SemIR::InterfaceId::None;
  2514. if (!interface_const_id.has_value()) {
  2515. auto import_specific_id = SemIR::SpecificId::None;
  2516. if (auto import_generic_interface_type =
  2517. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2518. inst.type_id)) {
  2519. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2520. }
  2521. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2522. if (resolver.HasNewWork()) {
  2523. // This is the end of the first phase. Don't make a new interface yet if
  2524. // we already have new work.
  2525. return ResolveResult::Retry();
  2526. }
  2527. // On the second phase, create a forward declaration of the interface.
  2528. auto enclosing_specific_id =
  2529. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2530. std::tie(interface_id, interface_const_id) =
  2531. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2532. } else {
  2533. // On the third phase, compute the interface ID from the constant value of
  2534. // the declaration.
  2535. auto interface_const_inst = resolver.local_insts().Get(
  2536. resolver.local_constant_values().GetInstId(interface_const_id));
  2537. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2538. const SemIR::FacetTypeInfo& facet_type_info =
  2539. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2540. auto single = facet_type_info.TryAsSingleExtend();
  2541. CARBON_CHECK(single);
  2542. interface_id = std::get<SemIR::SpecificInterface>(*single).interface_id;
  2543. } else {
  2544. auto generic_interface_type =
  2545. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2546. interface_const_inst.type_id());
  2547. interface_id = generic_interface_type.interface_id;
  2548. }
  2549. }
  2550. auto parent_scope_id =
  2551. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2552. auto implicit_param_patterns = GetLocalInstBlockContents(
  2553. resolver, import_interface.implicit_param_patterns_id);
  2554. auto param_patterns =
  2555. GetLocalInstBlockContents(resolver, import_interface.param_patterns_id);
  2556. auto generic_data =
  2557. GetLocalGenericData(resolver, import_interface.generic_id);
  2558. auto require_impls = GetLocalRequireImplsBlockContents(
  2559. resolver, import_interface.require_impls_block_id);
  2560. std::optional<SemIR::InstId> self_param_id;
  2561. if (import_interface.is_complete()) {
  2562. self_param_id =
  2563. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2564. }
  2565. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2566. if (resolver.HasNewWork()) {
  2567. return ResolveResult::Retry(interface_const_id,
  2568. new_interface.first_decl_id());
  2569. }
  2570. new_interface.parent_scope_id = parent_scope_id;
  2571. new_interface.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2572. resolver, import_interface.implicit_param_patterns_id,
  2573. implicit_param_patterns);
  2574. new_interface.param_patterns_id = GetLocalCanonicalInstBlockId(
  2575. resolver, import_interface.param_patterns_id, param_patterns);
  2576. new_interface.require_impls_block_id = GetLocalCanonicalRequireImplsBlockId(
  2577. resolver, import_interface.require_impls_block_id, require_impls);
  2578. if (import_interface.is_complete()) {
  2579. CARBON_CHECK(self_param_id);
  2580. AddInterfaceDefinition(resolver, import_interface, new_interface,
  2581. *self_param_id);
  2582. }
  2583. return ResolveResult::FinishGenericOrDone(
  2584. resolver, interface_const_id, new_interface.first_decl_id(),
  2585. import_interface.generic_id, new_interface.generic_id, generic_data);
  2586. }
  2587. // Make a declaration of a named constraint. This is done as a separate step
  2588. // from importing the constraint definition in order to resolve cycles.
  2589. static auto MakeNamedConstraintDecl(
  2590. ImportContext& context,
  2591. const SemIR::NamedConstraint& import_named_constraint,
  2592. SemIR::SpecificId enclosing_specific_id)
  2593. -> std::pair<SemIR::NamedConstraintId, SemIR::ConstantId> {
  2594. SemIR::NamedConstraintDecl named_constraint_decl = {
  2595. .type_id = SemIR::TypeType::TypeId,
  2596. .named_constraint_id = SemIR::NamedConstraintId::None,
  2597. .decl_block_id = SemIR::InstBlockId::Empty};
  2598. auto named_constraint_decl_id = AddPlaceholderImportedInst(
  2599. context, import_named_constraint.first_owning_decl_id,
  2600. named_constraint_decl);
  2601. // Start with an incomplete interface.
  2602. named_constraint_decl.named_constraint_id =
  2603. context.local_named_constraints().Add(
  2604. {GetIncompleteLocalEntityBase(context, named_constraint_decl_id,
  2605. import_named_constraint),
  2606. {.scope_id = import_named_constraint.is_complete()
  2607. ? AddPlaceholderNameScope(context)
  2608. : SemIR::NameScopeId::None}});
  2609. if (import_named_constraint.has_parameters()) {
  2610. named_constraint_decl.type_id = GetGenericNamedConstraintType(
  2611. context.local_context(), named_constraint_decl.named_constraint_id,
  2612. enclosing_specific_id);
  2613. }
  2614. // Write the interface ID into the InterfaceDecl.
  2615. auto interface_const_id = ReplacePlaceholderImportedInst(
  2616. context, named_constraint_decl_id, named_constraint_decl);
  2617. return {named_constraint_decl.named_constraint_id, interface_const_id};
  2618. }
  2619. // Imports the definition for a named constraint that has been imported as a
  2620. // forward declaration.
  2621. static auto AddNamedConstraintDefinition(
  2622. ImportContext& context,
  2623. const SemIR::NamedConstraint& import_named_constraint,
  2624. SemIR::NamedConstraint& new_named_constraint, SemIR::InstId self_param_id)
  2625. -> void {
  2626. auto& new_scope =
  2627. context.local_name_scopes().Get(new_named_constraint.scope_id);
  2628. const auto& import_scope =
  2629. context.import_name_scopes().Get(import_named_constraint.scope_id);
  2630. // Push a block so that we can add scoped instructions to it.
  2631. context.local_context().inst_block_stack().Push();
  2632. InitializeNameScopeAndImportRefs(context, import_scope, new_scope,
  2633. new_named_constraint.first_owning_decl_id,
  2634. SemIR::NameId::None,
  2635. new_named_constraint.parent_scope_id);
  2636. new_named_constraint.body_block_id =
  2637. context.local_context().inst_block_stack().Pop();
  2638. new_named_constraint.self_param_id = self_param_id;
  2639. new_named_constraint.complete = import_named_constraint.complete;
  2640. CARBON_CHECK(
  2641. import_scope.extended_scopes().empty(),
  2642. "Named constraints don't currently have extended scopes to support.");
  2643. }
  2644. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2645. SemIR::NamedConstraintDecl inst,
  2646. SemIR::ConstantId named_constraint_const_id)
  2647. -> ResolveResult {
  2648. const auto& import_named_constraint =
  2649. resolver.import_named_constraints().Get(inst.named_constraint_id);
  2650. auto named_constraint_id = SemIR::NamedConstraintId::None;
  2651. if (!named_constraint_const_id.has_value()) {
  2652. auto import_specific_id = SemIR::SpecificId::None;
  2653. if (auto import_generic_named_constraint_type =
  2654. resolver.import_types().TryGetAs<SemIR::GenericNamedConstraintType>(
  2655. inst.type_id)) {
  2656. import_specific_id =
  2657. import_generic_named_constraint_type->enclosing_specific_id;
  2658. }
  2659. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2660. if (resolver.HasNewWork()) {
  2661. // This is the end of the first phase. Don't make a new interface yet if
  2662. // we already have new work.
  2663. return ResolveResult::Retry();
  2664. }
  2665. // On the second phase, create a forward declaration of the interface.
  2666. auto enclosing_specific_id =
  2667. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2668. std::tie(named_constraint_id, named_constraint_const_id) =
  2669. MakeNamedConstraintDecl(resolver, import_named_constraint,
  2670. enclosing_specific_id);
  2671. } else {
  2672. // On the third phase, compute the interface ID from the constant value of
  2673. // the declaration.
  2674. auto named_constraint_const_inst = resolver.local_insts().Get(
  2675. resolver.local_constant_values().GetInstId(named_constraint_const_id));
  2676. if (auto facet_type =
  2677. named_constraint_const_inst.TryAs<SemIR::FacetType>()) {
  2678. const SemIR::FacetTypeInfo& facet_type_info =
  2679. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2680. auto single = facet_type_info.TryAsSingleExtend();
  2681. CARBON_CHECK(single);
  2682. named_constraint_id =
  2683. std::get<SemIR::SpecificNamedConstraint>(*single).named_constraint_id;
  2684. } else {
  2685. auto generic_named_constraint_type =
  2686. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  2687. named_constraint_const_inst.type_id());
  2688. named_constraint_id = generic_named_constraint_type.named_constraint_id;
  2689. }
  2690. }
  2691. auto parent_scope_id =
  2692. GetLocalNameScopeId(resolver, import_named_constraint.parent_scope_id);
  2693. auto implicit_param_patterns = GetLocalInstBlockContents(
  2694. resolver, import_named_constraint.implicit_param_patterns_id);
  2695. auto param_patterns = GetLocalInstBlockContents(
  2696. resolver, import_named_constraint.param_patterns_id);
  2697. auto generic_data =
  2698. GetLocalGenericData(resolver, import_named_constraint.generic_id);
  2699. auto require_impls = GetLocalRequireImplsBlockContents(
  2700. resolver, import_named_constraint.require_impls_block_id);
  2701. std::optional<SemIR::InstId> self_param_id;
  2702. if (import_named_constraint.is_complete()) {
  2703. self_param_id =
  2704. GetLocalConstantInstId(resolver, import_named_constraint.self_param_id);
  2705. }
  2706. auto& new_named_constraint =
  2707. resolver.local_named_constraints().Get(named_constraint_id);
  2708. if (resolver.HasNewWork()) {
  2709. return ResolveResult::Retry(named_constraint_const_id,
  2710. new_named_constraint.first_decl_id());
  2711. }
  2712. new_named_constraint.parent_scope_id = parent_scope_id;
  2713. new_named_constraint.implicit_param_patterns_id =
  2714. GetLocalCanonicalInstBlockId(
  2715. resolver, import_named_constraint.implicit_param_patterns_id,
  2716. implicit_param_patterns);
  2717. new_named_constraint.param_patterns_id = GetLocalCanonicalInstBlockId(
  2718. resolver, import_named_constraint.param_patterns_id, param_patterns);
  2719. new_named_constraint.require_impls_block_id =
  2720. GetLocalCanonicalRequireImplsBlockId(
  2721. resolver, import_named_constraint.require_impls_block_id,
  2722. require_impls);
  2723. if (import_named_constraint.is_complete()) {
  2724. CARBON_CHECK(self_param_id);
  2725. AddNamedConstraintDefinition(resolver, import_named_constraint,
  2726. new_named_constraint, *self_param_id);
  2727. }
  2728. return ResolveResult::FinishGenericOrDone(
  2729. resolver, named_constraint_const_id, new_named_constraint.first_decl_id(),
  2730. import_named_constraint.generic_id, new_named_constraint.generic_id,
  2731. generic_data);
  2732. }
  2733. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2734. SemIR::FacetAccessType inst) -> ResolveResult {
  2735. auto facet_value_inst_id =
  2736. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2737. if (resolver.HasNewWork()) {
  2738. return ResolveResult::Retry();
  2739. }
  2740. return ResolveResult::Deduplicated<SemIR::FacetAccessType>(
  2741. resolver, {.type_id = SemIR::TypeType::TypeId,
  2742. .facet_value_inst_id = facet_value_inst_id});
  2743. }
  2744. // Collects and assigns constants for a `FacetTypeInfo`. Discards constants when
  2745. // `local_facet_type_info` is null.
  2746. static auto ResolveFacetTypeInfo(
  2747. ImportRefResolver& resolver,
  2748. const SemIR::FacetTypeInfo& import_facet_type_info,
  2749. SemIR::FacetTypeInfo* local_facet_type_info) -> void {
  2750. if (local_facet_type_info) {
  2751. local_facet_type_info->extend_constraints.reserve(
  2752. import_facet_type_info.extend_constraints.size());
  2753. }
  2754. for (auto interface : import_facet_type_info.extend_constraints) {
  2755. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2756. if (local_facet_type_info) {
  2757. local_facet_type_info->extend_constraints.push_back(
  2758. GetLocalSpecificInterface(resolver, interface, data));
  2759. }
  2760. }
  2761. if (local_facet_type_info) {
  2762. local_facet_type_info->self_impls_constraints.reserve(
  2763. import_facet_type_info.self_impls_constraints.size());
  2764. }
  2765. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2766. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2767. if (local_facet_type_info) {
  2768. local_facet_type_info->self_impls_constraints.push_back(
  2769. GetLocalSpecificInterface(resolver, interface, data));
  2770. }
  2771. }
  2772. if (local_facet_type_info) {
  2773. local_facet_type_info->extend_named_constraints.reserve(
  2774. import_facet_type_info.extend_named_constraints.size());
  2775. }
  2776. for (auto constraint : import_facet_type_info.extend_named_constraints) {
  2777. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  2778. if (local_facet_type_info) {
  2779. local_facet_type_info->extend_named_constraints.push_back(
  2780. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  2781. }
  2782. }
  2783. if (local_facet_type_info) {
  2784. local_facet_type_info->self_impls_named_constraints.reserve(
  2785. import_facet_type_info.self_impls_named_constraints.size());
  2786. }
  2787. for (auto constraint : import_facet_type_info.self_impls_named_constraints) {
  2788. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  2789. if (local_facet_type_info) {
  2790. local_facet_type_info->self_impls_named_constraints.push_back(
  2791. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  2792. }
  2793. }
  2794. if (local_facet_type_info) {
  2795. local_facet_type_info->rewrite_constraints.reserve(
  2796. import_facet_type_info.rewrite_constraints.size());
  2797. }
  2798. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2799. auto lhs_id = GetLocalConstantInstId(resolver, rewrite.lhs_id);
  2800. auto rhs_id = GetLocalConstantInstId(resolver, rewrite.rhs_id);
  2801. if (local_facet_type_info) {
  2802. local_facet_type_info->rewrite_constraints.push_back(
  2803. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  2804. }
  2805. }
  2806. }
  2807. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2808. SemIR::FacetType inst) -> ResolveResult {
  2809. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2810. const SemIR::FacetTypeInfo& import_facet_type_info =
  2811. resolver.import_facet_types().Get(inst.facet_type_id);
  2812. // Ensure values are imported, but discard them to avoid allocations.
  2813. ResolveFacetTypeInfo(resolver, import_facet_type_info,
  2814. /*local_facet_type_info=*/nullptr);
  2815. if (resolver.HasNewWork()) {
  2816. return ResolveResult::Retry();
  2817. }
  2818. SemIR::FacetTypeInfo local_facet_type_info = {
  2819. // TODO: Also process the other requirements.
  2820. .other_requirements = import_facet_type_info.other_requirements};
  2821. // Re-resolve and add values to the local `FacetTypeInfo`.
  2822. ResolveFacetTypeInfo(resolver, import_facet_type_info,
  2823. &local_facet_type_info);
  2824. SemIR::FacetTypeId facet_type_id =
  2825. resolver.local_facet_types().Add(std::move(local_facet_type_info));
  2826. return ResolveResult::Deduplicated<SemIR::FacetType>(
  2827. resolver,
  2828. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  2829. }
  2830. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2831. SemIR::FacetValue inst) -> ResolveResult {
  2832. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2833. auto type_inst_id = GetLocalTypeInstId(resolver, inst.type_inst_id);
  2834. auto witnesses = GetLocalInstBlockContents(resolver, inst.witnesses_block_id);
  2835. if (resolver.HasNewWork()) {
  2836. return ResolveResult::Retry();
  2837. }
  2838. auto witnesses_block_id = SemIR::InstBlockId::None;
  2839. if (inst.witnesses_block_id.has_value()) {
  2840. witnesses_block_id =
  2841. AddCanonicalWitnessesBlock(resolver.local_ir(), witnesses);
  2842. }
  2843. return ResolveResult::Deduplicated<SemIR::FacetValue>(
  2844. resolver,
  2845. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  2846. .type_inst_id = type_inst_id,
  2847. .witnesses_block_id = witnesses_block_id});
  2848. }
  2849. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2850. SemIR::LookupImplWitness inst)
  2851. -> ResolveResult {
  2852. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2853. SemIR::WitnessType::TypeInstId);
  2854. auto query_self_inst_id =
  2855. GetLocalConstantInstId(resolver, inst.query_self_inst_id);
  2856. const auto& import_specific_interface =
  2857. resolver.import_specific_interfaces().Get(
  2858. inst.query_specific_interface_id);
  2859. auto data =
  2860. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  2861. if (resolver.HasNewWork()) {
  2862. return ResolveResult::Retry();
  2863. }
  2864. auto specific_interface =
  2865. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  2866. auto query_specific_interface_id =
  2867. resolver.local_specific_interfaces().Add(specific_interface);
  2868. return ResolveResult::Deduplicated<SemIR::LookupImplWitness>(
  2869. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2870. SemIR::WitnessType::TypeInstId),
  2871. .query_self_inst_id = query_self_inst_id,
  2872. .query_specific_interface_id = query_specific_interface_id});
  2873. }
  2874. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2875. SemIR::ImplWitness inst) -> ResolveResult {
  2876. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2877. SemIR::WitnessType::TypeInstId);
  2878. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2879. auto witness_table_id =
  2880. GetLocalConstantInstId(resolver, inst.witness_table_id);
  2881. if (resolver.HasNewWork()) {
  2882. return ResolveResult::Retry();
  2883. }
  2884. auto specific_id =
  2885. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2886. return ResolveResult::Deduplicated<SemIR::ImplWitness>(
  2887. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2888. SemIR::WitnessType::TypeInstId),
  2889. .witness_table_id = witness_table_id,
  2890. .specific_id = specific_id});
  2891. }
  2892. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2893. SemIR::ImplWitnessAccess inst)
  2894. -> ResolveResult {
  2895. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2896. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2897. if (resolver.HasNewWork()) {
  2898. return ResolveResult::Retry();
  2899. }
  2900. return ResolveResult::Deduplicated<SemIR::ImplWitnessAccess>(
  2901. resolver,
  2902. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  2903. .witness_id = witness_id,
  2904. .index = inst.index});
  2905. }
  2906. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2907. SemIR::ImplWitnessTable inst,
  2908. SemIR::InstId import_inst_id) -> ResolveResult {
  2909. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2910. auto import_decl_inst_id = import_impl.first_decl_id();
  2911. auto local_decl_inst_id =
  2912. GetLocalConstantInstId(resolver, import_decl_inst_id);
  2913. if (resolver.HasNewWork()) {
  2914. return ResolveResult::Retry();
  2915. }
  2916. auto impl_decl =
  2917. resolver.local_insts().GetAs<SemIR::ImplDecl>(local_decl_inst_id);
  2918. auto impl_id = impl_decl.impl_id;
  2919. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  2920. // Create a corresponding instruction to represent the table.
  2921. return ResolveResult::Unique<SemIR::ImplWitnessTable>(
  2922. resolver, import_inst_id,
  2923. {.elements_id = elements_id, .impl_id = impl_id});
  2924. }
  2925. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2926. SemIR::InitForm inst) -> ResolveResult {
  2927. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2928. auto type_component_const_id =
  2929. GetLocalConstantId(resolver, inst.type_component_inst_id);
  2930. if (resolver.HasNewWork()) {
  2931. return ResolveResult::Retry();
  2932. }
  2933. return ResolveResult::Deduplicated<SemIR::InitForm>(
  2934. resolver,
  2935. SemIR::InitForm{
  2936. .type_id =
  2937. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  2938. .type_component_inst_id = resolver.local_constant_values().GetInstId(
  2939. type_component_const_id),
  2940. .index = inst.index});
  2941. }
  2942. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2943. SemIR::IntValue inst) -> ResolveResult {
  2944. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2945. if (resolver.HasNewWork()) {
  2946. return ResolveResult::Retry();
  2947. }
  2948. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2949. // to add a new canonical int in this IR.
  2950. auto int_id = inst.int_id.is_embedded_value()
  2951. ? inst.int_id
  2952. : resolver.local_ints().AddSigned(
  2953. resolver.import_ints().Get(inst.int_id));
  2954. return ResolveResult::Deduplicated<SemIR::IntValue>(
  2955. resolver,
  2956. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  2957. .int_id = int_id});
  2958. }
  2959. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2960. SemIR::IntType inst) -> ResolveResult {
  2961. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2962. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2963. if (resolver.HasNewWork()) {
  2964. return ResolveResult::Retry();
  2965. }
  2966. return ResolveResult::Deduplicated<SemIR::IntType>(
  2967. resolver, {.type_id = SemIR::TypeType::TypeId,
  2968. .int_kind = inst.int_kind,
  2969. .bit_width_id = bit_width_id});
  2970. }
  2971. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2972. SemIR::Namespace inst,
  2973. SemIR::InstId import_inst_id) -> ResolveResult {
  2974. const auto& name_scope =
  2975. resolver.import_name_scopes().Get(inst.name_scope_id);
  2976. // A package from a different file becomes a child of the package here, as it
  2977. // would be if it were imported.
  2978. auto parent_scope_id =
  2979. inst.name_scope_id == SemIR::NameScopeId::Package
  2980. ? SemIR::NameScopeId::Package
  2981. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2982. if (resolver.HasNewWork()) {
  2983. return ResolveResult::Retry();
  2984. }
  2985. auto namespace_type_id = GetSingletonType(resolver.local_context(),
  2986. SemIR::NamespaceType::TypeInstId);
  2987. auto namespace_decl =
  2988. SemIR::Namespace{.type_id = namespace_type_id,
  2989. .name_scope_id = SemIR::NameScopeId::None,
  2990. .import_id = SemIR::AbsoluteInstId::None};
  2991. auto inst_id =
  2992. AddPlaceholderImportedInst(resolver, import_inst_id, namespace_decl);
  2993. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2994. namespace_decl.name_scope_id =
  2995. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2996. // Namespaces from this package are eagerly imported, so anything we load here
  2997. // must be a closed import.
  2998. resolver.local_name_scopes()
  2999. .Get(namespace_decl.name_scope_id)
  3000. .set_is_closed_import(true);
  3001. auto namespace_const_id =
  3002. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  3003. return {.const_id = namespace_const_id};
  3004. }
  3005. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3006. SemIR::PatternType inst) -> ResolveResult {
  3007. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3008. auto scrutinee_type_inst_id =
  3009. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  3010. if (resolver.HasNewWork()) {
  3011. return ResolveResult::Retry();
  3012. }
  3013. return ResolveResult::Deduplicated<SemIR::PatternType>(
  3014. resolver, {.type_id = SemIR::TypeType::TypeId,
  3015. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  3016. }
  3017. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3018. SemIR::PointerType inst) -> ResolveResult {
  3019. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3020. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  3021. if (resolver.HasNewWork()) {
  3022. return ResolveResult::Retry();
  3023. }
  3024. return ResolveResult::Deduplicated<SemIR::PointerType>(
  3025. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  3026. }
  3027. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3028. SemIR::RequireCompleteType inst)
  3029. -> ResolveResult {
  3030. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  3031. SemIR::WitnessType::TypeInstId);
  3032. auto complete_type_inst_id =
  3033. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  3034. if (resolver.HasNewWork()) {
  3035. return ResolveResult::Retry();
  3036. }
  3037. return ResolveResult::Deduplicated<SemIR::RequireCompleteType>(
  3038. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  3039. SemIR::WitnessType::TypeInstId),
  3040. .complete_type_inst_id = complete_type_inst_id});
  3041. }
  3042. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3043. SemIR::RequireSpecificDefinition inst)
  3044. -> ResolveResult {
  3045. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  3046. SemIR::RequireSpecificDefinitionType::TypeInstId);
  3047. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3048. if (resolver.HasNewWork()) {
  3049. return ResolveResult::Retry();
  3050. }
  3051. auto specific_id =
  3052. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3053. return ResolveResult::Deduplicated<SemIR::RequireSpecificDefinition>(
  3054. resolver, {.type_id = GetSingletonType(
  3055. resolver.local_context(),
  3056. SemIR::RequireSpecificDefinitionType::TypeInstId),
  3057. .specific_id = specific_id});
  3058. }
  3059. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3060. SemIR::ReturnSlotPattern inst,
  3061. SemIR::InstId import_inst_id) -> ResolveResult {
  3062. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3063. if (resolver.HasNewWork()) {
  3064. return ResolveResult::Retry();
  3065. }
  3066. return ResolveResult::Unique<SemIR::ReturnSlotPattern>(
  3067. resolver, import_inst_id,
  3068. {.type_id =
  3069. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3070. .type_inst_id = SemIR::TypeInstId::None});
  3071. }
  3072. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3073. SemIR::SpecificFunction inst) -> ResolveResult {
  3074. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3075. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3076. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3077. if (resolver.HasNewWork()) {
  3078. return ResolveResult::Retry();
  3079. }
  3080. auto type_id =
  3081. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id);
  3082. auto specific_id =
  3083. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3084. return ResolveResult::Deduplicated<SemIR::SpecificFunction>(
  3085. resolver,
  3086. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3087. }
  3088. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3089. SemIR::SpecificImplFunction inst)
  3090. -> ResolveResult {
  3091. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  3092. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  3093. if (resolver.HasNewWork()) {
  3094. return ResolveResult::Retry();
  3095. }
  3096. auto type_id = GetSingletonType(resolver.local_context(),
  3097. SemIR::SpecificFunctionType::TypeInstId);
  3098. auto specific_id =
  3099. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  3100. return ResolveResult::Deduplicated<SemIR::SpecificImplFunction>(
  3101. resolver,
  3102. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  3103. }
  3104. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3105. SemIR::StructAccess inst) -> ResolveResult {
  3106. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3107. auto struct_id = GetLocalConstantInstId(resolver, inst.struct_id);
  3108. if (resolver.HasNewWork()) {
  3109. return ResolveResult::Retry();
  3110. }
  3111. // A `struct_access` constant requires its struct operand to have a complete
  3112. // type.
  3113. CompleteTypeOrCheckFail(resolver.local_context(),
  3114. resolver.local_insts().Get(struct_id).type_id());
  3115. return ResolveResult::Deduplicated<SemIR::StructAccess>(
  3116. resolver,
  3117. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3118. .struct_id = struct_id,
  3119. .index = inst.index});
  3120. }
  3121. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3122. SemIR::StructType inst) -> ResolveResult {
  3123. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3124. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  3125. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  3126. field_type_inst_ids.reserve(orig_fields.size());
  3127. for (auto field : orig_fields) {
  3128. field_type_inst_ids.push_back(
  3129. GetLocalTypeInstId(resolver, field.type_inst_id));
  3130. }
  3131. if (resolver.HasNewWork()) {
  3132. return ResolveResult::Retry();
  3133. }
  3134. // Prepare a vector of fields for GetStructType.
  3135. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  3136. new_fields.reserve(orig_fields.size());
  3137. for (auto [orig_field, field_type_inst_id] :
  3138. llvm::zip_equal(orig_fields, field_type_inst_ids)) {
  3139. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  3140. new_fields.push_back(
  3141. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  3142. }
  3143. return ResolveResult::Deduplicated<SemIR::StructType>(
  3144. resolver, {.type_id = SemIR::TypeType::TypeId,
  3145. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  3146. new_fields)});
  3147. }
  3148. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3149. SemIR::StructValue inst) -> ResolveResult {
  3150. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3151. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3152. if (resolver.HasNewWork()) {
  3153. return ResolveResult::Retry();
  3154. }
  3155. return ResolveResult::Deduplicated<SemIR::StructValue>(
  3156. resolver,
  3157. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3158. .elements_id =
  3159. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3160. }
  3161. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3162. SemIR::SymbolicBindingType inst)
  3163. -> ResolveResult {
  3164. auto facet_value_inst_id =
  3165. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  3166. if (resolver.HasNewWork()) {
  3167. return ResolveResult::Retry();
  3168. }
  3169. auto entity_name_id =
  3170. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  3171. return ResolveResult::Deduplicated<SemIR::SymbolicBindingType>(
  3172. resolver, {.type_id = SemIR::TypeType::TypeId,
  3173. .entity_name_id = entity_name_id,
  3174. .facet_value_inst_id = facet_value_inst_id});
  3175. }
  3176. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3177. SemIR::TupleAccess inst) -> ResolveResult {
  3178. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3179. auto tuple_id = GetLocalConstantInstId(resolver, inst.tuple_id);
  3180. if (resolver.HasNewWork()) {
  3181. return ResolveResult::Retry();
  3182. }
  3183. // A `tuple_access` constant requires its struct operand to have a complete
  3184. // type.
  3185. CompleteTypeOrCheckFail(resolver.local_context(),
  3186. resolver.local_insts().Get(tuple_id).type_id());
  3187. return ResolveResult::Deduplicated<SemIR::TupleAccess>(
  3188. resolver,
  3189. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3190. .tuple_id = tuple_id,
  3191. .index = inst.index});
  3192. }
  3193. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3194. SemIR::TuplePattern inst,
  3195. SemIR::InstId import_inst_id) -> ResolveResult {
  3196. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3197. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  3198. if (resolver.HasNewWork()) {
  3199. return ResolveResult::Retry();
  3200. }
  3201. return ResolveResult::Unique<SemIR::TuplePattern>(
  3202. resolver, import_inst_id,
  3203. {.type_id =
  3204. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3205. .elements_id =
  3206. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements)});
  3207. }
  3208. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3209. SemIR::TupleType inst) -> ResolveResult {
  3210. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3211. auto orig_type_inst_ids =
  3212. resolver.import_inst_blocks().Get(inst.type_elements_id);
  3213. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  3214. // type system that its holding `TypeInstId` elements.
  3215. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  3216. type_inst_ids.reserve(orig_type_inst_ids.size());
  3217. for (auto elem_type_inst_id :
  3218. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  3219. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  3220. }
  3221. if (resolver.HasNewWork()) {
  3222. return ResolveResult::Retry();
  3223. }
  3224. return ResolveResult::Deduplicated<SemIR::TupleType>(
  3225. resolver, {.type_id = SemIR::TypeType::TypeId,
  3226. .type_elements_id = GetLocalCanonicalInstBlockId(
  3227. resolver, inst.type_elements_id, type_inst_ids)});
  3228. }
  3229. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3230. SemIR::TupleValue inst) -> ResolveResult {
  3231. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  3232. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  3233. if (resolver.HasNewWork()) {
  3234. return ResolveResult::Retry();
  3235. }
  3236. return ResolveResult::Deduplicated<SemIR::TupleValue>(
  3237. resolver,
  3238. {.type_id = resolver.local_types().GetTypeIdForTypeConstantId(type_id),
  3239. .elements_id =
  3240. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  3241. }
  3242. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3243. SemIR::UnboundElementType inst)
  3244. -> ResolveResult {
  3245. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  3246. auto class_const_inst_id =
  3247. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  3248. auto elem_const_inst_id =
  3249. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  3250. if (resolver.HasNewWork()) {
  3251. return ResolveResult::Retry();
  3252. }
  3253. return ResolveResult::Deduplicated<SemIR::UnboundElementType>(
  3254. resolver, {.type_id = SemIR::TypeType::TypeId,
  3255. .class_type_inst_id = class_const_inst_id,
  3256. .element_type_inst_id = elem_const_inst_id});
  3257. }
  3258. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3259. SemIR::VarPattern inst,
  3260. SemIR::InstId import_inst_id) -> ResolveResult {
  3261. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3262. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  3263. if (resolver.HasNewWork()) {
  3264. return ResolveResult::Retry();
  3265. }
  3266. return ResolveResult::Unique<SemIR::VarPattern>(
  3267. resolver, import_inst_id,
  3268. {.type_id =
  3269. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3270. .subpattern_id = subpattern_id});
  3271. }
  3272. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3273. SemIR::VarStorage inst,
  3274. SemIR::InstId import_inst_id) -> ResolveResult {
  3275. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3276. auto pattern_id = GetLocalConstantInstId(resolver, inst.pattern_id);
  3277. if (resolver.HasNewWork()) {
  3278. return ResolveResult::Retry();
  3279. }
  3280. return ResolveResult::Unique<SemIR::VarStorage>(
  3281. resolver, import_inst_id,
  3282. {.type_id =
  3283. resolver.local_types().GetTypeIdForTypeConstantId(type_const_id),
  3284. .pattern_id = pattern_id});
  3285. }
  3286. // Tries to resolve the InstId, returning a canonical constant when ready, or
  3287. // `None` if more has been added to the stack. This is the same as
  3288. // TryResolveInst, except that it may resolve symbolic constants as canonical
  3289. // constants instead of as constants associated with a particular generic.
  3290. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  3291. SemIR::InstId inst_id,
  3292. SemIR::ConstantId const_id)
  3293. -> ResolveResult {
  3294. // These instruction types are imported across multiple phases to arrive at
  3295. // their constant value. We can't just import their constant value instruction
  3296. // directly.
  3297. auto untyped_inst = resolver.import_insts().GetWithAttachedType(inst_id);
  3298. CARBON_KIND_SWITCH(untyped_inst) {
  3299. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  3300. return TryResolveTypedInst(resolver, inst, const_id);
  3301. }
  3302. case CARBON_KIND(SemIR::ClassDecl inst): {
  3303. return TryResolveTypedInst(resolver, inst, const_id);
  3304. }
  3305. case CARBON_KIND(SemIR::FunctionDecl inst): {
  3306. return TryResolveTypedInst(resolver, inst, const_id);
  3307. }
  3308. case CARBON_KIND(SemIR::ImplDecl inst): {
  3309. return TryResolveTypedInst(resolver, inst, const_id);
  3310. }
  3311. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  3312. return TryResolveTypedInst(resolver, inst, const_id);
  3313. }
  3314. case CARBON_KIND(SemIR::NamedConstraintDecl inst): {
  3315. return TryResolveTypedInst(resolver, inst, const_id);
  3316. }
  3317. case CARBON_KIND(SemIR::RequireImplsDecl inst): {
  3318. return TryResolveTypedInst(resolver, inst, const_id);
  3319. }
  3320. default:
  3321. break;
  3322. }
  3323. // Other instructions are imported in a single phase (once their dependencies
  3324. // are all imported).
  3325. CARBON_CHECK(!const_id.has_value());
  3326. auto inst_constant_id = resolver.import_constant_values().Get(inst_id);
  3327. if (!inst_constant_id.is_constant()) {
  3328. // TODO: Import of non-constant BindNames happens when importing `let`
  3329. // declarations.
  3330. CARBON_CHECK(resolver.import_insts().Is<SemIR::AnyBinding>(inst_id),
  3331. "TryResolveInst on non-constant instruction {0}", inst_id);
  3332. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  3333. }
  3334. // Import the canonical constant value instruction for `inst_id` directly. We
  3335. // don't try to import the non-canonical `inst_id`.
  3336. auto constant_inst_id =
  3337. resolver.import_constant_values().GetInstId(inst_constant_id);
  3338. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  3339. constant_inst_id) == constant_inst_id,
  3340. "Constant value of constant instruction should refer to "
  3341. "the same instruction");
  3342. if (SemIR::IsSingletonInstId(constant_inst_id)) {
  3343. // Constants for builtins can be directly copied.
  3344. return ResolveResult::Done(
  3345. resolver.local_constant_values().Get(constant_inst_id));
  3346. }
  3347. auto untyped_constant_inst =
  3348. resolver.import_insts().GetWithAttachedType(constant_inst_id);
  3349. CARBON_KIND_SWITCH(untyped_constant_inst) {
  3350. case CARBON_KIND(SemIR::AdaptDecl inst): {
  3351. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3352. }
  3353. case CARBON_KIND(SemIR::ArrayType inst): {
  3354. return TryResolveTypedInst(resolver, inst);
  3355. }
  3356. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  3357. return TryResolveTypedInst(resolver, inst);
  3358. }
  3359. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  3360. return TryResolveTypedInst(resolver, inst);
  3361. }
  3362. case CARBON_KIND(SemIR::BaseDecl inst): {
  3363. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3364. }
  3365. case CARBON_KIND(SemIR::AliasBinding inst): {
  3366. return TryResolveTypedInst(resolver, inst);
  3367. }
  3368. case CARBON_KIND(SemIR::SymbolicBinding inst): {
  3369. return TryResolveTypedInst(resolver, inst);
  3370. }
  3371. case CARBON_KIND(SemIR::BoolLiteral inst): {
  3372. return TryResolveTypedInst(resolver, inst);
  3373. }
  3374. case CARBON_KIND(SemIR::BoundMethod inst): {
  3375. return TryResolveTypedInst(resolver, inst);
  3376. }
  3377. case CARBON_KIND(SemIR::Call inst): {
  3378. return TryResolveTypedInst(resolver, inst);
  3379. }
  3380. case CARBON_KIND(SemIR::CharLiteralValue inst): {
  3381. return TryResolveTypedInst(resolver, inst);
  3382. }
  3383. case CARBON_KIND(SemIR::ClassType inst): {
  3384. return TryResolveTypedInst(resolver, inst);
  3385. }
  3386. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  3387. return TryResolveTypedInst(resolver, inst);
  3388. }
  3389. case CARBON_KIND(SemIR::ConstType inst): {
  3390. return TryResolveTypedInst(resolver, inst);
  3391. }
  3392. case CARBON_KIND(SemIR::CppOverloadSetType inst): {
  3393. return TryResolveTypedInst(resolver, inst);
  3394. }
  3395. case CARBON_KIND(SemIR::CppOverloadSetValue inst): {
  3396. return TryResolveTypedInst(resolver, inst);
  3397. }
  3398. case CARBON_KIND(SemIR::CustomWitness inst): {
  3399. return TryResolveTypedInst(resolver, inst);
  3400. }
  3401. case CARBON_KIND(SemIR::ExportDecl inst): {
  3402. return TryResolveTypedInst(resolver, inst);
  3403. }
  3404. case CARBON_KIND(SemIR::FacetAccessType inst): {
  3405. return TryResolveTypedInst(resolver, inst);
  3406. }
  3407. case CARBON_KIND(SemIR::FacetType inst): {
  3408. return TryResolveTypedInst(resolver, inst);
  3409. }
  3410. case CARBON_KIND(SemIR::FacetValue inst): {
  3411. return TryResolveTypedInst(resolver, inst);
  3412. }
  3413. case CARBON_KIND(SemIR::FieldDecl inst): {
  3414. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3415. }
  3416. case CARBON_KIND(SemIR::FloatLiteralValue inst): {
  3417. return TryResolveTypedInst(resolver, inst);
  3418. }
  3419. case CARBON_KIND(SemIR::FloatType inst): {
  3420. return TryResolveTypedInst(resolver, inst);
  3421. }
  3422. case CARBON_KIND(SemIR::FloatValue inst): {
  3423. return TryResolveTypedInst(resolver, inst);
  3424. }
  3425. case CARBON_KIND(SemIR::FunctionType inst): {
  3426. return TryResolveTypedInst(resolver, inst);
  3427. }
  3428. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  3429. return TryResolveTypedInst(resolver, inst);
  3430. }
  3431. case CARBON_KIND(SemIR::GenericClassType inst): {
  3432. return TryResolveTypedInst(resolver, inst);
  3433. }
  3434. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  3435. return TryResolveTypedInst(resolver, inst);
  3436. }
  3437. case CARBON_KIND(SemIR::GenericNamedConstraintType inst): {
  3438. return TryResolveTypedInst(resolver, inst);
  3439. }
  3440. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  3441. return TryResolveTypedInst(resolver, inst);
  3442. }
  3443. case CARBON_KIND(SemIR::ImplWitness inst): {
  3444. return TryResolveTypedInst(resolver, inst);
  3445. }
  3446. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  3447. return TryResolveTypedInst(resolver, inst);
  3448. }
  3449. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  3450. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3451. }
  3452. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  3453. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3454. }
  3455. case CARBON_KIND(SemIR::InitForm inst): {
  3456. return TryResolveTypedInst(resolver, inst);
  3457. }
  3458. case CARBON_KIND(SemIR::IntValue inst): {
  3459. return TryResolveTypedInst(resolver, inst);
  3460. }
  3461. case CARBON_KIND(SemIR::IntType inst): {
  3462. return TryResolveTypedInst(resolver, inst);
  3463. }
  3464. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  3465. return TryResolveTypedInst(resolver, inst);
  3466. }
  3467. case CARBON_KIND(SemIR::Namespace inst): {
  3468. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3469. }
  3470. case CARBON_KIND(SemIR::OutParamPattern inst): {
  3471. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3472. }
  3473. case CARBON_KIND(SemIR::PartialType inst): {
  3474. return TryResolveTypedInst(resolver, inst);
  3475. }
  3476. case CARBON_KIND(SemIR::PatternType inst): {
  3477. return TryResolveTypedInst(resolver, inst);
  3478. }
  3479. case CARBON_KIND(SemIR::PointerType inst): {
  3480. return TryResolveTypedInst(resolver, inst);
  3481. }
  3482. case CARBON_KIND(SemIR::RefBindingPattern inst): {
  3483. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3484. }
  3485. case CARBON_KIND(SemIR::RefParamPattern inst): {
  3486. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3487. }
  3488. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  3489. return TryResolveTypedInst(resolver, inst);
  3490. }
  3491. case CARBON_KIND(SemIR::RequireSpecificDefinition inst): {
  3492. return TryResolveTypedInst(resolver, inst);
  3493. }
  3494. case CARBON_KIND(SemIR::ReturnSlotPattern inst): {
  3495. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3496. }
  3497. case CARBON_KIND(SemIR::SpecificFunction inst): {
  3498. return TryResolveTypedInst(resolver, inst);
  3499. }
  3500. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  3501. return TryResolveTypedInst(resolver, inst);
  3502. }
  3503. case CARBON_KIND(SemIR::StructAccess inst): {
  3504. return TryResolveTypedInst(resolver, inst);
  3505. }
  3506. case CARBON_KIND(SemIR::StructType inst): {
  3507. return TryResolveTypedInst(resolver, inst);
  3508. }
  3509. case CARBON_KIND(SemIR::StructValue inst): {
  3510. return TryResolveTypedInst(resolver, inst);
  3511. }
  3512. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  3513. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3514. }
  3515. case CARBON_KIND(SemIR::SymbolicBindingType inst): {
  3516. return TryResolveTypedInst(resolver, inst);
  3517. }
  3518. case CARBON_KIND(SemIR::TupleAccess inst): {
  3519. return TryResolveTypedInst(resolver, inst);
  3520. }
  3521. case CARBON_KIND(SemIR::TuplePattern inst): {
  3522. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3523. }
  3524. case CARBON_KIND(SemIR::TupleType inst): {
  3525. return TryResolveTypedInst(resolver, inst);
  3526. }
  3527. case CARBON_KIND(SemIR::TupleValue inst): {
  3528. return TryResolveTypedInst(resolver, inst);
  3529. }
  3530. case CARBON_KIND(SemIR::UnboundElementType inst): {
  3531. return TryResolveTypedInst(resolver, inst);
  3532. }
  3533. case CARBON_KIND(SemIR::ValueBindingPattern inst): {
  3534. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3535. }
  3536. case CARBON_KIND(SemIR::ValueParamPattern inst): {
  3537. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3538. }
  3539. case CARBON_KIND(SemIR::VarParamPattern inst): {
  3540. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3541. }
  3542. case CARBON_KIND(SemIR::VarPattern inst): {
  3543. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3544. }
  3545. case CARBON_KIND(SemIR::VarStorage inst): {
  3546. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3547. }
  3548. case CARBON_KIND(SemIR::VtableDecl inst): {
  3549. return TryResolveTypedInst(resolver, inst);
  3550. }
  3551. case CARBON_KIND(SemIR::VtablePtr inst): {
  3552. return TryResolveTypedInst(resolver, inst);
  3553. }
  3554. default:
  3555. // Found a canonical instruction which needs to be resolved, but which is
  3556. // not yet handled.
  3557. //
  3558. // TODO: Could we turn this into a compile-time error?
  3559. CARBON_FATAL(
  3560. "Missing case in TryResolveInstCanonical for instruction kind {0}",
  3561. untyped_constant_inst.kind());
  3562. }
  3563. }
  3564. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  3565. // more has been added to the stack. A similar API is followed for all
  3566. // following TryResolveTypedInst helper functions.
  3567. //
  3568. // `const_id` is `None` unless we've tried to resolve this instruction
  3569. // before, in which case it's the previous result.
  3570. //
  3571. // TODO: Error is returned when support is missing, but that should go away.
  3572. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  3573. SemIR::ConstantId const_id) -> ResolveResult {
  3574. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  3575. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  3576. return TryResolveInstCanonical(resolver, inst_id, const_id);
  3577. }
  3578. // Try to import the generic. This might add new work.
  3579. const auto& symbolic_const =
  3580. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  3581. auto generic_const_id =
  3582. GetLocalConstantId(resolver, symbolic_const.generic_id);
  3583. auto inner_const_id = SemIR::ConstantId::None;
  3584. if (const_id.has_value()) {
  3585. // For the third phase, extract the constant value that
  3586. // TryResolveInstCanonical produced previously.
  3587. inner_const_id = resolver.local_constant_values().GetAttached(
  3588. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  3589. }
  3590. // Import the constant and rebuild the symbolic constant data.
  3591. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  3592. if (!result.const_id.has_value()) {
  3593. // First phase: TryResolveInstCanoncial needs a retry.
  3594. return result;
  3595. }
  3596. if (!const_id.has_value()) {
  3597. // Second phase: we have created an unattached constant. Create a
  3598. // corresponding attached constant.
  3599. if (symbolic_const.generic_id.has_value()) {
  3600. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  3601. {.inst_id =
  3602. resolver.local_constant_values().GetInstId(result.const_id),
  3603. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  3604. .index = symbolic_const.index,
  3605. .dependence = symbolic_const.dependence});
  3606. if (result.decl_id.has_value()) {
  3607. // Overwrite the unattached symbolic constant given initially to the
  3608. // declaration with its final attached symbolic value.
  3609. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  3610. }
  3611. }
  3612. } else {
  3613. // Third phase: perform a consistency check and produce the constant we
  3614. // created in the second phase.
  3615. CARBON_CHECK(result.const_id == inner_const_id,
  3616. "Constant value changed in third phase.");
  3617. result.const_id = const_id;
  3618. }
  3619. return result;
  3620. }
  3621. auto ImportRefResolver::Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  3622. work_stack_.push_back(InstWork{.inst_id = inst_id});
  3623. while (!work_stack_.empty()) {
  3624. auto work_variant = work_stack_.back();
  3625. CARBON_KIND_SWITCH(work_variant) {
  3626. case CARBON_KIND(InstWork work): {
  3627. CARBON_CHECK(work.inst_id.has_value());
  3628. // Step 1: check for a constant value.
  3629. auto existing = FindResolvedConstId(work.inst_id);
  3630. if (existing.const_id.has_value() && !work.retry_with_constant_value) {
  3631. work_stack_.pop_back();
  3632. continue;
  3633. }
  3634. // Step 2: resolve the instruction.
  3635. initial_work_ = work_stack_.size();
  3636. auto result = TryResolveInst(*this, work.inst_id, existing.const_id);
  3637. CARBON_CHECK(!HasNewWork() || result.retry);
  3638. CARBON_CHECK(!existing.const_id.has_value() ||
  3639. existing.const_id == result.const_id,
  3640. "Constant value changed in third phase.");
  3641. if (!existing.const_id.has_value()) {
  3642. SetResolvedConstId(work.inst_id, existing.indirect_insts,
  3643. result.const_id);
  3644. }
  3645. // Step 3: pop or retry.
  3646. if (result.retry) {
  3647. std::get<InstWork>(work_stack_[initial_work_ - 1])
  3648. .retry_with_constant_value = result.const_id.has_value();
  3649. } else {
  3650. work_stack_.pop_back();
  3651. if (result.import_generic_id.has_value()) {
  3652. work_stack_.push_back(
  3653. GenericWork{.import_id = result.import_generic_id,
  3654. .local_id = result.local_generic_id});
  3655. }
  3656. }
  3657. break;
  3658. }
  3659. case CARBON_KIND(GenericWork generic_work): {
  3660. // Generics may require 2 steps to finish, similar to step 2 and step 3
  3661. // of instructions.
  3662. initial_work_ = work_stack_.size();
  3663. if (TryFinishGeneric(*this, generic_work.import_id,
  3664. generic_work.local_id)) {
  3665. work_stack_.pop_back();
  3666. }
  3667. break;
  3668. }
  3669. case CARBON_KIND(SpecificWork specific_work): {
  3670. // Specifics may require 2 steps to finish, similar to step 2 and step 3
  3671. // of instructions.
  3672. initial_work_ = work_stack_.size();
  3673. if (TryFinishSpecific(*this, specific_work.import_id,
  3674. specific_work.local_id)) {
  3675. work_stack_.pop_back();
  3676. }
  3677. break;
  3678. }
  3679. }
  3680. }
  3681. auto constant_id =
  3682. local_constant_values_for_import_insts().GetAttached(inst_id);
  3683. CARBON_CHECK(constant_id.has_value());
  3684. return constant_id;
  3685. }
  3686. auto ImportRefResolver::ResolveConstant(SemIR::ConstantId import_const_id)
  3687. -> SemIR::ConstantId {
  3688. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  3689. }
  3690. auto ImportRefResolver::ResolveType(SemIR::TypeId import_type_id)
  3691. -> SemIR::TypeId {
  3692. if (!import_type_id.has_value()) {
  3693. return import_type_id;
  3694. }
  3695. auto import_type_const_id = import_ir().types().GetConstantId(import_type_id);
  3696. CARBON_CHECK(import_type_const_id.has_value());
  3697. if (auto import_type_inst_id = import_ir().types().GetAsTypeInstId(
  3698. import_ir().constant_values().GetInstId(import_type_const_id));
  3699. SemIR::IsSingletonInstId(import_type_inst_id)) {
  3700. // Builtins don't require constant resolution; we can use them directly.
  3701. return GetSingletonType(local_context(), import_type_inst_id);
  3702. } else {
  3703. return local_types().GetTypeIdForTypeConstantId(
  3704. ResolveConstant(import_type_id.AsConstantId()));
  3705. }
  3706. }
  3707. auto ImportRefResolver::HasNewWork() -> bool {
  3708. CARBON_CHECK(initial_work_ <= work_stack_.size(), "Work shouldn't decrease");
  3709. return initial_work_ < work_stack_.size();
  3710. }
  3711. auto ImportRefResolver::PushSpecific(SemIR::SpecificId import_id,
  3712. SemIR::SpecificId local_id) -> void {
  3713. // Insert before the current instruction.
  3714. work_stack_.insert(
  3715. work_stack_.begin() + initial_work_ - 1,
  3716. SpecificWork{.import_id = import_id, .local_id = local_id});
  3717. ++initial_work_;
  3718. }
  3719. auto ImportRefResolver::GetLocalConstantValueOrPush(SemIR::InstId inst_id)
  3720. -> SemIR::ConstantId {
  3721. if (!inst_id.has_value()) {
  3722. return SemIR::ConstantId::None;
  3723. }
  3724. auto const_id = local_constant_values_for_import_insts().GetAttached(inst_id);
  3725. if (!const_id.has_value()) {
  3726. work_stack_.push_back(InstWork{.inst_id = inst_id});
  3727. }
  3728. return const_id;
  3729. }
  3730. auto ImportRefResolver::FindResolvedConstId(SemIR::InstId inst_id)
  3731. -> ResolvedConstId {
  3732. ResolvedConstId result;
  3733. if (auto existing_const_id =
  3734. local_constant_values_for_import_insts().GetAttached(inst_id);
  3735. existing_const_id.has_value()) {
  3736. result.const_id = existing_const_id;
  3737. return result;
  3738. }
  3739. const auto* cursor_ir = &import_ir();
  3740. auto cursor_inst_id = inst_id;
  3741. while (true) {
  3742. auto import_ir_inst_id = cursor_ir->insts().GetImportSource(cursor_inst_id);
  3743. if (!import_ir_inst_id.has_value()) {
  3744. return result;
  3745. }
  3746. auto ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
  3747. if (ir_inst.ir_id() == SemIR::ImportIRId::Cpp) {
  3748. local_context().TODO(SemIR::LocId::None,
  3749. "Unsupported: Importing C++ indirectly");
  3750. SetResolvedConstId(inst_id, result.indirect_insts,
  3751. SemIR::ErrorInst::ConstantId);
  3752. result.const_id = SemIR::ErrorInst::ConstantId;
  3753. result.indirect_insts.clear();
  3754. return result;
  3755. }
  3756. const auto* prev_ir = cursor_ir;
  3757. auto prev_inst_id = cursor_inst_id;
  3758. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id()).sem_ir;
  3759. auto cursor_ir_id =
  3760. AddImportIR(local_context(), {.decl_id = SemIR::InstId::None,
  3761. .is_export = false,
  3762. .sem_ir = cursor_ir});
  3763. cursor_inst_id = ir_inst.inst_id();
  3764. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id, "{0}",
  3765. cursor_ir->insts().Get(cursor_inst_id));
  3766. if (auto const_id =
  3767. local_context()
  3768. .import_ir_constant_values()
  3769. [local_ir().import_irs().GetRawIndex(cursor_ir_id)]
  3770. .GetAttached(cursor_inst_id);
  3771. const_id.has_value()) {
  3772. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  3773. result.const_id = const_id;
  3774. result.indirect_insts.clear();
  3775. return result;
  3776. } else {
  3777. result.indirect_insts.push_back(
  3778. SemIR::ImportIRInst(cursor_ir_id, cursor_inst_id));
  3779. }
  3780. }
  3781. }
  3782. auto ImportRefResolver::SetResolvedConstId(
  3783. SemIR::InstId inst_id, llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  3784. SemIR::ConstantId const_id) -> void {
  3785. local_constant_values_for_import_insts().Set(inst_id, const_id);
  3786. SetIndirectConstantValues(local_context(), indirect_insts, const_id);
  3787. }
  3788. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  3789. // loaded (including the one pointed at directly by the ImportRef), and the
  3790. // final instruction's type ID.
  3791. //
  3792. // This addresses cases where an ImportRefUnloaded may point at another
  3793. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  3794. // constant-evaluated version of the instruction to work with.
  3795. static auto GetInstForLoad(Context& context,
  3796. SemIR::ImportIRInstId import_ir_inst_id)
  3797. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  3798. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  3799. {}, SemIR::TypeId::None};
  3800. auto& [import_ir_insts, type_id] = result;
  3801. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  3802. // The first ImportIRInst is added directly because the IR doesn't need to be
  3803. // localized.
  3804. import_ir_insts.push_back(import_ir_inst);
  3805. const auto* cursor_ir =
  3806. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3807. while (true) {
  3808. auto cursor_inst =
  3809. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  3810. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  3811. if (!import_ref) {
  3812. type_id = cursor_inst.type_id();
  3813. return result;
  3814. }
  3815. import_ir_inst =
  3816. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  3817. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3818. import_ir_insts.push_back(SemIR::ImportIRInst(
  3819. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  3820. .is_export = false,
  3821. .sem_ir = cursor_ir}),
  3822. import_ir_inst.inst_id()));
  3823. }
  3824. }
  3825. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  3826. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  3827. if (!inst) {
  3828. return;
  3829. }
  3830. auto [indirect_insts, load_type_id] =
  3831. GetInstForLoad(context, inst->import_ir_inst_id);
  3832. // The last indirect instruction is the one to resolve. Pop it here because
  3833. // Resolve will assign the constant.
  3834. auto load_ir_inst = indirect_insts.pop_back_val();
  3835. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  3836. // Loading an import ref creates local constants from the import ones, but
  3837. // shouldn't be generating novel instructions in the semir as a side effect of
  3838. // that process. Doing so in a generic context would also cause them to end up
  3839. // in the eval block, which would be doubly wrong.
  3840. context.inst_block_stack().Push();
  3841. auto type_id = resolver.ResolveType(load_type_id);
  3842. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  3843. CARBON_CHECK(
  3844. context.inst_block_stack().PeekCurrentBlockContents().empty(),
  3845. "Importing an instruction shouldn't add new instructions to the "
  3846. "local inst block. Found {0} new instructions, first is {1}: {2}.",
  3847. context.inst_block_stack().PeekCurrentBlockContents().size(),
  3848. context.inst_block_stack().PeekCurrentBlockContents().front(),
  3849. context.insts().Get(
  3850. context.inst_block_stack().PeekCurrentBlockContents().front()));
  3851. context.inst_block_stack().PopAndDiscard();
  3852. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  3853. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  3854. // TryEvalInst, which we want to avoid with ImportRefs.
  3855. context.sem_ir().insts().Set(
  3856. inst_id,
  3857. SemIR::ImportRefLoaded{.type_id = type_id,
  3858. .import_ir_inst_id = inst->import_ir_inst_id,
  3859. .entity_name_id = inst->entity_name_id});
  3860. // Store the constant for both the ImportRefLoaded and indirect instructions.
  3861. context.constant_values().Set(inst_id, constant_id);
  3862. SetIndirectConstantValues(context, indirect_insts, constant_id);
  3863. }
  3864. auto ImportImplsFromApiFile(Context& context) -> void {
  3865. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  3866. auto& import_ir = context.import_irs().Get(import_ir_id);
  3867. if (!import_ir.sem_ir) {
  3868. return;
  3869. }
  3870. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  3871. // Resolve the imported impl to a local impl ID.
  3872. ImportImpl(context, import_ir_id, impl_id);
  3873. }
  3874. }
  3875. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  3876. SemIR::ImplId impl_id) -> void {
  3877. ImportRefResolver resolver(&context, import_ir_id);
  3878. resolver.Resolve(resolver.import_impls().Get(impl_id).first_decl_id());
  3879. }
  3880. auto ImportInterface(Context& context, SemIR::ImportIRId import_ir_id,
  3881. SemIR::InterfaceId interface_id) -> SemIR::InterfaceId {
  3882. ImportRefResolver resolver(&context, import_ir_id);
  3883. auto local_id = resolver.Resolve(
  3884. resolver.import_interfaces().Get(interface_id).first_decl_id());
  3885. auto local_inst =
  3886. context.insts().Get(context.constant_values().GetInstId(local_id));
  3887. // A non-generic interface will import as a facet type for that single
  3888. // interface.
  3889. if (auto facet_type = local_inst.TryAs<SemIR::FacetType>()) {
  3890. auto single = context.facet_types()
  3891. .Get(facet_type->facet_type_id)
  3892. .TryAsSingleExtend();
  3893. CARBON_CHECK(single,
  3894. "Importing an interface didn't produce a single interface");
  3895. return std::get<SemIR::SpecificInterface>(*single).interface_id;
  3896. }
  3897. // A generic interface will import as a constant of generic interface type.
  3898. auto generic_interface_type =
  3899. context.types().GetAs<SemIR::GenericInterfaceType>(local_inst.type_id());
  3900. return generic_interface_type.interface_id;
  3901. }
  3902. } // namespace Carbon::Check