import_ref.cpp 150 KB

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