import_ref.cpp 142 KB

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