import_ref.cpp 132 KB

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