import_ref.cpp 173 KB

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