import_ref.cpp 151 KB

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