import_ref.cpp 138 KB

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