import_ref.cpp 130 KB

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