import_ref.cpp 153 KB

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