import_ref.cpp 138 KB

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