import_ref.cpp 171 KB

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