import_ref.cpp 135 KB

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