import_ref.cpp 126 KB

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