import_ref.cpp 198 KB

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