import_ref.cpp 179 KB

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