import_ref.cpp 137 KB

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