import_ref.cpp 139 KB

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