import_ref.cpp 137 KB

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