import_ref.cpp 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291
  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. pattern_id = resolver.import_insts()
  867. .GetAs<SemIR::ValueParamPattern>(pattern_id)
  868. .subpattern_id;
  869. pattern_inst = resolver.import_insts().Get(pattern_id);
  870. // If the parameter is a symbolic binding, build the
  871. // SymbolicBindingPattern constant.
  872. if (pattern_inst.Is<SemIR::SymbolicBindingPattern>()) {
  873. GetLocalConstantId(resolver, pattern_id);
  874. }
  875. }
  876. }
  877. // Returns a version of param_patterns_id localized to the current IR.
  878. //
  879. // Must only be called after a call to
  880. // LoadLocalPatternConstantIds(param_patterns_id) has completed without adding
  881. // any new work to work_stack_.
  882. //
  883. // TODO: This is inconsistent with the rest of this class, which expects
  884. // the relevant constants to be explicitly passed in. That makes it
  885. // easier to statically detect when an input isn't loaded, but makes it
  886. // harder to support importing more complex inst structures. We should
  887. // take a holistic look at how to balance those concerns. For example,
  888. // could the same function be used to load the constants and use them, with
  889. // a parameter to select between the two?
  890. //
  891. // `self_param_id` is an optional out parameter, populated with the InstId in
  892. // the resulting parameter patterns that represents the Self parameter.
  893. static auto GetLocalParamPatternsId(ImportContext& context,
  894. SemIR::InstBlockId param_patterns_id,
  895. SemIR::InstId* self_param_id = nullptr)
  896. -> SemIR::InstBlockId {
  897. CARBON_CHECK(!self_param_id || !self_param_id->has_value());
  898. if (!param_patterns_id.has_value() ||
  899. param_patterns_id == SemIR::InstBlockId::Empty) {
  900. return param_patterns_id;
  901. }
  902. const auto& param_patterns =
  903. context.import_inst_blocks().Get(param_patterns_id);
  904. llvm::SmallVector<SemIR::InstId> new_patterns;
  905. for (auto param_id : param_patterns) {
  906. // Figure out the pattern structure. This echoes
  907. // Function::GetParamPatternInfoFromPatternId.
  908. auto addr_pattern_id = param_id;
  909. auto addr_inst =
  910. context.import_insts().TryGetAs<SemIR::AddrPattern>(addr_pattern_id);
  911. auto param_pattern_id = addr_pattern_id;
  912. if (addr_inst) {
  913. param_pattern_id = addr_inst->inner_id;
  914. }
  915. auto param_pattern = context.import_insts().GetAs<SemIR::ValueParamPattern>(
  916. param_pattern_id);
  917. auto binding_id = param_pattern.subpattern_id;
  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. new_param_id = AddInstInNoBlock(
  955. context.local_context(),
  956. MakeImportedLocIdAndInst<SemIR::ValueParamPattern>(
  957. context.local_context(), AddImportIRInst(context, param_pattern_id),
  958. {.type_id = type_id,
  959. .subpattern_id = new_param_id,
  960. .runtime_index = param_pattern.runtime_index}));
  961. if (addr_inst) {
  962. type_id = context.local_context().types().GetTypeIdForTypeConstantId(
  963. GetLocalConstantIdChecked(context, addr_inst->type_id));
  964. new_param_id =
  965. AddInstInNoBlock(context.local_context(),
  966. MakeImportedLocIdAndInst<SemIR::AddrPattern>(
  967. context.local_context(),
  968. AddImportIRInst(context, addr_pattern_id),
  969. {.type_id = type_id, .inner_id = new_param_id}));
  970. }
  971. if (self_param_id &&
  972. context.import_entity_names().Get(binding.entity_name_id).name_id ==
  973. SemIR::NameId::SelfValue) {
  974. *self_param_id = new_param_id;
  975. }
  976. new_patterns.push_back(new_param_id);
  977. }
  978. return context.local_inst_blocks().Add(new_patterns);
  979. }
  980. // Returns a version of import_return_slot_pattern_id localized to the current
  981. // IR.
  982. static auto GetLocalReturnSlotPatternId(
  983. ImportContext& context, SemIR::InstId import_return_slot_pattern_id)
  984. -> SemIR::InstId {
  985. if (!import_return_slot_pattern_id.has_value()) {
  986. return SemIR::InstId::None;
  987. }
  988. auto param_pattern = context.import_insts().GetAs<SemIR::OutParamPattern>(
  989. import_return_slot_pattern_id);
  990. auto return_slot_pattern =
  991. context.import_insts().GetAs<SemIR::ReturnSlotPattern>(
  992. param_pattern.subpattern_id);
  993. auto type_id = context.local_context().types().GetTypeIdForTypeConstantId(
  994. GetLocalConstantIdChecked(context, return_slot_pattern.type_id));
  995. auto new_return_slot_pattern_id = AddInstInNoBlock(
  996. context.local_context(),
  997. MakeImportedLocIdAndInst<SemIR::ReturnSlotPattern>(
  998. context.local_context(),
  999. AddImportIRInst(context, param_pattern.subpattern_id),
  1000. {.type_id = type_id, .type_inst_id = SemIR::InstId::None}));
  1001. return AddInstInNoBlock(
  1002. context.local_context(),
  1003. MakeImportedLocIdAndInst<SemIR::OutParamPattern>(
  1004. context.local_context(),
  1005. AddImportIRInst(context, import_return_slot_pattern_id),
  1006. {.type_id = type_id,
  1007. .subpattern_id = new_return_slot_pattern_id,
  1008. .runtime_index = param_pattern.runtime_index}));
  1009. }
  1010. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  1011. // unresolved constants to the resolver's work stack.
  1012. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  1013. SemIR::NameScopeId name_scope_id)
  1014. -> SemIR::NameScopeId {
  1015. // Get the instruction that created the scope.
  1016. auto [inst_id, inst] =
  1017. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  1018. if (!inst) {
  1019. // Map scopes that aren't associated with an instruction to `None`. For now,
  1020. // such scopes aren't used, and we don't have a good way to remap them.
  1021. return SemIR::NameScopeId::None;
  1022. }
  1023. // Get the constant value for the scope.
  1024. auto const_id = GetLocalConstantId(resolver, inst_id);
  1025. if (!const_id.has_value()) {
  1026. return SemIR::NameScopeId::None;
  1027. }
  1028. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  1029. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  1030. CARBON_KIND_SWITCH(name_scope_inst) {
  1031. case CARBON_KIND(SemIR::Namespace inst): {
  1032. return inst.name_scope_id;
  1033. }
  1034. case CARBON_KIND(SemIR::ClassType inst): {
  1035. return resolver.local_classes().Get(inst.class_id).scope_id;
  1036. }
  1037. case CARBON_KIND(SemIR::FacetType inst): {
  1038. const SemIR::FacetTypeInfo& facet_type_info =
  1039. resolver.local_facet_types().Get(inst.facet_type_id);
  1040. // This is specifically the facet type produced by an interface
  1041. // declaration, and so should consist of a single interface.
  1042. // TODO: Will also have to handle named constraints here, once those are
  1043. // implemented.
  1044. auto interface = facet_type_info.TryAsSingleInterface();
  1045. CARBON_CHECK(interface);
  1046. return resolver.local_interfaces().Get(interface->interface_id).scope_id;
  1047. }
  1048. case CARBON_KIND(SemIR::ImplDecl inst): {
  1049. return resolver.local_impls().Get(inst.impl_id).scope_id;
  1050. }
  1051. case SemIR::StructValue::Kind: {
  1052. auto type_inst =
  1053. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  1054. CARBON_KIND_SWITCH(type_inst) {
  1055. case CARBON_KIND(SemIR::GenericClassType inst): {
  1056. return resolver.local_classes().Get(inst.class_id).scope_id;
  1057. }
  1058. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  1059. return resolver.local_interfaces().Get(inst.interface_id).scope_id;
  1060. }
  1061. default: {
  1062. break;
  1063. }
  1064. }
  1065. break;
  1066. }
  1067. default: {
  1068. if (const_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1069. return SemIR::NameScopeId::None;
  1070. }
  1071. break;
  1072. }
  1073. }
  1074. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  1075. name_scope_inst);
  1076. }
  1077. // Given an imported entity base, returns an incomplete, local version of it.
  1078. //
  1079. // Most fields are set in the third phase once they're imported. Import enough
  1080. // of the parameter lists that we know whether this interface is a generic
  1081. // interface and can build the right constant value for it.
  1082. //
  1083. // TODO: Support extern.
  1084. static auto GetIncompleteLocalEntityBase(
  1085. ImportContext& context, SemIR::InstId decl_id,
  1086. const SemIR::EntityWithParamsBase& import_base)
  1087. -> SemIR::EntityWithParamsBase {
  1088. // Translate the extern_library_id if present.
  1089. auto extern_library_id = SemIR::LibraryNameId::None;
  1090. if (import_base.extern_library_id.has_value()) {
  1091. if (import_base.extern_library_id.index >= 0) {
  1092. auto val = context.import_string_literal_values().Get(
  1093. import_base.extern_library_id.AsStringLiteralValueId());
  1094. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  1095. context.local_string_literal_values().Add(val));
  1096. } else {
  1097. extern_library_id = import_base.extern_library_id;
  1098. }
  1099. }
  1100. return {
  1101. .name_id = GetLocalNameId(context, import_base.name_id),
  1102. .parent_scope_id = SemIR::NameScopeId::None,
  1103. .generic_id =
  1104. MakeIncompleteGeneric(context, decl_id, import_base.generic_id),
  1105. .first_param_node_id = Parse::NodeId::None,
  1106. .last_param_node_id = Parse::NodeId::None,
  1107. .pattern_block_id = SemIR::InstBlockId::None,
  1108. .implicit_param_patterns_id =
  1109. import_base.implicit_param_patterns_id.has_value()
  1110. ? SemIR::InstBlockId::Empty
  1111. : SemIR::InstBlockId::None,
  1112. .param_patterns_id = import_base.param_patterns_id.has_value()
  1113. ? SemIR::InstBlockId::Empty
  1114. : SemIR::InstBlockId::None,
  1115. .call_params_id = SemIR::InstBlockId::None,
  1116. .is_extern = import_base.is_extern,
  1117. .extern_library_id = extern_library_id,
  1118. .non_owning_decl_id = import_base.non_owning_decl_id.has_value()
  1119. ? decl_id
  1120. : SemIR::InstId::None,
  1121. .first_owning_decl_id = import_base.first_owning_decl_id.has_value()
  1122. ? decl_id
  1123. : SemIR::InstId::None,
  1124. };
  1125. }
  1126. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1127. // lookup.
  1128. static auto AddNameScopeImportRefs(ImportContext& context,
  1129. const SemIR::NameScope& import_scope,
  1130. SemIR::NameScope& new_scope) -> void {
  1131. for (auto entry : import_scope.entries()) {
  1132. SemIR::ScopeLookupResult result = entry.result;
  1133. if (result.is_poisoned()) {
  1134. continue;
  1135. }
  1136. auto ref_id = AddImportRef(context, result.target_inst_id());
  1137. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1138. .result = SemIR::ScopeLookupResult::MakeFound(
  1139. ref_id, result.access_kind())});
  1140. }
  1141. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1142. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1143. }
  1144. }
  1145. // Given a block ID for a list of associated entities of a witness, returns a
  1146. // version localized to the current IR.
  1147. static auto AddAssociatedEntities(ImportContext& context,
  1148. SemIR::NameScopeId local_name_scope_id,
  1149. SemIR::InstBlockId associated_entities_id)
  1150. -> SemIR::InstBlockId {
  1151. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1152. return SemIR::InstBlockId::Empty;
  1153. }
  1154. auto associated_entities =
  1155. context.import_inst_blocks().Get(associated_entities_id);
  1156. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1157. new_associated_entities.reserve(associated_entities.size());
  1158. for (auto inst_id : associated_entities) {
  1159. // Determine the name of the associated entity, by switching on its kind.
  1160. SemIR::NameId import_name_id = SemIR::NameId::None;
  1161. if (auto assoc_const_decl =
  1162. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1163. inst_id)) {
  1164. const auto& assoc_const = context.import_associated_constants().Get(
  1165. assoc_const_decl->assoc_const_id);
  1166. import_name_id = assoc_const.name_id;
  1167. } else if (auto function_decl =
  1168. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1169. inst_id)) {
  1170. const auto& function =
  1171. context.import_functions().Get(function_decl->function_id);
  1172. import_name_id = function.name_id;
  1173. } else if (auto import_ref =
  1174. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1175. inst_id)) {
  1176. import_name_id =
  1177. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1178. } else {
  1179. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1180. context.import_insts().Get(inst_id).kind());
  1181. }
  1182. auto name_id = GetLocalNameId(context, import_name_id);
  1183. auto entity_name_id = context.local_entity_names().Add(
  1184. {.name_id = name_id, .parent_scope_id = local_name_scope_id});
  1185. new_associated_entities.push_back(
  1186. AddImportRef(context, inst_id, entity_name_id));
  1187. }
  1188. return context.local_inst_blocks().Add(new_associated_entities);
  1189. }
  1190. // Produces a resolve result that provides the given constant value. Retries
  1191. // instead if work has been added.
  1192. static auto RetryOrDone(ImportRefResolver& resolver, SemIR::ConstantId const_id)
  1193. -> ResolveResult {
  1194. if (resolver.HasNewWork()) {
  1195. return ResolveResult::Retry();
  1196. }
  1197. return ResolveResult::Done(const_id);
  1198. }
  1199. // Produces a resolve result for the given instruction that describes a constant
  1200. // value. This should only be used for instructions that describe constants, and
  1201. // not for instructions that represent declarations. For a declaration, we need
  1202. // an associated location, so AddInstInNoBlock should be used instead. Requires
  1203. // that there is no new work.
  1204. static auto ResolveAsUntyped(ImportContext& context, SemIR::Inst inst)
  1205. -> ResolveResult {
  1206. auto result = TryEvalInst(context.local_context(), SemIR::InstId::None, inst);
  1207. CARBON_CHECK(result.is_constant(), "{0} is not constant", inst);
  1208. return ResolveResult::Done(result);
  1209. }
  1210. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1211. template <typename InstT>
  1212. static auto ResolveAs(ImportContext& context, InstT inst) -> ResolveResult {
  1213. return ResolveAsUntyped(context, inst);
  1214. }
  1215. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1216. SemIR::AdaptDecl inst,
  1217. SemIR::InstId import_inst_id) -> ResolveResult {
  1218. auto adapted_type_const_id = GetLocalConstantId(
  1219. resolver,
  1220. resolver.import_constant_values().Get(inst.adapted_type_inst_id));
  1221. if (resolver.HasNewWork()) {
  1222. return ResolveResult::Retry();
  1223. }
  1224. auto adapted_type_inst_id =
  1225. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1226. inst.adapted_type_inst_id, adapted_type_const_id);
  1227. // Create a corresponding instruction to represent the declaration.
  1228. auto inst_id = AddInstInNoBlock(
  1229. resolver.local_context(),
  1230. MakeImportedLocIdAndInst<SemIR::AdaptDecl>(
  1231. resolver.local_context(), AddImportIRInst(resolver, import_inst_id),
  1232. {.adapted_type_inst_id = adapted_type_inst_id}));
  1233. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1234. inst_id);
  1235. }
  1236. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1237. SemIR::ArrayType inst) -> ResolveResult {
  1238. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1239. auto element_type_const_id =
  1240. GetLocalConstantId(resolver, inst.element_type_id);
  1241. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1242. if (resolver.HasNewWork()) {
  1243. return ResolveResult::Retry();
  1244. }
  1245. auto element_type_id =
  1246. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1247. element_type_const_id);
  1248. return ResolveAs<SemIR::ArrayType>(
  1249. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1250. .bound_id = bound_id,
  1251. .element_type_id = element_type_id});
  1252. }
  1253. static auto MakeAssociatedConstant(
  1254. ImportContext& context, const SemIR::AssociatedConstant& import_assoc_const,
  1255. SemIR::TypeId type_id)
  1256. -> std::pair<SemIR::AssociatedConstantId, SemIR::ConstantId> {
  1257. SemIR::AssociatedConstantDecl assoc_const_decl = {
  1258. .type_id = type_id,
  1259. .assoc_const_id = SemIR::AssociatedConstantId::None,
  1260. .decl_block_id = SemIR::InstBlockId::Empty};
  1261. auto assoc_const_decl_id = AddPlaceholderInstInNoBlock(
  1262. context.local_context(),
  1263. MakeImportedLocIdAndInst(
  1264. context.local_context(),
  1265. AddImportIRInst(context, import_assoc_const.decl_id),
  1266. assoc_const_decl));
  1267. assoc_const_decl.assoc_const_id = context.local_associated_constants().Add({
  1268. .name_id = GetLocalNameId(context, import_assoc_const.name_id),
  1269. .parent_scope_id = SemIR::NameScopeId::None,
  1270. .decl_id = assoc_const_decl_id,
  1271. .generic_id = MakeIncompleteGeneric(context, import_assoc_const.decl_id,
  1272. import_assoc_const.generic_id),
  1273. .default_value_id =
  1274. import_assoc_const.default_value_id.has_value()
  1275. ? AddImportRef(context, import_assoc_const.default_value_id)
  1276. : SemIR::InstId::None,
  1277. });
  1278. // Write the associated constant ID into the AssociatedConstantDecl.
  1279. ReplaceInstBeforeConstantUse(context.local_context(), assoc_const_decl_id,
  1280. assoc_const_decl);
  1281. auto const_id = context.local_constant_values().Get(assoc_const_decl_id);
  1282. return {assoc_const_decl.assoc_const_id, const_id};
  1283. }
  1284. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1285. SemIR::AssociatedConstantDecl inst,
  1286. SemIR::ConstantId const_id) -> ResolveResult {
  1287. const auto& import_assoc_const =
  1288. resolver.import_associated_constants().Get(inst.assoc_const_id);
  1289. SemIR::AssociatedConstantId assoc_const_id =
  1290. SemIR::AssociatedConstantId::None;
  1291. if (!const_id.has_value()) {
  1292. // In the first phase, import the type of the associated constant.
  1293. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1294. if (resolver.HasNewWork()) {
  1295. return ResolveResult::Retry();
  1296. }
  1297. // In the second phase, create the associated constant and its declaration.
  1298. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1299. type_const_id);
  1300. std::tie(assoc_const_id, const_id) =
  1301. MakeAssociatedConstant(resolver, import_assoc_const, type_id);
  1302. } else {
  1303. // In the third phase, compute the associated constant ID from the constant
  1304. // value of the declaration.
  1305. assoc_const_id =
  1306. resolver.local_insts()
  1307. .GetAs<SemIR::AssociatedConstantDecl>(
  1308. resolver.local_constant_values().GetInstId(const_id))
  1309. .assoc_const_id;
  1310. }
  1311. // Load the values to populate the entity with.
  1312. auto parent_scope_id =
  1313. GetLocalNameScopeId(resolver, import_assoc_const.parent_scope_id);
  1314. auto generic_data =
  1315. GetLocalGenericData(resolver, import_assoc_const.generic_id);
  1316. auto& new_assoc_const =
  1317. resolver.local_associated_constants().Get(assoc_const_id);
  1318. if (resolver.HasNewWork()) {
  1319. return ResolveResult::Retry(const_id, new_assoc_const.decl_id);
  1320. }
  1321. // Populate the entity.
  1322. new_assoc_const.parent_scope_id = parent_scope_id;
  1323. SetGenericData(resolver, import_assoc_const.generic_id,
  1324. new_assoc_const.generic_id, generic_data);
  1325. return ResolveResult::Done(const_id, new_assoc_const.decl_id);
  1326. }
  1327. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1328. SemIR::AssociatedEntity inst) -> ResolveResult {
  1329. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1330. if (resolver.HasNewWork()) {
  1331. return ResolveResult::Retry();
  1332. }
  1333. // Add a lazy reference to the target declaration.
  1334. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1335. return ResolveAs<SemIR::AssociatedEntity>(
  1336. resolver,
  1337. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1338. type_const_id),
  1339. .index = inst.index,
  1340. .decl_id = decl_id});
  1341. }
  1342. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1343. SemIR::AssociatedEntityType inst)
  1344. -> ResolveResult {
  1345. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1346. auto interface_inst_id = GetLocalConstantId(resolver, inst.interface_type_id);
  1347. if (resolver.HasNewWork()) {
  1348. return ResolveResult::Retry();
  1349. }
  1350. return ResolveAs<SemIR::AssociatedEntityType>(
  1351. resolver,
  1352. {.type_id = SemIR::TypeType::SingletonTypeId,
  1353. .interface_type_id =
  1354. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1355. interface_inst_id)});
  1356. }
  1357. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1358. SemIR::BaseDecl inst,
  1359. SemIR::InstId import_inst_id) -> ResolveResult {
  1360. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1361. auto base_type_const_id = GetLocalConstantId(
  1362. resolver, resolver.import_constant_values().Get(inst.base_type_inst_id));
  1363. if (resolver.HasNewWork()) {
  1364. return ResolveResult::Retry();
  1365. }
  1366. auto base_type_inst_id =
  1367. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1368. inst.base_type_inst_id, base_type_const_id);
  1369. // Create a corresponding instruction to represent the declaration.
  1370. auto inst_id = AddInstInNoBlock(
  1371. resolver.local_context(),
  1372. MakeImportedLocIdAndInst<SemIR::BaseDecl>(
  1373. resolver.local_context(), AddImportIRInst(resolver, import_inst_id),
  1374. {.type_id =
  1375. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1376. type_const_id),
  1377. .base_type_inst_id = base_type_inst_id,
  1378. .index = inst.index}));
  1379. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1380. inst_id);
  1381. }
  1382. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Vtable inst)
  1383. -> ResolveResult {
  1384. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1385. auto virtual_functions =
  1386. GetLocalInstBlockContents(resolver, inst.virtual_functions_id);
  1387. if (resolver.HasNewWork()) {
  1388. return ResolveResult::Retry();
  1389. }
  1390. auto virtual_functions_id = GetLocalCanonicalInstBlockId(
  1391. resolver, inst.virtual_functions_id, virtual_functions);
  1392. return ResolveAs<SemIR::Vtable>(
  1393. resolver,
  1394. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1395. type_const_id),
  1396. .virtual_functions_id = virtual_functions_id});
  1397. }
  1398. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1399. SemIR::BindAlias inst) -> ResolveResult {
  1400. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1401. return RetryOrDone(resolver, value_id);
  1402. }
  1403. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1404. SemIR::BindSymbolicName inst) -> ResolveResult {
  1405. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1406. if (resolver.HasNewWork()) {
  1407. return ResolveResult::Retry();
  1408. }
  1409. const auto& import_entity_name =
  1410. resolver.import_entity_names().Get(inst.entity_name_id);
  1411. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1412. // TODO: Use the same `EntityName` for the `SymbolicBindingPattern` and the
  1413. // `BindSymbolicName`.
  1414. auto entity_name_id = resolver.local_entity_names().AddSymbolicBindingName(
  1415. name_id, SemIR::NameScopeId::None, import_entity_name.bind_index(),
  1416. import_entity_name.is_template);
  1417. return ResolveAs<SemIR::BindSymbolicName>(
  1418. resolver,
  1419. {.type_id =
  1420. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1421. .entity_name_id = entity_name_id,
  1422. .value_id = SemIR::InstId::None});
  1423. }
  1424. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1425. SemIR::SymbolicBindingPattern inst)
  1426. -> ResolveResult {
  1427. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1428. if (resolver.HasNewWork()) {
  1429. return ResolveResult::Retry();
  1430. }
  1431. const auto& import_entity_name =
  1432. resolver.import_entity_names().Get(inst.entity_name_id);
  1433. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1434. // TODO: Use the same `EntityName` for the `SymbolicBindingPattern` and the
  1435. // `BindSymbolicName`.
  1436. auto entity_name_id = resolver.local_entity_names().AddSymbolicBindingName(
  1437. name_id, SemIR::NameScopeId::None, import_entity_name.bind_index(),
  1438. import_entity_name.is_template);
  1439. return ResolveAs<SemIR::SymbolicBindingPattern>(
  1440. resolver,
  1441. {.type_id =
  1442. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1443. .entity_name_id = entity_name_id});
  1444. }
  1445. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1446. SemIR::BoundMethod inst) -> ResolveResult {
  1447. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1448. SemIR::BoundMethodType::SingletonInstId);
  1449. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1450. auto function_decl_id =
  1451. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1452. if (resolver.HasNewWork()) {
  1453. return ResolveResult::Retry();
  1454. }
  1455. return ResolveAs<SemIR::BoundMethod>(
  1456. resolver,
  1457. {.type_id = GetSingletonType(resolver.local_context(),
  1458. SemIR::BoundMethodType::SingletonInstId),
  1459. .object_id = object_id,
  1460. .function_decl_id = function_decl_id});
  1461. }
  1462. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1463. -> ResolveResult {
  1464. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1465. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1466. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1467. if (resolver.HasNewWork()) {
  1468. return ResolveResult::Retry();
  1469. }
  1470. return ResolveAs<SemIR::Call>(
  1471. resolver,
  1472. {.type_id =
  1473. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1474. .callee_id = callee_id,
  1475. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1476. }
  1477. // Makes an incomplete class. This is necessary even with classes with a
  1478. // complete declaration, because things such as `Self` may refer back to the
  1479. // type.
  1480. static auto MakeIncompleteClass(ImportContext& context,
  1481. const SemIR::Class& import_class,
  1482. SemIR::SpecificId enclosing_specific_id)
  1483. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1484. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::SingletonTypeId,
  1485. .class_id = SemIR::ClassId::None,
  1486. .decl_block_id = SemIR::InstBlockId::Empty};
  1487. auto class_decl_id = AddPlaceholderInstInNoBlock(
  1488. context.local_context(),
  1489. MakeImportedLocIdAndInst(
  1490. context.local_context(),
  1491. AddImportIRInst(context, import_class.latest_decl_id()), class_decl));
  1492. // Regardless of whether ClassDecl is a complete type, we first need an
  1493. // incomplete type so that any references have something to point at.
  1494. class_decl.class_id = context.local_classes().Add(
  1495. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1496. {.self_type_id = SemIR::TypeId::None,
  1497. .inheritance_kind = import_class.inheritance_kind,
  1498. .is_dynamic = import_class.is_dynamic}});
  1499. if (import_class.has_parameters()) {
  1500. class_decl.type_id = GetGenericClassType(
  1501. context.local_context(), class_decl.class_id, enclosing_specific_id);
  1502. }
  1503. // Write the class ID into the ClassDecl.
  1504. ReplaceInstBeforeConstantUse(context.local_context(), class_decl_id,
  1505. class_decl);
  1506. auto self_const_id = context.local_constant_values().Get(class_decl_id);
  1507. return {class_decl.class_id, self_const_id};
  1508. }
  1509. // Fills out the class definition for an incomplete class.
  1510. static auto AddClassDefinition(ImportContext& context,
  1511. const SemIR::Class& import_class,
  1512. SemIR::Class& new_class,
  1513. SemIR::InstId complete_type_witness_id,
  1514. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1515. SemIR::InstId vtable_id) -> void {
  1516. new_class.definition_id = new_class.first_owning_decl_id;
  1517. new_class.complete_type_witness_id = complete_type_witness_id;
  1518. new_class.scope_id = context.local_name_scopes().Add(
  1519. new_class.first_owning_decl_id, SemIR::NameId::None,
  1520. new_class.parent_scope_id);
  1521. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1522. const auto& import_scope =
  1523. context.import_name_scopes().Get(import_class.scope_id);
  1524. // Push a block so that we can add scoped instructions to it.
  1525. context.local_context().inst_block_stack().Push();
  1526. AddNameScopeImportRefs(context, import_scope, new_scope);
  1527. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1528. if (import_class.base_id.has_value()) {
  1529. new_class.base_id = base_id;
  1530. }
  1531. if (import_class.adapt_id.has_value()) {
  1532. new_class.adapt_id = adapt_id;
  1533. }
  1534. if (import_class.vtable_id.has_value()) {
  1535. new_class.vtable_id = vtable_id;
  1536. }
  1537. }
  1538. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1539. SemIR::ClassDecl inst,
  1540. SemIR::ConstantId class_const_id)
  1541. -> ResolveResult {
  1542. // TODO: The handling of interfaces repeats a lot with the handling of
  1543. // classes, and will likely also be repeated for named constraints and
  1544. // choice types. Factor out some of this functionality.
  1545. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1546. SemIR::ClassId class_id = SemIR::ClassId::None;
  1547. if (!class_const_id.has_value()) {
  1548. auto import_specific_id = SemIR::SpecificId::None;
  1549. if (auto import_generic_class_type =
  1550. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1551. inst.type_id)) {
  1552. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1553. }
  1554. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1555. if (resolver.HasNewWork()) {
  1556. // This is the end of the first phase. Don't make a new class yet if
  1557. // we already have new work.
  1558. return ResolveResult::Retry();
  1559. }
  1560. // On the second phase, create a forward declaration of the class for any
  1561. // recursive references.
  1562. auto enclosing_specific_id =
  1563. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1564. std::tie(class_id, class_const_id) =
  1565. MakeIncompleteClass(resolver, import_class, enclosing_specific_id);
  1566. } else {
  1567. // On the third phase, compute the class ID from the constant
  1568. // value of the declaration.
  1569. auto class_const_inst = resolver.local_insts().Get(
  1570. resolver.local_constant_values().GetInstId(class_const_id));
  1571. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1572. class_id = class_type->class_id;
  1573. } else {
  1574. auto generic_class_type =
  1575. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1576. class_const_inst.type_id());
  1577. class_id = generic_class_type.class_id;
  1578. }
  1579. }
  1580. // Load constants for the definition.
  1581. auto parent_scope_id =
  1582. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1583. LoadLocalPatternConstantIds(resolver,
  1584. import_class.implicit_param_patterns_id);
  1585. LoadLocalPatternConstantIds(resolver, import_class.param_patterns_id);
  1586. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1587. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1588. auto complete_type_witness_const_id =
  1589. import_class.complete_type_witness_id.has_value()
  1590. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1591. : SemIR::ConstantId::None;
  1592. auto base_id = import_class.base_id.has_value()
  1593. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1594. : SemIR::InstId::None;
  1595. auto adapt_id = import_class.adapt_id.has_value()
  1596. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1597. : SemIR::InstId::None;
  1598. auto& new_class = resolver.local_classes().Get(class_id);
  1599. if (resolver.HasNewWork()) {
  1600. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1601. }
  1602. auto vtable_id = import_class.vtable_id.has_value()
  1603. ? AddImportRef(resolver, import_class.vtable_id)
  1604. : SemIR::InstId::None;
  1605. new_class.parent_scope_id = parent_scope_id;
  1606. new_class.implicit_param_patterns_id = GetLocalParamPatternsId(
  1607. resolver, import_class.implicit_param_patterns_id);
  1608. new_class.param_patterns_id =
  1609. GetLocalParamPatternsId(resolver, import_class.param_patterns_id);
  1610. SetGenericData(resolver, import_class.generic_id, new_class.generic_id,
  1611. generic_data);
  1612. new_class.self_type_id =
  1613. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1614. self_const_id);
  1615. if (import_class.is_defined()) {
  1616. auto complete_type_witness_id = AddLoadedImportRef(
  1617. resolver,
  1618. GetSingletonType(resolver.local_context(),
  1619. SemIR::WitnessType::SingletonInstId),
  1620. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1621. AddClassDefinition(resolver, import_class, new_class,
  1622. complete_type_witness_id, base_id, adapt_id, vtable_id);
  1623. }
  1624. return ResolveResult::Done(class_const_id, new_class.first_decl_id());
  1625. }
  1626. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1627. SemIR::ClassType inst) -> ResolveResult {
  1628. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1629. auto class_const_id = GetLocalConstantId(
  1630. resolver,
  1631. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1632. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1633. if (resolver.HasNewWork()) {
  1634. return ResolveResult::Retry();
  1635. }
  1636. // Find the corresponding class type. For a non-generic class, this is the
  1637. // type of the class declaration. For a generic class, build a class type
  1638. // referencing this specialization of the generic class.
  1639. auto class_const_inst = resolver.local_insts().Get(
  1640. resolver.local_constant_values().GetInstId(class_const_id));
  1641. if (class_const_inst.Is<SemIR::ClassType>()) {
  1642. return ResolveResult::Done(class_const_id);
  1643. } else {
  1644. auto generic_class_type =
  1645. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1646. class_const_inst.type_id());
  1647. auto specific_id =
  1648. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1649. return ResolveAs<SemIR::ClassType>(
  1650. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1651. .class_id = generic_class_type.class_id,
  1652. .specific_id = specific_id});
  1653. }
  1654. }
  1655. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1656. SemIR::CompleteTypeWitness inst)
  1657. -> ResolveResult {
  1658. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1659. SemIR::WitnessType::SingletonInstId);
  1660. auto object_repr_const_id = GetLocalConstantId(resolver, inst.object_repr_id);
  1661. if (resolver.HasNewWork()) {
  1662. return ResolveResult::Retry();
  1663. }
  1664. auto object_repr_id =
  1665. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1666. object_repr_const_id);
  1667. return ResolveAs<SemIR::CompleteTypeWitness>(
  1668. resolver,
  1669. {.type_id = GetSingletonType(resolver.local_context(),
  1670. SemIR::WitnessType::SingletonInstId),
  1671. .object_repr_id = object_repr_id});
  1672. }
  1673. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1674. SemIR::ConstType inst) -> ResolveResult {
  1675. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1676. auto inner_const_id = GetLocalConstantId(resolver, inst.inner_id);
  1677. if (resolver.HasNewWork()) {
  1678. return ResolveResult::Retry();
  1679. }
  1680. auto inner_type_id =
  1681. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1682. inner_const_id);
  1683. return ResolveAs<SemIR::ConstType>(
  1684. resolver,
  1685. {.type_id = SemIR::TypeType::SingletonTypeId, .inner_id = inner_type_id});
  1686. }
  1687. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1688. SemIR::ExportDecl inst) -> ResolveResult {
  1689. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1690. return RetryOrDone(resolver, value_id);
  1691. }
  1692. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1693. SemIR::FieldDecl inst,
  1694. SemIR::InstId import_inst_id) -> ResolveResult {
  1695. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1696. if (resolver.HasNewWork()) {
  1697. return ResolveResult::Retry();
  1698. }
  1699. auto inst_id = AddInstInNoBlock(
  1700. resolver.local_context(),
  1701. MakeImportedLocIdAndInst<SemIR::FieldDecl>(
  1702. resolver.local_context(), AddImportIRInst(resolver, import_inst_id),
  1703. {.type_id =
  1704. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1705. const_id),
  1706. .name_id = GetLocalNameId(resolver, inst.name_id),
  1707. .index = inst.index}));
  1708. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1709. inst_id);
  1710. }
  1711. // Make a declaration of a function. This is done as a separate step from
  1712. // importing the function declaration in order to resolve cycles.
  1713. static auto MakeFunctionDecl(ImportContext& context,
  1714. const SemIR::Function& import_function,
  1715. SemIR::SpecificId specific_id)
  1716. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1717. SemIR::FunctionDecl function_decl = {
  1718. .type_id = SemIR::TypeId::None,
  1719. .function_id = SemIR::FunctionId::None,
  1720. .decl_block_id = SemIR::InstBlockId::Empty};
  1721. auto function_decl_id = AddPlaceholderInstInNoBlock(
  1722. context.local_context(),
  1723. MakeImportedLocIdAndInst(
  1724. context.local_context(),
  1725. AddImportIRInst(context, import_function.first_decl_id()),
  1726. function_decl));
  1727. // Start with an incomplete function.
  1728. function_decl.function_id = context.local_functions().Add(
  1729. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  1730. {.return_slot_pattern_id = SemIR::InstId::None,
  1731. .builtin_function_kind = import_function.builtin_function_kind}});
  1732. function_decl.type_id = GetFunctionType(
  1733. context.local_context(), function_decl.function_id, specific_id);
  1734. // Write the function ID and type into the FunctionDecl.
  1735. ReplaceInstBeforeConstantUse(context.local_context(), function_decl_id,
  1736. function_decl);
  1737. return {function_decl.function_id,
  1738. context.local_constant_values().Get(function_decl_id)};
  1739. }
  1740. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1741. SemIR::FunctionDecl inst,
  1742. SemIR::ConstantId function_const_id)
  1743. -> ResolveResult {
  1744. const auto& import_function =
  1745. resolver.import_functions().Get(inst.function_id);
  1746. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  1747. if (!function_const_id.has_value()) {
  1748. auto import_specific_id = resolver.import_types()
  1749. .GetAs<SemIR::FunctionType>(inst.type_id)
  1750. .specific_id;
  1751. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1752. if (resolver.HasNewWork()) {
  1753. // This is the end of the first phase. Don't make a new function yet if
  1754. // we already have new work.
  1755. return ResolveResult::Retry();
  1756. }
  1757. // On the second phase, create a forward declaration of the interface.
  1758. auto specific_id =
  1759. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1760. std::tie(function_id, function_const_id) =
  1761. MakeFunctionDecl(resolver, import_function, specific_id);
  1762. } else {
  1763. // On the third phase, compute the function ID from the constant value of
  1764. // the declaration.
  1765. auto function_const_inst = resolver.local_insts().Get(
  1766. resolver.local_constant_values().GetInstId(function_const_id));
  1767. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1768. function_const_inst.type_id());
  1769. function_id = function_type.function_id;
  1770. }
  1771. auto return_type_const_id = SemIR::ConstantId::None;
  1772. if (import_function.return_slot_pattern_id.has_value()) {
  1773. return_type_const_id = GetLocalConstantId(
  1774. resolver, resolver.import_insts()
  1775. .Get(import_function.return_slot_pattern_id)
  1776. .type_id());
  1777. }
  1778. auto parent_scope_id =
  1779. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1780. LoadLocalPatternConstantIds(resolver,
  1781. import_function.implicit_param_patterns_id);
  1782. LoadLocalPatternConstantIds(resolver, import_function.param_patterns_id);
  1783. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1784. auto& new_function = resolver.local_functions().Get(function_id);
  1785. if (resolver.HasNewWork()) {
  1786. return ResolveResult::Retry(function_const_id,
  1787. new_function.first_decl_id());
  1788. }
  1789. // Add the function declaration.
  1790. new_function.parent_scope_id = parent_scope_id;
  1791. SemIR::InstId self_param_id = SemIR::InstId::None;
  1792. new_function.implicit_param_patterns_id = GetLocalParamPatternsId(
  1793. resolver, import_function.implicit_param_patterns_id, &self_param_id);
  1794. new_function.self_param_id = self_param_id;
  1795. new_function.param_patterns_id =
  1796. GetLocalParamPatternsId(resolver, import_function.param_patterns_id);
  1797. new_function.return_slot_pattern_id = GetLocalReturnSlotPatternId(
  1798. resolver, import_function.return_slot_pattern_id);
  1799. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1800. generic_data);
  1801. if (import_function.definition_id.has_value()) {
  1802. new_function.definition_id = new_function.first_owning_decl_id;
  1803. }
  1804. return ResolveResult::Done(function_const_id, new_function.first_decl_id());
  1805. }
  1806. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1807. SemIR::FunctionType inst) -> ResolveResult {
  1808. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1809. auto fn_val_id = GetLocalConstantInstId(
  1810. resolver,
  1811. resolver.import_functions().Get(inst.function_id).first_decl_id());
  1812. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1813. if (resolver.HasNewWork()) {
  1814. return ResolveResult::Retry();
  1815. }
  1816. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  1817. return ResolveAs<SemIR::FunctionType>(
  1818. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1819. .function_id = resolver.local_types()
  1820. .GetAs<SemIR::FunctionType>(fn_type_id)
  1821. .function_id,
  1822. .specific_id = GetOrAddLocalSpecific(
  1823. resolver, inst.specific_id, specific_data)});
  1824. }
  1825. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1826. SemIR::FunctionTypeWithSelfType inst)
  1827. -> ResolveResult {
  1828. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1829. auto interface_function_type_id =
  1830. GetLocalConstantInstId(resolver, inst.interface_function_type_id);
  1831. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  1832. if (resolver.HasNewWork()) {
  1833. return ResolveResult::Retry();
  1834. }
  1835. return ResolveAs<SemIR::FunctionTypeWithSelfType>(
  1836. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1837. .interface_function_type_id = interface_function_type_id,
  1838. .self_id = self_id});
  1839. }
  1840. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1841. SemIR::GenericClassType inst) -> ResolveResult {
  1842. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1843. auto class_val_id = GetLocalConstantInstId(
  1844. resolver,
  1845. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1846. if (resolver.HasNewWork()) {
  1847. return ResolveResult::Retry();
  1848. }
  1849. auto class_val = resolver.local_insts().Get(class_val_id);
  1850. CARBON_CHECK(
  1851. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1852. return ResolveResult::Done(
  1853. resolver.local_types().GetConstantId(class_val.type_id()));
  1854. }
  1855. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1856. SemIR::GenericInterfaceType inst)
  1857. -> ResolveResult {
  1858. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1859. auto interface_val_id = GetLocalConstantInstId(
  1860. resolver,
  1861. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  1862. if (resolver.HasNewWork()) {
  1863. return ResolveResult::Retry();
  1864. }
  1865. auto interface_val = resolver.local_insts().Get(interface_val_id);
  1866. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  1867. interface_val.type_id()));
  1868. return ResolveResult::Done(
  1869. resolver.local_types().GetConstantId(interface_val.type_id()));
  1870. }
  1871. // Make a declaration of an impl. This is done as a separate step from
  1872. // importing the impl definition in order to resolve cycles.
  1873. static auto MakeImplDeclaration(ImportContext& context,
  1874. const SemIR::Impl& import_impl,
  1875. SemIR::InstId witness_id)
  1876. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1877. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  1878. .decl_block_id = SemIR::InstBlockId::Empty};
  1879. auto impl_decl_id = AddPlaceholderInstInNoBlock(
  1880. context.local_context(),
  1881. MakeImportedLocIdAndInst(
  1882. context.local_context(),
  1883. AddImportIRInst(context, import_impl.latest_decl_id()), impl_decl));
  1884. impl_decl.impl_id = context.local_impls().Add(
  1885. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  1886. {.self_id = SemIR::InstId::None,
  1887. .constraint_id = SemIR::InstId::None,
  1888. .interface = SemIR::SpecificInterface::None,
  1889. .witness_id = witness_id}});
  1890. // Write the impl ID into the ImplDecl.
  1891. ReplaceInstBeforeConstantUse(context.local_context(), impl_decl_id,
  1892. impl_decl);
  1893. return {impl_decl.impl_id, context.local_constant_values().Get(impl_decl_id)};
  1894. }
  1895. // Imports the definition of an impl.
  1896. static auto AddImplDefinition(ImportContext& context,
  1897. const SemIR::Impl& import_impl,
  1898. SemIR::Impl& new_impl) -> void {
  1899. new_impl.definition_id = new_impl.first_owning_decl_id;
  1900. new_impl.defined = true;
  1901. if (import_impl.scope_id.has_value()) {
  1902. new_impl.scope_id = context.local_name_scopes().Add(
  1903. new_impl.first_owning_decl_id, SemIR::NameId::None,
  1904. new_impl.parent_scope_id);
  1905. // Import the contents of the definition scope, if we might need it. Name
  1906. // lookup is never performed into this scope by a user of the impl, so
  1907. // this is only necessary in the same library that defined the impl, in
  1908. // order to support defining members of the impl out of line in the impl
  1909. // file when the impl is defined in the API file.
  1910. // TODO: Check to see if this impl is owned by the API file, rather than
  1911. // merely being imported into it.
  1912. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1913. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  1914. const auto& import_scope =
  1915. context.import_name_scopes().Get(import_impl.scope_id);
  1916. // Push a block so that we can add scoped instructions to it.
  1917. context.local_context().inst_block_stack().Push();
  1918. AddNameScopeImportRefs(context, import_scope, new_scope);
  1919. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  1920. }
  1921. }
  1922. }
  1923. namespace {
  1924. struct SpecificInterfaceData {
  1925. SemIR::ConstantId interface_const_id;
  1926. SpecificData specific_data;
  1927. };
  1928. } // namespace
  1929. static auto GetLocalSpecificInstanceData(
  1930. ImportRefResolver& resolver, SemIR::SpecificInterface import_interface)
  1931. -> SpecificInterfaceData {
  1932. return {.interface_const_id = GetLocalConstantId(
  1933. resolver, resolver.import_interfaces()
  1934. .Get(import_interface.interface_id)
  1935. .first_owning_decl_id),
  1936. .specific_data =
  1937. GetLocalSpecificData(resolver, import_interface.specific_id)};
  1938. }
  1939. static auto GetLocalSpecificInterface(ImportContext& context,
  1940. SemIR::SpecificId import_specific_id,
  1941. SpecificInterfaceData interface_data)
  1942. -> SemIR::SpecificInterface {
  1943. // Find the corresponding interface type. For a non-generic interface,
  1944. // this is the type of the interface declaration. For a generic interface,
  1945. // build a interface type referencing this specialization of the generic
  1946. // interface.
  1947. auto interface_const_inst =
  1948. context.local_insts().Get(context.local_constant_values().GetInstId(
  1949. interface_data.interface_const_id));
  1950. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  1951. const SemIR::FacetTypeInfo& new_facet_type_info =
  1952. context.local_facet_types().Get(facet_type->facet_type_id);
  1953. return new_facet_type_info.impls_constraints.front();
  1954. } else {
  1955. auto generic_interface_type =
  1956. context.local_types().GetAs<SemIR::GenericInterfaceType>(
  1957. interface_const_inst.type_id());
  1958. auto specific_id = GetOrAddLocalSpecific(context, import_specific_id,
  1959. interface_data.specific_data);
  1960. return {generic_interface_type.interface_id, specific_id};
  1961. }
  1962. }
  1963. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1964. SemIR::ImplDecl inst,
  1965. SemIR::ConstantId impl_const_id)
  1966. -> ResolveResult {
  1967. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1968. // functions. Factor out the commonality.
  1969. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  1970. auto specific_interface_data =
  1971. GetLocalSpecificInstanceData(resolver, import_impl.interface);
  1972. SemIR::ImplId impl_id = SemIR::ImplId::None;
  1973. if (!impl_const_id.has_value()) {
  1974. if (resolver.HasNewWork()) {
  1975. // This is the end of the first phase. Don't make a new impl yet if we
  1976. // already have new work.
  1977. return ResolveResult::Retry();
  1978. }
  1979. // On the second phase, create a forward declaration of the impl for any
  1980. // recursive references.
  1981. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  1982. std::tie(impl_id, impl_const_id) =
  1983. MakeImplDeclaration(resolver, import_impl, witness_id);
  1984. } else {
  1985. // On the third phase, compute the impl ID from the "constant value" of
  1986. // the declaration, which is a reference to the created ImplDecl.
  1987. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  1988. resolver.local_constant_values().GetInstId(impl_const_id));
  1989. impl_id = impl_const_inst.impl_id;
  1990. }
  1991. // Load constants for the definition.
  1992. auto parent_scope_id =
  1993. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  1994. LoadLocalPatternConstantIds(resolver, import_impl.implicit_param_patterns_id);
  1995. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  1996. auto self_const_id = GetLocalConstantId(
  1997. resolver, resolver.import_constant_values().Get(import_impl.self_id));
  1998. auto constraint_const_id = GetLocalConstantId(
  1999. resolver,
  2000. resolver.import_constant_values().Get(import_impl.constraint_id));
  2001. auto& new_impl = resolver.local_impls().Get(impl_id);
  2002. if (resolver.HasNewWork()) {
  2003. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2004. }
  2005. new_impl.parent_scope_id = parent_scope_id;
  2006. new_impl.implicit_param_patterns_id =
  2007. GetLocalParamPatternsId(resolver, import_impl.implicit_param_patterns_id);
  2008. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  2009. generic_data);
  2010. // Create instructions for self and constraint to hold the symbolic constant
  2011. // value for a generic impl.
  2012. new_impl.self_id =
  2013. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  2014. import_impl.self_id, self_const_id);
  2015. new_impl.constraint_id =
  2016. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  2017. import_impl.constraint_id, constraint_const_id);
  2018. new_impl.interface = GetLocalSpecificInterface(
  2019. resolver, import_impl.interface.specific_id, specific_interface_data);
  2020. if (import_impl.is_defined()) {
  2021. AddImplDefinition(resolver, import_impl, new_impl);
  2022. }
  2023. // If the `impl` is declared in the API file corresponding to the current
  2024. // file, add this to impl lookup so that it can be found by redeclarations
  2025. // in the current file.
  2026. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2027. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2028. }
  2029. return ResolveResult::Done(impl_const_id, new_impl.first_decl_id());
  2030. }
  2031. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2032. SemIR::ImportRefLoaded /*inst*/,
  2033. SemIR::InstId inst_id) -> ResolveResult {
  2034. // Return the constant for the instruction of the imported constant.
  2035. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2036. CARBON_CHECK(constant_id.has_value(),
  2037. "Loaded import ref has no constant value");
  2038. if (!constant_id.is_constant()) {
  2039. resolver.local_context().TODO(
  2040. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2041. return ResolveResult::Done(constant_id);
  2042. }
  2043. auto new_constant_id = GetLocalConstantId(
  2044. resolver, resolver.import_constant_values().GetInstId(constant_id));
  2045. return RetryOrDone(resolver, new_constant_id);
  2046. }
  2047. // Make a declaration of an interface. This is done as a separate step from
  2048. // importing the interface definition in order to resolve cycles.
  2049. static auto MakeInterfaceDecl(ImportContext& context,
  2050. const SemIR::Interface& import_interface,
  2051. SemIR::SpecificId enclosing_specific_id)
  2052. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2053. SemIR::InterfaceDecl interface_decl = {
  2054. .type_id = SemIR::TypeType::SingletonTypeId,
  2055. .interface_id = SemIR::InterfaceId::None,
  2056. .decl_block_id = SemIR::InstBlockId::Empty};
  2057. auto interface_decl_id = AddPlaceholderInstInNoBlock(
  2058. context.local_context(),
  2059. MakeImportedLocIdAndInst(
  2060. context.local_context(),
  2061. AddImportIRInst(context, import_interface.first_owning_decl_id),
  2062. interface_decl));
  2063. // Start with an incomplete interface.
  2064. interface_decl.interface_id = context.local_interfaces().Add(
  2065. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2066. import_interface),
  2067. {}});
  2068. if (import_interface.has_parameters()) {
  2069. interface_decl.type_id = GetGenericInterfaceType(
  2070. context.local_context(), interface_decl.interface_id,
  2071. enclosing_specific_id);
  2072. }
  2073. // Write the interface ID into the InterfaceDecl.
  2074. ReplaceInstBeforeConstantUse(context.local_context(), interface_decl_id,
  2075. interface_decl);
  2076. return {interface_decl.interface_id,
  2077. context.local_constant_values().Get(interface_decl_id)};
  2078. }
  2079. // Imports the definition for an interface that has been imported as a forward
  2080. // declaration.
  2081. static auto AddInterfaceDefinition(ImportContext& context,
  2082. const SemIR::Interface& import_interface,
  2083. SemIR::Interface& new_interface,
  2084. SemIR::InstId self_param_id) -> void {
  2085. new_interface.scope_id = context.local_name_scopes().Add(
  2086. new_interface.first_owning_decl_id, SemIR::NameId::None,
  2087. new_interface.parent_scope_id);
  2088. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  2089. const auto& import_scope =
  2090. context.import_name_scopes().Get(import_interface.scope_id);
  2091. // Push a block so that we can add scoped instructions to it.
  2092. context.local_context().inst_block_stack().Push();
  2093. AddNameScopeImportRefs(context, import_scope, new_scope);
  2094. new_interface.associated_entities_id = AddAssociatedEntities(
  2095. context, new_interface.scope_id, import_interface.associated_entities_id);
  2096. new_interface.body_block_id =
  2097. context.local_context().inst_block_stack().Pop();
  2098. new_interface.self_param_id = self_param_id;
  2099. CARBON_CHECK(import_scope.extended_scopes().empty(),
  2100. "Interfaces don't currently have extended scopes to support.");
  2101. }
  2102. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2103. SemIR::InterfaceDecl inst,
  2104. SemIR::ConstantId interface_const_id)
  2105. -> ResolveResult {
  2106. const auto& import_interface =
  2107. resolver.import_interfaces().Get(inst.interface_id);
  2108. SemIR::InterfaceId interface_id = SemIR::InterfaceId::None;
  2109. if (!interface_const_id.has_value()) {
  2110. auto import_specific_id = SemIR::SpecificId::None;
  2111. if (auto import_generic_interface_type =
  2112. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2113. inst.type_id)) {
  2114. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2115. }
  2116. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2117. if (resolver.HasNewWork()) {
  2118. // This is the end of the first phase. Don't make a new interface yet if
  2119. // we already have new work.
  2120. return ResolveResult::Retry();
  2121. }
  2122. // On the second phase, create a forward declaration of the interface.
  2123. auto enclosing_specific_id =
  2124. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2125. std::tie(interface_id, interface_const_id) =
  2126. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2127. } else {
  2128. // On the third phase, compute the interface ID from the constant value of
  2129. // the declaration.
  2130. auto interface_const_inst = resolver.local_insts().Get(
  2131. resolver.local_constant_values().GetInstId(interface_const_id));
  2132. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2133. const SemIR::FacetTypeInfo& facet_type_info =
  2134. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2135. auto interface_type = facet_type_info.TryAsSingleInterface();
  2136. CARBON_CHECK(interface_type);
  2137. interface_id = interface_type->interface_id;
  2138. } else {
  2139. auto generic_interface_type =
  2140. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2141. interface_const_inst.type_id());
  2142. interface_id = generic_interface_type.interface_id;
  2143. }
  2144. }
  2145. auto parent_scope_id =
  2146. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2147. LoadLocalPatternConstantIds(resolver,
  2148. import_interface.implicit_param_patterns_id);
  2149. LoadLocalPatternConstantIds(resolver, import_interface.param_patterns_id);
  2150. auto generic_data =
  2151. GetLocalGenericData(resolver, import_interface.generic_id);
  2152. std::optional<SemIR::InstId> self_param_id;
  2153. if (import_interface.is_defined()) {
  2154. self_param_id =
  2155. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2156. }
  2157. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2158. if (resolver.HasNewWork()) {
  2159. return ResolveResult::Retry(interface_const_id,
  2160. new_interface.first_decl_id());
  2161. }
  2162. new_interface.parent_scope_id = parent_scope_id;
  2163. new_interface.implicit_param_patterns_id = GetLocalParamPatternsId(
  2164. resolver, import_interface.implicit_param_patterns_id);
  2165. new_interface.param_patterns_id =
  2166. GetLocalParamPatternsId(resolver, import_interface.param_patterns_id);
  2167. SetGenericData(resolver, import_interface.generic_id,
  2168. new_interface.generic_id, generic_data);
  2169. if (import_interface.is_defined()) {
  2170. CARBON_CHECK(self_param_id);
  2171. AddInterfaceDefinition(resolver, import_interface, new_interface,
  2172. *self_param_id);
  2173. }
  2174. return ResolveResult::Done(interface_const_id, new_interface.first_decl_id());
  2175. }
  2176. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2177. SemIR::FacetAccessType inst) -> ResolveResult {
  2178. auto facet_value_inst_id =
  2179. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2180. if (resolver.HasNewWork()) {
  2181. return ResolveResult::Retry();
  2182. }
  2183. return ResolveAs<SemIR::FacetAccessType>(
  2184. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2185. .facet_value_inst_id = facet_value_inst_id});
  2186. }
  2187. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2188. SemIR::FacetAccessWitness inst)
  2189. -> ResolveResult {
  2190. auto facet_value_inst_id =
  2191. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2192. if (resolver.HasNewWork()) {
  2193. return ResolveResult::Retry();
  2194. }
  2195. return ResolveAs<SemIR::FacetAccessWitness>(
  2196. resolver,
  2197. {.type_id = GetSingletonType(resolver.local_context(),
  2198. SemIR::WitnessType::SingletonInstId),
  2199. .facet_value_inst_id = facet_value_inst_id});
  2200. }
  2201. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2202. SemIR::FacetType inst) -> ResolveResult {
  2203. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2204. const SemIR::FacetTypeInfo& facet_type_info =
  2205. resolver.import_facet_types().Get(inst.facet_type_id);
  2206. for (auto interface : facet_type_info.impls_constraints) {
  2207. // We discard this here and recompute it below instead of saving it to avoid
  2208. // allocations.
  2209. GetLocalSpecificInstanceData(resolver, interface);
  2210. }
  2211. for (auto rewrite : facet_type_info.rewrite_constraints) {
  2212. GetLocalConstantId(resolver, rewrite.lhs_const_id);
  2213. GetLocalConstantId(resolver, rewrite.rhs_const_id);
  2214. }
  2215. if (resolver.HasNewWork()) {
  2216. return ResolveResult::Retry();
  2217. }
  2218. llvm::SmallVector<SemIR::FacetTypeInfo::ImplsConstraint> impls_constraints;
  2219. for (auto interface : facet_type_info.impls_constraints) {
  2220. auto data = GetLocalSpecificInstanceData(resolver, interface);
  2221. impls_constraints.push_back(
  2222. GetLocalSpecificInterface(resolver, interface.specific_id, data));
  2223. }
  2224. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>
  2225. rewrite_constraints;
  2226. for (auto rewrite : facet_type_info.rewrite_constraints) {
  2227. rewrite_constraints.push_back(
  2228. {.lhs_const_id = GetLocalConstantId(resolver, rewrite.lhs_const_id),
  2229. .rhs_const_id = GetLocalConstantId(resolver, rewrite.rhs_const_id)});
  2230. }
  2231. // TODO: Also process the other requirements.
  2232. SemIR::FacetTypeId facet_type_id =
  2233. resolver.local_facet_types().Add(SemIR::FacetTypeInfo{
  2234. .impls_constraints = impls_constraints,
  2235. .rewrite_constraints = rewrite_constraints,
  2236. .other_requirements = facet_type_info.other_requirements});
  2237. return ResolveAs<SemIR::FacetType>(
  2238. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2239. .facet_type_id = facet_type_id});
  2240. }
  2241. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2242. SemIR::FacetValue inst) -> ResolveResult {
  2243. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2244. auto type_inst_id = GetLocalConstantInstId(resolver, inst.type_inst_id);
  2245. auto witness_inst_id = GetLocalConstantInstId(resolver, inst.witness_inst_id);
  2246. if (resolver.HasNewWork()) {
  2247. return ResolveResult::Retry();
  2248. }
  2249. return ResolveAs<SemIR::FacetValue>(
  2250. resolver,
  2251. {.type_id =
  2252. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2253. .type_inst_id = type_inst_id,
  2254. .witness_inst_id = witness_inst_id});
  2255. }
  2256. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2257. SemIR::ImplWitness inst) -> ResolveResult {
  2258. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2259. if (resolver.HasNewWork()) {
  2260. return ResolveResult::Retry();
  2261. }
  2262. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  2263. auto specific_id =
  2264. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2265. return ResolveAs<SemIR::ImplWitness>(
  2266. resolver,
  2267. {.type_id = GetSingletonType(resolver.local_context(),
  2268. SemIR::WitnessType::SingletonInstId),
  2269. .elements_id = elements_id,
  2270. .specific_id = specific_id});
  2271. }
  2272. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2273. SemIR::ImplWitnessAccess inst)
  2274. -> ResolveResult {
  2275. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2276. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2277. if (resolver.HasNewWork()) {
  2278. return ResolveResult::Retry();
  2279. }
  2280. return ResolveAs<SemIR::ImplWitnessAccess>(
  2281. resolver,
  2282. {.type_id =
  2283. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2284. .witness_id = witness_id,
  2285. .index = inst.index});
  2286. }
  2287. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2288. SemIR::IntValue inst) -> ResolveResult {
  2289. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2290. if (resolver.HasNewWork()) {
  2291. return ResolveResult::Retry();
  2292. }
  2293. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2294. // to add a new canonical int in this IR.
  2295. auto int_id = inst.int_id.is_embedded_value()
  2296. ? inst.int_id
  2297. : resolver.local_ints().AddSigned(
  2298. resolver.import_ints().Get(inst.int_id));
  2299. return ResolveAs<SemIR::IntValue>(
  2300. resolver,
  2301. {.type_id =
  2302. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2303. .int_id = int_id});
  2304. }
  2305. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2306. SemIR::IntType inst) -> ResolveResult {
  2307. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2308. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2309. if (resolver.HasNewWork()) {
  2310. return ResolveResult::Retry();
  2311. }
  2312. return ResolveAs<SemIR::IntType>(resolver,
  2313. {.type_id = SemIR::TypeType::SingletonTypeId,
  2314. .int_kind = inst.int_kind,
  2315. .bit_width_id = bit_width_id});
  2316. }
  2317. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2318. SemIR::Namespace inst,
  2319. SemIR::InstId import_inst_id) -> ResolveResult {
  2320. const auto& name_scope =
  2321. resolver.import_name_scopes().Get(inst.name_scope_id);
  2322. // A package from a different file becomes a child of the package here, as it
  2323. // would be if it were imported.
  2324. auto parent_scope_id =
  2325. inst.name_scope_id == SemIR::NameScopeId::Package
  2326. ? SemIR::NameScopeId::Package
  2327. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2328. if (resolver.HasNewWork()) {
  2329. return ResolveResult::Retry();
  2330. }
  2331. auto namespace_type_id = GetSingletonType(
  2332. resolver.local_context(), SemIR::NamespaceType::SingletonInstId);
  2333. auto namespace_decl =
  2334. SemIR::Namespace{.type_id = namespace_type_id,
  2335. .name_scope_id = SemIR::NameScopeId::None,
  2336. .import_id = SemIR::AbsoluteInstId::None};
  2337. auto inst_id = AddPlaceholderInstInNoBlock(
  2338. resolver.local_context(),
  2339. MakeImportedLocIdAndInst(resolver.local_context(),
  2340. AddImportIRInst(resolver, import_inst_id),
  2341. namespace_decl));
  2342. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2343. namespace_decl.name_scope_id =
  2344. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2345. // Namespaces from this package are eagerly imported, so anything we load here
  2346. // must be a closed import.
  2347. resolver.local_name_scopes()
  2348. .Get(namespace_decl.name_scope_id)
  2349. .set_is_closed_import(true);
  2350. ReplaceInstBeforeConstantUse(resolver.local_context(), inst_id,
  2351. namespace_decl);
  2352. return {.const_id = resolver.local_constant_values().Get(inst_id)};
  2353. }
  2354. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2355. SemIR::PointerType inst) -> ResolveResult {
  2356. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2357. auto pointee_const_id = GetLocalConstantId(resolver, inst.pointee_id);
  2358. if (resolver.HasNewWork()) {
  2359. return ResolveResult::Retry();
  2360. }
  2361. auto pointee_type_id =
  2362. resolver.local_context().types().GetTypeIdForTypeConstantId(
  2363. pointee_const_id);
  2364. return ResolveAs<SemIR::PointerType>(
  2365. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2366. .pointee_id = pointee_type_id});
  2367. }
  2368. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2369. SemIR::RequireCompleteType inst)
  2370. -> ResolveResult {
  2371. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2372. SemIR::WitnessType::SingletonInstId);
  2373. auto complete_type_const_id =
  2374. GetLocalConstantId(resolver, inst.complete_type_id);
  2375. if (resolver.HasNewWork()) {
  2376. return ResolveResult::Retry();
  2377. }
  2378. auto complete_type_id =
  2379. resolver.local_context().types().GetTypeIdForTypeConstantId(
  2380. complete_type_const_id);
  2381. return ResolveAs<SemIR::RequireCompleteType>(
  2382. resolver,
  2383. {.type_id = GetSingletonType(resolver.local_context(),
  2384. SemIR::WitnessType::SingletonInstId),
  2385. .complete_type_id = complete_type_id});
  2386. }
  2387. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2388. SemIR::SpecificFunction inst) -> ResolveResult {
  2389. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2390. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2391. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2392. if (resolver.HasNewWork()) {
  2393. return ResolveResult::Retry();
  2394. }
  2395. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2396. type_const_id);
  2397. auto specific_id =
  2398. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2399. return ResolveAs<SemIR::SpecificFunction>(
  2400. resolver,
  2401. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2402. }
  2403. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2404. SemIR::StructType inst) -> ResolveResult {
  2405. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2406. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2407. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  2408. field_const_ids.reserve(orig_fields.size());
  2409. for (auto field : orig_fields) {
  2410. field_const_ids.push_back(GetLocalConstantId(resolver, field.type_id));
  2411. }
  2412. if (resolver.HasNewWork()) {
  2413. return ResolveResult::Retry();
  2414. }
  2415. // Prepare a vector of fields for GetStructType.
  2416. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2417. new_fields.reserve(orig_fields.size());
  2418. for (auto [orig_field, field_const_id] :
  2419. llvm::zip(orig_fields, field_const_ids)) {
  2420. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2421. auto field_type_id =
  2422. resolver.local_context().types().GetTypeIdForTypeConstantId(
  2423. field_const_id);
  2424. new_fields.push_back({.name_id = name_id, .type_id = field_type_id});
  2425. }
  2426. return ResolveAs<SemIR::StructType>(
  2427. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2428. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2429. new_fields)});
  2430. }
  2431. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2432. SemIR::StructValue inst) -> ResolveResult {
  2433. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2434. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2435. if (resolver.HasNewWork()) {
  2436. return ResolveResult::Retry();
  2437. }
  2438. return ResolveAs<SemIR::StructValue>(
  2439. resolver,
  2440. {.type_id =
  2441. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2442. .elements_id =
  2443. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2444. }
  2445. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2446. SemIR::TupleType inst) -> ResolveResult {
  2447. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2448. auto orig_elem_type_ids = resolver.import_type_blocks().Get(inst.elements_id);
  2449. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  2450. elem_const_ids.reserve(orig_elem_type_ids.size());
  2451. for (auto elem_type_id : orig_elem_type_ids) {
  2452. elem_const_ids.push_back(GetLocalConstantId(resolver, elem_type_id));
  2453. }
  2454. if (resolver.HasNewWork()) {
  2455. return ResolveResult::Retry();
  2456. }
  2457. // Prepare a vector of the tuple types for GetTupleType.
  2458. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  2459. elem_type_ids.reserve(orig_elem_type_ids.size());
  2460. for (auto elem_const_id : elem_const_ids) {
  2461. elem_type_ids.push_back(
  2462. resolver.local_context().types().GetTypeIdForTypeConstantId(
  2463. elem_const_id));
  2464. }
  2465. return ResolveResult::Done(resolver.local_types().GetConstantId(
  2466. GetTupleType(resolver.local_context(), elem_type_ids)));
  2467. }
  2468. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2469. SemIR::TupleValue inst) -> ResolveResult {
  2470. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2471. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2472. if (resolver.HasNewWork()) {
  2473. return ResolveResult::Retry();
  2474. }
  2475. return ResolveAs<SemIR::TupleValue>(
  2476. resolver,
  2477. {.type_id =
  2478. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2479. .elements_id =
  2480. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2481. }
  2482. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2483. SemIR::UnboundElementType inst)
  2484. -> ResolveResult {
  2485. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2486. auto class_const_id = GetLocalConstantId(resolver, inst.class_type_id);
  2487. auto elem_const_id = GetLocalConstantId(resolver, inst.element_type_id);
  2488. if (resolver.HasNewWork()) {
  2489. return ResolveResult::Retry();
  2490. }
  2491. return ResolveAs<SemIR::UnboundElementType>(
  2492. resolver,
  2493. {.type_id = SemIR::TypeType::SingletonTypeId,
  2494. .class_type_id =
  2495. resolver.local_context().types().GetTypeIdForTypeConstantId(
  2496. class_const_id),
  2497. .element_type_id =
  2498. resolver.local_context().types().GetTypeIdForTypeConstantId(
  2499. elem_const_id)});
  2500. }
  2501. // Tries to resolve the InstId, returning a canonical constant when ready, or
  2502. // `None` if more has been added to the stack. This is the same as
  2503. // TryResolveInst, except that it may resolve symbolic constants as canonical
  2504. // constants instead of as constants associated with a particular generic.
  2505. //
  2506. // TODO: Consider refactoring the body to a helper in order to eliminate
  2507. // recursion.
  2508. // NOLINTNEXTLINE(misc-no-recursion)
  2509. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  2510. SemIR::InstId inst_id,
  2511. SemIR::ConstantId const_id)
  2512. -> ResolveResult {
  2513. if (SemIR::IsSingletonInstId(inst_id)) {
  2514. CARBON_CHECK(!const_id.has_value());
  2515. // Constants for builtins can be directly copied.
  2516. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  2517. }
  2518. auto untyped_inst = resolver.import_insts().Get(inst_id);
  2519. CARBON_KIND_SWITCH(untyped_inst) {
  2520. case CARBON_KIND(SemIR::AdaptDecl inst): {
  2521. return TryResolveTypedInst(resolver, inst, inst_id);
  2522. }
  2523. case CARBON_KIND(SemIR::ArrayType inst): {
  2524. return TryResolveTypedInst(resolver, inst);
  2525. }
  2526. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  2527. return TryResolveTypedInst(resolver, inst, const_id);
  2528. }
  2529. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  2530. return TryResolveTypedInst(resolver, inst);
  2531. }
  2532. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  2533. return TryResolveTypedInst(resolver, inst);
  2534. }
  2535. case CARBON_KIND(SemIR::BaseDecl inst): {
  2536. return TryResolveTypedInst(resolver, inst, inst_id);
  2537. }
  2538. case CARBON_KIND(SemIR::BindAlias inst): {
  2539. return TryResolveTypedInst(resolver, inst);
  2540. }
  2541. case SemIR::BindName::Kind: {
  2542. // TODO: Should we be resolving BindNames at all?
  2543. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  2544. }
  2545. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  2546. return TryResolveTypedInst(resolver, inst);
  2547. }
  2548. case CARBON_KIND(SemIR::BoundMethod inst): {
  2549. return TryResolveTypedInst(resolver, inst);
  2550. }
  2551. case CARBON_KIND(SemIR::Call inst): {
  2552. return TryResolveTypedInst(resolver, inst);
  2553. }
  2554. case CARBON_KIND(SemIR::ClassDecl inst): {
  2555. return TryResolveTypedInst(resolver, inst, const_id);
  2556. }
  2557. case CARBON_KIND(SemIR::ClassType inst): {
  2558. return TryResolveTypedInst(resolver, inst);
  2559. }
  2560. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  2561. return TryResolveTypedInst(resolver, inst);
  2562. }
  2563. case CARBON_KIND(SemIR::ConstType inst): {
  2564. return TryResolveTypedInst(resolver, inst);
  2565. }
  2566. case CARBON_KIND(SemIR::ExportDecl inst): {
  2567. return TryResolveTypedInst(resolver, inst);
  2568. }
  2569. case CARBON_KIND(SemIR::FacetAccessType inst): {
  2570. return TryResolveTypedInst(resolver, inst);
  2571. }
  2572. case CARBON_KIND(SemIR::FacetAccessWitness inst): {
  2573. return TryResolveTypedInst(resolver, inst);
  2574. }
  2575. case CARBON_KIND(SemIR::FacetType inst): {
  2576. return TryResolveTypedInst(resolver, inst);
  2577. }
  2578. case CARBON_KIND(SemIR::FacetValue inst): {
  2579. return TryResolveTypedInst(resolver, inst);
  2580. }
  2581. case CARBON_KIND(SemIR::FieldDecl inst): {
  2582. return TryResolveTypedInst(resolver, inst, inst_id);
  2583. }
  2584. case CARBON_KIND(SemIR::FunctionDecl inst): {
  2585. return TryResolveTypedInst(resolver, inst, const_id);
  2586. }
  2587. case CARBON_KIND(SemIR::FunctionType inst): {
  2588. return TryResolveTypedInst(resolver, inst);
  2589. }
  2590. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  2591. return TryResolveTypedInst(resolver, inst);
  2592. }
  2593. case CARBON_KIND(SemIR::GenericClassType inst): {
  2594. return TryResolveTypedInst(resolver, inst);
  2595. }
  2596. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  2597. return TryResolveTypedInst(resolver, inst);
  2598. }
  2599. case CARBON_KIND(SemIR::ImplDecl inst): {
  2600. return TryResolveTypedInst(resolver, inst, const_id);
  2601. }
  2602. case CARBON_KIND(SemIR::ImplWitness inst): {
  2603. return TryResolveTypedInst(resolver, inst);
  2604. }
  2605. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  2606. return TryResolveTypedInst(resolver, inst);
  2607. }
  2608. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  2609. return TryResolveTypedInst(resolver, inst, inst_id);
  2610. }
  2611. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  2612. return TryResolveTypedInst(resolver, inst, const_id);
  2613. }
  2614. case CARBON_KIND(SemIR::IntValue inst): {
  2615. return TryResolveTypedInst(resolver, inst);
  2616. }
  2617. case CARBON_KIND(SemIR::IntType inst): {
  2618. return TryResolveTypedInst(resolver, inst);
  2619. }
  2620. case CARBON_KIND(SemIR::Namespace inst): {
  2621. return TryResolveTypedInst(resolver, inst, inst_id);
  2622. }
  2623. case CARBON_KIND(SemIR::PointerType inst): {
  2624. return TryResolveTypedInst(resolver, inst);
  2625. }
  2626. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  2627. return TryResolveTypedInst(resolver, inst);
  2628. }
  2629. case CARBON_KIND(SemIR::SpecificFunction inst): {
  2630. return TryResolveTypedInst(resolver, inst);
  2631. }
  2632. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  2633. return TryResolveTypedInst(resolver, inst);
  2634. }
  2635. case CARBON_KIND(SemIR::StructType inst): {
  2636. return TryResolveTypedInst(resolver, inst);
  2637. }
  2638. case CARBON_KIND(SemIR::StructValue inst): {
  2639. return TryResolveTypedInst(resolver, inst);
  2640. }
  2641. case CARBON_KIND(SemIR::TupleType inst): {
  2642. return TryResolveTypedInst(resolver, inst);
  2643. }
  2644. case CARBON_KIND(SemIR::TupleValue inst): {
  2645. return TryResolveTypedInst(resolver, inst);
  2646. }
  2647. case CARBON_KIND(SemIR::UnboundElementType inst): {
  2648. return TryResolveTypedInst(resolver, inst);
  2649. }
  2650. case CARBON_KIND(SemIR::Vtable inst): {
  2651. return TryResolveTypedInst(resolver, inst);
  2652. }
  2653. default: {
  2654. // This instruction might have a constant value of a different kind.
  2655. auto constant_inst_id =
  2656. resolver.import_constant_values().GetConstantInstId(inst_id);
  2657. if (constant_inst_id == inst_id) {
  2658. // Produce a diagnostic to provide a source location with the CHECK
  2659. // failure.
  2660. resolver.local_context().TODO(
  2661. SemIR::LocId(AddImportIRInst(resolver, inst_id)),
  2662. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  2663. CARBON_FATAL("TryResolveInst on unsupported instruction kind {0}",
  2664. untyped_inst.kind());
  2665. }
  2666. // Try to resolve the constant value instead. Note that this can only
  2667. // retry once.
  2668. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  2669. constant_inst_id) == constant_inst_id,
  2670. "Constant value of constant instruction should refer to "
  2671. "the same instruction");
  2672. return TryResolveInstCanonical(resolver, constant_inst_id, const_id);
  2673. }
  2674. }
  2675. }
  2676. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  2677. // more has been added to the stack. A similar API is followed for all
  2678. // following TryResolveTypedInst helper functions.
  2679. //
  2680. // `const_id` is `None` unless we've tried to resolve this instruction
  2681. // before, in which case it's the previous result.
  2682. //
  2683. // TODO: Error is returned when support is missing, but that should go away.
  2684. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  2685. SemIR::ConstantId const_id) -> ResolveResult {
  2686. auto inst_const_id = resolver.import_constant_values().Get(inst_id);
  2687. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  2688. return TryResolveInstCanonical(resolver, inst_id, const_id);
  2689. }
  2690. // Try to import the generic. This might add new work.
  2691. const auto& symbolic_const =
  2692. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  2693. auto generic_const_id =
  2694. GetLocalConstantId(resolver, symbolic_const.generic_id);
  2695. auto inner_const_id = SemIR::ConstantId::None;
  2696. if (const_id.has_value()) {
  2697. // For the third phase, extract the constant value that
  2698. // TryResolveInstCanonical produced previously.
  2699. inner_const_id = resolver.local_constant_values().Get(
  2700. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  2701. }
  2702. // Import the constant and rebuild the symbolic constant data.
  2703. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  2704. if (!result.const_id.has_value()) {
  2705. // First phase: TryResolveInstCanoncial needs a retry.
  2706. return result;
  2707. }
  2708. if (!const_id.has_value()) {
  2709. // Second phase: we have created an abstract constant. Create a
  2710. // corresponding generic constant.
  2711. if (symbolic_const.generic_id.has_value()) {
  2712. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  2713. {.inst_id =
  2714. resolver.local_constant_values().GetInstId(result.const_id),
  2715. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  2716. .index = symbolic_const.index,
  2717. .dependence = symbolic_const.dependence});
  2718. if (result.decl_id.has_value()) {
  2719. // Overwrite the abstract symbolic constant given initially to the
  2720. // declaration with its final concrete symbolic value.
  2721. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  2722. }
  2723. }
  2724. } else {
  2725. // Third phase: perform a consistency check and produce the constant we
  2726. // created in the second phase.
  2727. CARBON_CHECK(result.const_id == inner_const_id,
  2728. "Constant value changed in third phase.");
  2729. result.const_id = const_id;
  2730. }
  2731. return result;
  2732. }
  2733. // Resolves and returns the local contents for an imported instruction block
  2734. // of constant instructions.
  2735. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  2736. SemIR::InstBlockId import_block_id)
  2737. -> llvm::SmallVector<SemIR::InstId> {
  2738. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  2739. llvm::SmallVector<SemIR::InstId> inst_ids;
  2740. inst_ids.reserve(import_block.size());
  2741. for (auto import_inst_id : import_block) {
  2742. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  2743. resolver.ResolveOneInst(import_inst_id)));
  2744. }
  2745. return inst_ids;
  2746. }
  2747. // Resolves and returns a local eval block for a region of an imported
  2748. // generic.
  2749. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  2750. const SemIR::Generic& import_generic,
  2751. SemIR::GenericId generic_id,
  2752. SemIR::GenericInstIndex::Region region)
  2753. -> SemIR::InstBlockId {
  2754. auto import_block_id = import_generic.GetEvalBlock(region);
  2755. if (!import_block_id.has_value()) {
  2756. return SemIR::InstBlockId::None;
  2757. }
  2758. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2759. return RebuildGenericEvalBlock(resolver.local_context(), generic_id, region,
  2760. inst_ids);
  2761. }
  2762. // Fills in the remaining information in a partially-imported generic.
  2763. // NOLINTNEXTLINE(misc-no-recursion)
  2764. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  2765. ImportContext::PendingGeneric pending)
  2766. -> void {
  2767. const auto& import_generic =
  2768. resolver.import_generics().Get(pending.import_id);
  2769. // Load the bindings for the generic eagerly; they're used to form the self
  2770. // specific.
  2771. // TODO: Avoid recursion.
  2772. for (auto binding_id : resolver.local_inst_blocks().Get(
  2773. resolver.local_generics().Get(pending.local_id).bindings_id)) {
  2774. LoadImportRef(resolver.local_context(), binding_id);
  2775. }
  2776. // Don't store the local generic between calls: the generics list can be
  2777. // reallocated by ResolveLocalEvalBlock importing more specifics.
  2778. auto decl_block_id =
  2779. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2780. SemIR::GenericInstIndex::Region::Declaration);
  2781. resolver.local_generics().Get(pending.local_id).decl_block_id = decl_block_id;
  2782. auto local_decl_id = resolver.local_generics().Get(pending.local_id).decl_id;
  2783. auto self_specific_id = MakeSelfSpecific(resolver.local_context(),
  2784. local_decl_id, pending.local_id);
  2785. resolver.local_generics().Get(pending.local_id).self_specific_id =
  2786. self_specific_id;
  2787. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  2788. .local_id = self_specific_id});
  2789. auto definition_block_id =
  2790. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2791. SemIR::GenericInstIndex::Region::Definition);
  2792. resolver.local_generics().Get(pending.local_id).definition_block_id =
  2793. definition_block_id;
  2794. }
  2795. // Resolves and returns a local inst block of constant instructions
  2796. // corresponding to an imported inst block.
  2797. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  2798. SemIR::InstBlockId import_block_id)
  2799. -> SemIR::InstBlockId {
  2800. if (!import_block_id.has_value()) {
  2801. return SemIR::InstBlockId::None;
  2802. }
  2803. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2804. return resolver.local_inst_blocks().Add(inst_ids);
  2805. }
  2806. // Fills in the remaining information in a partially-imported specific.
  2807. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  2808. ImportContext::PendingSpecific pending)
  2809. -> void {
  2810. const auto& import_specific =
  2811. resolver.import_specifics().Get(pending.import_id);
  2812. // Don't store the local specific between calls: the specifics list can be
  2813. // reallocated by ResolveLocalInstBlock importing more specifics.
  2814. if (!resolver.local_specifics()
  2815. .Get(pending.local_id)
  2816. .decl_block_id.has_value()) {
  2817. auto decl_block_id =
  2818. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  2819. resolver.local_specifics().Get(pending.local_id).decl_block_id =
  2820. decl_block_id;
  2821. }
  2822. if (!resolver.local_specifics()
  2823. .Get(pending.local_id)
  2824. .definition_block_id.has_value() &&
  2825. import_specific.definition_block_id.has_value()) {
  2826. auto definition_block_id =
  2827. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  2828. resolver.local_specifics().Get(pending.local_id).definition_block_id =
  2829. definition_block_id;
  2830. }
  2831. }
  2832. // Perform any work that we deferred until the end of the main Resolve loop.
  2833. // NOLINTNEXTLINE(misc-no-recursion)
  2834. auto ImportRefResolver::PerformPendingWork() -> void {
  2835. // Note that the individual Finish steps can add new pending work, so keep
  2836. // going until we have no more work to do.
  2837. while (!pending_generics().empty() || !pending_specifics().empty()) {
  2838. // Process generics in the order that we added them because a later
  2839. // generic might refer to an earlier one, and the calls to
  2840. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  2841. // state.
  2842. // TODO: Import the generic eval block rather than calling
  2843. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  2844. // NOLINTNEXTLINE(modernize-loop-convert)
  2845. for (size_t i = 0; i != pending_generics().size(); ++i) {
  2846. FinishPendingGeneric(*this, pending_generics()[i]);
  2847. }
  2848. pending_generics().clear();
  2849. while (!pending_specifics().empty()) {
  2850. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  2851. }
  2852. }
  2853. }
  2854. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  2855. // loaded (including the one pointed at directly by the ImportRef), and the
  2856. // final instruction's type ID.
  2857. //
  2858. // This addresses cases where an ImportRefUnloaded may point at another
  2859. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  2860. // constant-evaluated version of the instruction to work with.
  2861. static auto GetInstForLoad(Context& context,
  2862. SemIR::ImportIRInstId import_ir_inst_id)
  2863. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  2864. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  2865. {}, SemIR::TypeId::None};
  2866. auto& [import_ir_insts, type_id] = result;
  2867. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  2868. // The first ImportIRInst is added directly because the IR doesn't need to be
  2869. // localized.
  2870. import_ir_insts.push_back(import_ir_inst);
  2871. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2872. while (true) {
  2873. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  2874. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  2875. if (!import_ref) {
  2876. type_id = cursor_inst.type_id();
  2877. return result;
  2878. }
  2879. import_ir_inst =
  2880. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  2881. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2882. import_ir_insts.push_back(
  2883. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::None,
  2884. .is_export = false,
  2885. .sem_ir = cursor_ir}),
  2886. .inst_id = import_ir_inst.inst_id});
  2887. }
  2888. }
  2889. // NOLINTNEXTLINE(misc-no-recursion)
  2890. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  2891. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  2892. if (!inst) {
  2893. return;
  2894. }
  2895. auto [indirect_insts, load_type_id] =
  2896. GetInstForLoad(context, inst->import_ir_inst_id);
  2897. // The last indirect instruction is the one to resolve. Pop it here because
  2898. // Resolve will assign the constant.
  2899. auto load_ir_inst = indirect_insts.pop_back_val();
  2900. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  2901. // The resolver calls into Context to create instructions. Don't register
  2902. // those instructions as part of the enclosing generic scope if they're
  2903. // dependent on a generic parameter.
  2904. context.generic_region_stack().Push();
  2905. auto type_id = resolver.ResolveType(load_type_id);
  2906. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  2907. context.generic_region_stack().Pop();
  2908. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  2909. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  2910. // TryEvalInst, which we want to avoid with ImportRefs.
  2911. context.sem_ir().insts().Set(
  2912. inst_id,
  2913. SemIR::ImportRefLoaded{.type_id = type_id,
  2914. .import_ir_inst_id = inst->import_ir_inst_id,
  2915. .entity_name_id = inst->entity_name_id});
  2916. // Store the constant for both the ImportRefLoaded and indirect instructions.
  2917. context.constant_values().Set(inst_id, constant_id);
  2918. for (const auto& import_ir_inst : indirect_insts) {
  2919. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  2920. import_ir_inst.inst_id, constant_id);
  2921. }
  2922. }
  2923. auto ImportImplsFromApiFile(Context& context) -> void {
  2924. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  2925. auto& import_ir = context.import_irs().Get(import_ir_id);
  2926. if (!import_ir.sem_ir) {
  2927. return;
  2928. }
  2929. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  2930. // Resolve the imported impl to a local impl ID.
  2931. ImportImpl(context, import_ir_id, impl_id);
  2932. }
  2933. }
  2934. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  2935. SemIR::ImplId impl_id) -> void {
  2936. ImportRefResolver resolver(context, import_ir_id);
  2937. context.generic_region_stack().Push();
  2938. resolver.Resolve(context.import_irs()
  2939. .Get(import_ir_id)
  2940. .sem_ir->impls()
  2941. .Get(impl_id)
  2942. .first_decl_id());
  2943. context.generic_region_stack().Pop();
  2944. }
  2945. // Returns whether a parse node associated with an imported instruction of kind
  2946. // `imported_kind` is usable as the location of a corresponding local
  2947. // instruction of kind `local_kind`.
  2948. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  2949. SemIR::InstKind local_kind) -> bool {
  2950. if (imported_kind == local_kind) {
  2951. return true;
  2952. }
  2953. if (imported_kind == SemIR::ImportDecl::Kind &&
  2954. local_kind == SemIR::Namespace::Kind) {
  2955. static_assert(
  2956. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  2957. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  2958. return true;
  2959. }
  2960. return false;
  2961. }
  2962. namespace Internal {
  2963. auto CheckCompatibleImportedNodeKind(Context& context,
  2964. SemIR::ImportIRInstId imported_loc_id,
  2965. SemIR::InstKind kind) -> void {
  2966. auto& import_ir_inst = context.import_ir_insts().Get(imported_loc_id);
  2967. const auto* import_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2968. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
  2969. CARBON_CHECK(
  2970. HasCompatibleImportedNodeKind(imported_kind, kind),
  2971. "Node of kind {0} created with location of imported node of kind {1}",
  2972. kind, imported_kind);
  2973. }
  2974. } // namespace Internal
  2975. } // namespace Carbon::Check