import_ref.cpp 135 KB

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