import_ref.cpp 143 KB

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