import_ref.cpp 161 KB

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