import_ref.cpp 139 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384
  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. .special_function_kind = import_function.special_function_kind,
  1774. .builtin_function_kind = import_function.builtin_function_kind}});
  1775. function_decl.type_id = GetFunctionType(
  1776. context.local_context(), function_decl.function_id, specific_id);
  1777. // Write the function ID and type into the FunctionDecl.
  1778. auto function_const_id =
  1779. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  1780. return {function_decl.function_id, function_const_id};
  1781. }
  1782. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1783. SemIR::FunctionDecl inst,
  1784. SemIR::ConstantId function_const_id)
  1785. -> ResolveResult {
  1786. const auto& import_function =
  1787. resolver.import_functions().Get(inst.function_id);
  1788. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  1789. if (!function_const_id.has_value()) {
  1790. auto import_specific_id = resolver.import_types()
  1791. .GetAs<SemIR::FunctionType>(inst.type_id)
  1792. .specific_id;
  1793. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1794. if (resolver.HasNewWork()) {
  1795. // This is the end of the first phase. Don't make a new function yet if
  1796. // we already have new work.
  1797. return ResolveResult::Retry();
  1798. }
  1799. // On the second phase, create a forward declaration of the interface.
  1800. auto specific_id =
  1801. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1802. std::tie(function_id, function_const_id) =
  1803. MakeFunctionDecl(resolver, import_function, specific_id);
  1804. } else {
  1805. // On the third phase, compute the function ID from the constant value of
  1806. // the declaration.
  1807. auto function_const_inst = resolver.local_insts().Get(
  1808. resolver.local_constant_values().GetInstId(function_const_id));
  1809. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1810. function_const_inst.type_id());
  1811. function_id = function_type.function_id;
  1812. }
  1813. auto return_type_const_id = SemIR::ConstantId::None;
  1814. if (import_function.return_slot_pattern_id.has_value()) {
  1815. return_type_const_id = GetLocalConstantId(
  1816. resolver, resolver.import_insts().GetAttachedType(
  1817. import_function.return_slot_pattern_id));
  1818. }
  1819. auto parent_scope_id =
  1820. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1821. LoadLocalPatternConstantIds(resolver,
  1822. import_function.implicit_param_patterns_id);
  1823. LoadLocalPatternConstantIds(resolver, import_function.param_patterns_id);
  1824. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1825. auto& new_function = resolver.local_functions().Get(function_id);
  1826. if (resolver.HasNewWork()) {
  1827. return ResolveResult::Retry(function_const_id,
  1828. new_function.first_decl_id());
  1829. }
  1830. // Add the function declaration.
  1831. new_function.parent_scope_id = parent_scope_id;
  1832. SemIR::InstId self_param_id = SemIR::InstId::None;
  1833. new_function.implicit_param_patterns_id = GetLocalParamPatternsId(
  1834. resolver, import_function.implicit_param_patterns_id, &self_param_id);
  1835. new_function.self_param_id = self_param_id;
  1836. new_function.param_patterns_id =
  1837. GetLocalParamPatternsId(resolver, import_function.param_patterns_id);
  1838. new_function.return_slot_pattern_id = GetLocalReturnSlotPatternId(
  1839. resolver, import_function.return_slot_pattern_id, return_type_const_id);
  1840. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1841. generic_data);
  1842. if (import_function.definition_id.has_value()) {
  1843. new_function.definition_id = new_function.first_owning_decl_id;
  1844. }
  1845. return ResolveResult::Done(function_const_id, new_function.first_decl_id());
  1846. }
  1847. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1848. SemIR::FunctionType inst) -> ResolveResult {
  1849. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1850. auto fn_val_id = GetLocalConstantInstId(
  1851. resolver,
  1852. resolver.import_functions().Get(inst.function_id).first_decl_id());
  1853. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1854. if (resolver.HasNewWork()) {
  1855. return ResolveResult::Retry();
  1856. }
  1857. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  1858. return ResolveAs<SemIR::FunctionType>(
  1859. resolver, {.type_id = SemIR::TypeType::TypeId,
  1860. .function_id = resolver.local_types()
  1861. .GetAs<SemIR::FunctionType>(fn_type_id)
  1862. .function_id,
  1863. .specific_id = GetOrAddLocalSpecific(
  1864. resolver, inst.specific_id, specific_data)});
  1865. }
  1866. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1867. SemIR::FunctionTypeWithSelfType inst)
  1868. -> ResolveResult {
  1869. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1870. auto interface_function_type_id =
  1871. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  1872. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  1873. if (resolver.HasNewWork()) {
  1874. return ResolveResult::Retry();
  1875. }
  1876. return ResolveAs<SemIR::FunctionTypeWithSelfType>(
  1877. resolver, {.type_id = SemIR::TypeType::TypeId,
  1878. .interface_function_type_id = interface_function_type_id,
  1879. .self_id = self_id});
  1880. }
  1881. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1882. SemIR::GenericClassType inst) -> ResolveResult {
  1883. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1884. auto class_val_id = GetLocalConstantInstId(
  1885. resolver,
  1886. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1887. if (resolver.HasNewWork()) {
  1888. return ResolveResult::Retry();
  1889. }
  1890. auto class_val = resolver.local_insts().Get(class_val_id);
  1891. CARBON_CHECK(
  1892. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1893. return ResolveResult::Done(
  1894. resolver.local_types().GetConstantId(class_val.type_id()));
  1895. }
  1896. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1897. SemIR::GenericInterfaceType inst)
  1898. -> ResolveResult {
  1899. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1900. auto interface_val_id = GetLocalConstantInstId(
  1901. resolver,
  1902. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  1903. if (resolver.HasNewWork()) {
  1904. return ResolveResult::Retry();
  1905. }
  1906. auto interface_val = resolver.local_insts().Get(interface_val_id);
  1907. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  1908. interface_val.type_id()));
  1909. return ResolveResult::Done(
  1910. resolver.local_types().GetConstantId(interface_val.type_id()));
  1911. }
  1912. // Make a declaration of an impl. This is done as a separate step from
  1913. // importing the impl definition in order to resolve cycles.
  1914. static auto MakeImplDeclaration(ImportContext& context,
  1915. const SemIR::Impl& import_impl,
  1916. SemIR::InstId witness_id)
  1917. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1918. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  1919. .decl_block_id = SemIR::InstBlockId::Empty};
  1920. auto impl_decl_id = AddPlaceholderImportedInst(
  1921. context, import_impl.latest_decl_id(), impl_decl);
  1922. impl_decl.impl_id = context.local_impls().Add(
  1923. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  1924. {.self_id = SemIR::TypeInstId::None,
  1925. .constraint_id = SemIR::TypeInstId::None,
  1926. .interface = SemIR::SpecificInterface::None,
  1927. .witness_id = witness_id}});
  1928. // Write the impl ID into the ImplDecl.
  1929. auto impl_const_id =
  1930. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  1931. return {impl_decl.impl_id, impl_const_id};
  1932. }
  1933. // Imports the definition of an impl.
  1934. static auto AddImplDefinition(ImportContext& context,
  1935. const SemIR::Impl& import_impl,
  1936. SemIR::Impl& new_impl) -> void {
  1937. new_impl.definition_id = new_impl.first_owning_decl_id;
  1938. new_impl.defined = true;
  1939. if (import_impl.scope_id.has_value()) {
  1940. new_impl.scope_id = context.local_name_scopes().Add(
  1941. new_impl.first_owning_decl_id, SemIR::NameId::None,
  1942. new_impl.parent_scope_id);
  1943. // Import the contents of the definition scope, if we might need it. Name
  1944. // lookup is never performed into this scope by a user of the impl, so
  1945. // this is only necessary in the same library that defined the impl, in
  1946. // order to support defining members of the impl out of line in the impl
  1947. // file when the impl is defined in the API file.
  1948. // TODO: Check to see if this impl is owned by the API file, rather than
  1949. // merely being imported into it.
  1950. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1951. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  1952. const auto& import_scope =
  1953. context.import_name_scopes().Get(import_impl.scope_id);
  1954. // Push a block so that we can add scoped instructions to it.
  1955. context.local_context().inst_block_stack().Push();
  1956. AddNameScopeImportRefs(context, import_scope, new_scope);
  1957. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  1958. }
  1959. }
  1960. }
  1961. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1962. SemIR::ImplDecl inst,
  1963. SemIR::ConstantId impl_const_id)
  1964. -> ResolveResult {
  1965. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1966. // functions. Factor out the commonality.
  1967. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  1968. auto specific_interface_data =
  1969. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  1970. SemIR::ImplId impl_id = SemIR::ImplId::None;
  1971. if (!impl_const_id.has_value()) {
  1972. if (resolver.HasNewWork()) {
  1973. // This is the end of the first phase. Don't make a new impl yet if we
  1974. // already have new work.
  1975. return ResolveResult::Retry();
  1976. }
  1977. // On the second phase, create a forward declaration of the impl for any
  1978. // recursive references.
  1979. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  1980. std::tie(impl_id, impl_const_id) =
  1981. MakeImplDeclaration(resolver, import_impl, witness_id);
  1982. } else {
  1983. // On the third phase, compute the impl ID from the "constant value" of
  1984. // the declaration, which is a reference to the created ImplDecl.
  1985. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  1986. resolver.local_constant_values().GetInstId(impl_const_id));
  1987. impl_id = impl_const_inst.impl_id;
  1988. }
  1989. // Load constants for the definition.
  1990. auto parent_scope_id =
  1991. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  1992. LoadLocalPatternConstantIds(resolver, import_impl.implicit_param_patterns_id);
  1993. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  1994. auto self_const_id = GetLocalConstantId(
  1995. resolver,
  1996. resolver.import_constant_values().GetAttached(import_impl.self_id));
  1997. auto constraint_const_id = GetLocalConstantId(
  1998. resolver,
  1999. resolver.import_constant_values().GetAttached(import_impl.constraint_id));
  2000. auto& new_impl = resolver.local_impls().Get(impl_id);
  2001. if (resolver.HasNewWork()) {
  2002. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2003. }
  2004. new_impl.parent_scope_id = parent_scope_id;
  2005. new_impl.implicit_param_patterns_id =
  2006. GetLocalParamPatternsId(resolver, import_impl.implicit_param_patterns_id);
  2007. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  2008. generic_data);
  2009. // Create instructions for self and constraint to hold the symbolic constant
  2010. // value for a generic impl.
  2011. new_impl.self_id = resolver.local_ir().types().GetAsTypeInstId(
  2012. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId, import_impl.self_id,
  2013. self_const_id));
  2014. new_impl.constraint_id = resolver.local_ir().types().GetAsTypeInstId(
  2015. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId,
  2016. import_impl.constraint_id, constraint_const_id));
  2017. new_impl.interface = GetLocalSpecificInterface(
  2018. resolver, import_impl.interface, specific_interface_data);
  2019. if (import_impl.is_complete()) {
  2020. AddImplDefinition(resolver, import_impl, new_impl);
  2021. }
  2022. // If the `impl` is declared in the API file corresponding to the current
  2023. // file, add this to impl lookup so that it can be found by redeclarations
  2024. // in the current file.
  2025. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2026. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2027. }
  2028. return ResolveResult::Done(impl_const_id, new_impl.first_decl_id());
  2029. }
  2030. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2031. SemIR::ImportRefLoaded /*inst*/,
  2032. SemIR::InstId inst_id) -> ResolveResult {
  2033. // Return the constant for the instruction of the imported constant.
  2034. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2035. CARBON_CHECK(constant_id.has_value(),
  2036. "Loaded import ref has no constant value");
  2037. if (!constant_id.is_constant()) {
  2038. resolver.local_context().TODO(
  2039. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2040. return ResolveResult::Done(constant_id);
  2041. }
  2042. auto new_constant_id = GetLocalConstantId(
  2043. resolver, resolver.import_constant_values().GetInstId(constant_id));
  2044. return RetryOrDone(resolver, new_constant_id);
  2045. }
  2046. // Make a declaration of an interface. This is done as a separate step from
  2047. // importing the interface definition in order to resolve cycles.
  2048. static auto MakeInterfaceDecl(ImportContext& context,
  2049. const SemIR::Interface& import_interface,
  2050. SemIR::SpecificId enclosing_specific_id)
  2051. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2052. SemIR::InterfaceDecl interface_decl = {
  2053. .type_id = SemIR::TypeType::TypeId,
  2054. .interface_id = SemIR::InterfaceId::None,
  2055. .decl_block_id = SemIR::InstBlockId::Empty};
  2056. auto interface_decl_id = AddPlaceholderImportedInst(
  2057. context, import_interface.first_owning_decl_id, interface_decl);
  2058. // Start with an incomplete interface.
  2059. interface_decl.interface_id = context.local_interfaces().Add(
  2060. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2061. import_interface),
  2062. {}});
  2063. if (import_interface.has_parameters()) {
  2064. interface_decl.type_id = GetGenericInterfaceType(
  2065. context.local_context(), interface_decl.interface_id,
  2066. enclosing_specific_id);
  2067. }
  2068. // Write the interface ID into the InterfaceDecl.
  2069. auto interface_const_id = ReplacePlaceholderImportedInst(
  2070. context, interface_decl_id, interface_decl);
  2071. return {interface_decl.interface_id, interface_const_id};
  2072. }
  2073. // Imports the definition for an interface that has been imported as a forward
  2074. // declaration.
  2075. static auto AddInterfaceDefinition(ImportContext& context,
  2076. const SemIR::Interface& import_interface,
  2077. SemIR::Interface& new_interface,
  2078. SemIR::InstId self_param_id) -> void {
  2079. new_interface.scope_id = context.local_name_scopes().Add(
  2080. new_interface.first_owning_decl_id, SemIR::NameId::None,
  2081. new_interface.parent_scope_id);
  2082. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  2083. new_scope.set_is_interface_definition();
  2084. const auto& import_scope =
  2085. context.import_name_scopes().Get(import_interface.scope_id);
  2086. // Push a block so that we can add scoped instructions to it.
  2087. context.local_context().inst_block_stack().Push();
  2088. AddNameScopeImportRefs(context, import_scope, new_scope);
  2089. new_interface.associated_entities_id = AddAssociatedEntities(
  2090. context, new_interface.scope_id, import_interface.associated_entities_id);
  2091. new_interface.body_block_id =
  2092. context.local_context().inst_block_stack().Pop();
  2093. new_interface.self_param_id = self_param_id;
  2094. CARBON_CHECK(import_scope.extended_scopes().empty(),
  2095. "Interfaces don't currently have extended scopes to support.");
  2096. }
  2097. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2098. SemIR::InterfaceDecl inst,
  2099. SemIR::ConstantId interface_const_id)
  2100. -> ResolveResult {
  2101. const auto& import_interface =
  2102. resolver.import_interfaces().Get(inst.interface_id);
  2103. SemIR::InterfaceId interface_id = SemIR::InterfaceId::None;
  2104. if (!interface_const_id.has_value()) {
  2105. auto import_specific_id = SemIR::SpecificId::None;
  2106. if (auto import_generic_interface_type =
  2107. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2108. inst.type_id)) {
  2109. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2110. }
  2111. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2112. if (resolver.HasNewWork()) {
  2113. // This is the end of the first phase. Don't make a new interface yet if
  2114. // we already have new work.
  2115. return ResolveResult::Retry();
  2116. }
  2117. // On the second phase, create a forward declaration of the interface.
  2118. auto enclosing_specific_id =
  2119. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2120. std::tie(interface_id, interface_const_id) =
  2121. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2122. } else {
  2123. // On the third phase, compute the interface ID from the constant value of
  2124. // the declaration.
  2125. auto interface_const_inst = resolver.local_insts().Get(
  2126. resolver.local_constant_values().GetInstId(interface_const_id));
  2127. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2128. const SemIR::FacetTypeInfo& facet_type_info =
  2129. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2130. auto interface_type = facet_type_info.TryAsSingleInterface();
  2131. CARBON_CHECK(interface_type);
  2132. interface_id = interface_type->interface_id;
  2133. } else {
  2134. auto generic_interface_type =
  2135. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2136. interface_const_inst.type_id());
  2137. interface_id = generic_interface_type.interface_id;
  2138. }
  2139. }
  2140. auto parent_scope_id =
  2141. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2142. LoadLocalPatternConstantIds(resolver,
  2143. import_interface.implicit_param_patterns_id);
  2144. LoadLocalPatternConstantIds(resolver, import_interface.param_patterns_id);
  2145. auto generic_data =
  2146. GetLocalGenericData(resolver, import_interface.generic_id);
  2147. std::optional<SemIR::InstId> self_param_id;
  2148. if (import_interface.is_complete()) {
  2149. self_param_id =
  2150. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2151. }
  2152. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2153. if (resolver.HasNewWork()) {
  2154. return ResolveResult::Retry(interface_const_id,
  2155. new_interface.first_decl_id());
  2156. }
  2157. new_interface.parent_scope_id = parent_scope_id;
  2158. new_interface.implicit_param_patterns_id = GetLocalParamPatternsId(
  2159. resolver, import_interface.implicit_param_patterns_id);
  2160. new_interface.param_patterns_id =
  2161. GetLocalParamPatternsId(resolver, import_interface.param_patterns_id);
  2162. SetGenericData(resolver, import_interface.generic_id,
  2163. new_interface.generic_id, generic_data);
  2164. if (import_interface.is_complete()) {
  2165. CARBON_CHECK(self_param_id);
  2166. AddInterfaceDefinition(resolver, import_interface, new_interface,
  2167. *self_param_id);
  2168. }
  2169. return ResolveResult::Done(interface_const_id, new_interface.first_decl_id());
  2170. }
  2171. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2172. SemIR::FacetAccessType inst) -> ResolveResult {
  2173. auto facet_value_inst_id =
  2174. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2175. if (resolver.HasNewWork()) {
  2176. return ResolveResult::Retry();
  2177. }
  2178. return ResolveAs<SemIR::FacetAccessType>(
  2179. resolver, {.type_id = SemIR::TypeType::TypeId,
  2180. .facet_value_inst_id = facet_value_inst_id});
  2181. }
  2182. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2183. SemIR::FacetType inst) -> ResolveResult {
  2184. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2185. const SemIR::FacetTypeInfo& import_facet_type_info =
  2186. resolver.import_facet_types().Get(inst.facet_type_id);
  2187. for (auto interface : import_facet_type_info.extend_constraints) {
  2188. // We discard this here and recompute it below instead of saving it to avoid
  2189. // allocations.
  2190. GetLocalSpecificInterfaceData(resolver, interface);
  2191. }
  2192. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2193. // We discard this here and recompute it below instead of saving it to avoid
  2194. // allocations.
  2195. GetLocalSpecificInterfaceData(resolver, interface);
  2196. }
  2197. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2198. GetLocalConstantInstId(resolver, rewrite.lhs_id);
  2199. GetLocalConstantInstId(resolver, rewrite.rhs_id);
  2200. }
  2201. if (resolver.HasNewWork()) {
  2202. return ResolveResult::Retry();
  2203. }
  2204. SemIR::FacetTypeInfo local_facet_type_info = {
  2205. .other_requirements = import_facet_type_info.other_requirements};
  2206. local_facet_type_info.extend_constraints.reserve(
  2207. import_facet_type_info.extend_constraints.size());
  2208. for (auto interface : import_facet_type_info.extend_constraints) {
  2209. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2210. local_facet_type_info.extend_constraints.push_back(
  2211. GetLocalSpecificInterface(resolver, interface, data));
  2212. }
  2213. local_facet_type_info.self_impls_constraints.reserve(
  2214. import_facet_type_info.self_impls_constraints.size());
  2215. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2216. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2217. local_facet_type_info.self_impls_constraints.push_back(
  2218. GetLocalSpecificInterface(resolver, interface, data));
  2219. }
  2220. local_facet_type_info.rewrite_constraints.reserve(
  2221. import_facet_type_info.rewrite_constraints.size());
  2222. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2223. local_facet_type_info.rewrite_constraints.push_back(
  2224. {.lhs_id = GetLocalConstantInstId(resolver, rewrite.lhs_id),
  2225. .rhs_id = GetLocalConstantInstId(resolver, rewrite.rhs_id)});
  2226. }
  2227. // TODO: Also process the other requirements.
  2228. SemIR::FacetTypeId facet_type_id =
  2229. resolver.local_facet_types().Add(std::move(local_facet_type_info));
  2230. return ResolveAs<SemIR::FacetType>(
  2231. resolver,
  2232. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  2233. }
  2234. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2235. SemIR::FacetValue inst) -> ResolveResult {
  2236. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2237. auto type_inst_id = GetLocalTypeInstId(resolver, inst.type_inst_id);
  2238. auto witnesses = GetLocalInstBlockContents(resolver, inst.witnesses_block_id);
  2239. if (resolver.HasNewWork()) {
  2240. return ResolveResult::Retry();
  2241. }
  2242. return ResolveAs<SemIR::FacetValue>(
  2243. resolver,
  2244. {.type_id =
  2245. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2246. .type_inst_id = type_inst_id,
  2247. .witnesses_block_id = GetLocalCanonicalInstBlockId(
  2248. resolver, inst.witnesses_block_id, witnesses)});
  2249. }
  2250. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2251. SemIR::LookupImplWitness inst)
  2252. -> ResolveResult {
  2253. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2254. SemIR::WitnessType::TypeInstId);
  2255. auto query_self_inst_id =
  2256. GetLocalConstantInstId(resolver, inst.query_self_inst_id);
  2257. const auto& import_specific_interface =
  2258. resolver.import_specific_interfaces().Get(
  2259. inst.query_specific_interface_id);
  2260. auto data =
  2261. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  2262. if (resolver.HasNewWork()) {
  2263. return ResolveResult::Retry();
  2264. }
  2265. auto specific_interface =
  2266. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  2267. auto query_specific_interface_id =
  2268. resolver.local_specific_interfaces().Add(specific_interface);
  2269. return ResolveAs<SemIR::LookupImplWitness>(
  2270. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2271. SemIR::WitnessType::TypeInstId),
  2272. .query_self_inst_id = query_self_inst_id,
  2273. .query_specific_interface_id = query_specific_interface_id});
  2274. }
  2275. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2276. SemIR::ImplWitness inst) -> ResolveResult {
  2277. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2278. SemIR::WitnessType::TypeInstId);
  2279. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2280. auto witness_table_id =
  2281. GetLocalConstantInstId(resolver, inst.witness_table_id);
  2282. if (resolver.HasNewWork()) {
  2283. return ResolveResult::Retry();
  2284. }
  2285. auto specific_id =
  2286. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2287. return ResolveAs<SemIR::ImplWitness>(
  2288. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2289. SemIR::WitnessType::TypeInstId),
  2290. .witness_table_id = witness_table_id,
  2291. .specific_id = specific_id});
  2292. }
  2293. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2294. SemIR::ImplWitnessAccess inst)
  2295. -> ResolveResult {
  2296. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2297. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2298. if (resolver.HasNewWork()) {
  2299. return ResolveResult::Retry();
  2300. }
  2301. return ResolveAs<SemIR::ImplWitnessAccess>(
  2302. resolver,
  2303. {.type_id =
  2304. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2305. .witness_id = witness_id,
  2306. .index = inst.index});
  2307. }
  2308. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2309. SemIR::ImplWitnessTable inst,
  2310. SemIR::InstId import_inst_id) -> ResolveResult {
  2311. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2312. auto import_decl_inst_id = import_impl.first_decl_id();
  2313. auto local_decl_inst_id =
  2314. GetLocalConstantInstId(resolver, import_decl_inst_id);
  2315. if (resolver.HasNewWork()) {
  2316. return ResolveResult::Retry();
  2317. }
  2318. auto impl_decl =
  2319. resolver.local_insts().GetAs<SemIR::ImplDecl>(local_decl_inst_id);
  2320. auto impl_id = impl_decl.impl_id;
  2321. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  2322. // Create a corresponding instruction to represent the table.
  2323. auto inst_id = AddImportedInst<SemIR::ImplWitnessTable>(
  2324. resolver, import_inst_id,
  2325. {.elements_id = elements_id, .impl_id = impl_id});
  2326. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  2327. inst_id);
  2328. }
  2329. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2330. SemIR::IntValue inst) -> ResolveResult {
  2331. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2332. if (resolver.HasNewWork()) {
  2333. return ResolveResult::Retry();
  2334. }
  2335. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2336. // to add a new canonical int in this IR.
  2337. auto int_id = inst.int_id.is_embedded_value()
  2338. ? inst.int_id
  2339. : resolver.local_ints().AddSigned(
  2340. resolver.import_ints().Get(inst.int_id));
  2341. return ResolveAs<SemIR::IntValue>(
  2342. resolver,
  2343. {.type_id =
  2344. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2345. .int_id = int_id});
  2346. }
  2347. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2348. SemIR::IntType inst) -> ResolveResult {
  2349. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2350. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2351. if (resolver.HasNewWork()) {
  2352. return ResolveResult::Retry();
  2353. }
  2354. return ResolveAs<SemIR::IntType>(resolver,
  2355. {.type_id = SemIR::TypeType::TypeId,
  2356. .int_kind = inst.int_kind,
  2357. .bit_width_id = bit_width_id});
  2358. }
  2359. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2360. SemIR::Namespace inst,
  2361. SemIR::InstId import_inst_id) -> ResolveResult {
  2362. const auto& name_scope =
  2363. resolver.import_name_scopes().Get(inst.name_scope_id);
  2364. // A package from a different file becomes a child of the package here, as it
  2365. // would be if it were imported.
  2366. auto parent_scope_id =
  2367. inst.name_scope_id == SemIR::NameScopeId::Package
  2368. ? SemIR::NameScopeId::Package
  2369. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2370. if (resolver.HasNewWork()) {
  2371. return ResolveResult::Retry();
  2372. }
  2373. auto namespace_type_id = GetSingletonType(resolver.local_context(),
  2374. SemIR::NamespaceType::TypeInstId);
  2375. auto namespace_decl =
  2376. SemIR::Namespace{.type_id = namespace_type_id,
  2377. .name_scope_id = SemIR::NameScopeId::None,
  2378. .import_id = SemIR::AbsoluteInstId::None};
  2379. auto inst_id =
  2380. AddPlaceholderImportedInst(resolver, import_inst_id, namespace_decl);
  2381. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2382. namespace_decl.name_scope_id =
  2383. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2384. // Namespaces from this package are eagerly imported, so anything we load here
  2385. // must be a closed import.
  2386. resolver.local_name_scopes()
  2387. .Get(namespace_decl.name_scope_id)
  2388. .set_is_closed_import(true);
  2389. auto namespace_const_id =
  2390. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  2391. return {.const_id = namespace_const_id};
  2392. }
  2393. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2394. SemIR::PatternType inst) -> ResolveResult {
  2395. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2396. auto scrutinee_type_inst_id =
  2397. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  2398. if (resolver.HasNewWork()) {
  2399. return ResolveResult::Retry();
  2400. }
  2401. return ResolveAs<SemIR::PatternType>(
  2402. resolver, {.type_id = SemIR::TypeType::TypeId,
  2403. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  2404. }
  2405. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2406. SemIR::PointerType inst) -> ResolveResult {
  2407. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2408. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  2409. if (resolver.HasNewWork()) {
  2410. return ResolveResult::Retry();
  2411. }
  2412. return ResolveAs<SemIR::PointerType>(
  2413. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  2414. }
  2415. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2416. SemIR::RequireCompleteType inst)
  2417. -> ResolveResult {
  2418. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2419. SemIR::WitnessType::TypeInstId);
  2420. auto complete_type_inst_id =
  2421. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  2422. if (resolver.HasNewWork()) {
  2423. return ResolveResult::Retry();
  2424. }
  2425. return ResolveAs<SemIR::RequireCompleteType>(
  2426. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2427. SemIR::WitnessType::TypeInstId),
  2428. .complete_type_inst_id = complete_type_inst_id});
  2429. }
  2430. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2431. SemIR::SpecificFunction inst) -> ResolveResult {
  2432. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2433. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2434. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2435. if (resolver.HasNewWork()) {
  2436. return ResolveResult::Retry();
  2437. }
  2438. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2439. type_const_id);
  2440. auto specific_id =
  2441. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2442. return ResolveAs<SemIR::SpecificFunction>(
  2443. resolver,
  2444. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2445. }
  2446. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2447. SemIR::SpecificImplFunction inst)
  2448. -> ResolveResult {
  2449. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2450. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2451. if (resolver.HasNewWork()) {
  2452. return ResolveResult::Retry();
  2453. }
  2454. auto type_id = GetSingletonType(resolver.local_context(),
  2455. SemIR::SpecificFunctionType::TypeInstId);
  2456. auto specific_id =
  2457. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2458. return ResolveAs<SemIR::SpecificImplFunction>(
  2459. resolver,
  2460. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2461. }
  2462. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2463. SemIR::StructType inst) -> ResolveResult {
  2464. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2465. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2466. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  2467. field_type_inst_ids.reserve(orig_fields.size());
  2468. for (auto field : orig_fields) {
  2469. field_type_inst_ids.push_back(
  2470. GetLocalTypeInstId(resolver, field.type_inst_id));
  2471. }
  2472. if (resolver.HasNewWork()) {
  2473. return ResolveResult::Retry();
  2474. }
  2475. // Prepare a vector of fields for GetStructType.
  2476. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2477. new_fields.reserve(orig_fields.size());
  2478. for (auto [orig_field, field_type_inst_id] :
  2479. llvm::zip(orig_fields, field_type_inst_ids)) {
  2480. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2481. new_fields.push_back(
  2482. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  2483. }
  2484. return ResolveAs<SemIR::StructType>(
  2485. resolver, {.type_id = SemIR::TypeType::TypeId,
  2486. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2487. new_fields)});
  2488. }
  2489. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2490. SemIR::StructValue inst) -> ResolveResult {
  2491. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2492. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2493. if (resolver.HasNewWork()) {
  2494. return ResolveResult::Retry();
  2495. }
  2496. return ResolveAs<SemIR::StructValue>(
  2497. resolver,
  2498. {.type_id =
  2499. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2500. .elements_id =
  2501. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2502. }
  2503. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2504. SemIR::TupleType inst) -> ResolveResult {
  2505. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2506. auto orig_type_inst_ids =
  2507. resolver.import_inst_blocks().Get(inst.type_elements_id);
  2508. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  2509. // type system that its holding `TypeInstId` elements.
  2510. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  2511. type_inst_ids.reserve(orig_type_inst_ids.size());
  2512. for (auto elem_type_inst_id :
  2513. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  2514. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  2515. }
  2516. if (resolver.HasNewWork()) {
  2517. return ResolveResult::Retry();
  2518. }
  2519. return ResolveAs<SemIR::TupleType>(
  2520. resolver, {.type_id = SemIR::TypeType::TypeId,
  2521. .type_elements_id = GetLocalCanonicalInstBlockId(
  2522. resolver, inst.type_elements_id, type_inst_ids)});
  2523. }
  2524. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2525. SemIR::TupleValue inst) -> ResolveResult {
  2526. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2527. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2528. if (resolver.HasNewWork()) {
  2529. return ResolveResult::Retry();
  2530. }
  2531. return ResolveAs<SemIR::TupleValue>(
  2532. resolver,
  2533. {.type_id =
  2534. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2535. .elements_id =
  2536. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2537. }
  2538. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2539. SemIR::UnboundElementType inst)
  2540. -> ResolveResult {
  2541. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2542. auto class_const_inst_id =
  2543. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  2544. auto elem_const_inst_id =
  2545. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  2546. if (resolver.HasNewWork()) {
  2547. return ResolveResult::Retry();
  2548. }
  2549. return ResolveAs<SemIR::UnboundElementType>(
  2550. resolver, {.type_id = SemIR::TypeType::TypeId,
  2551. .class_type_inst_id = class_const_inst_id,
  2552. .element_type_inst_id = elem_const_inst_id});
  2553. }
  2554. // Tries to resolve the InstId, returning a canonical constant when ready, or
  2555. // `None` if more has been added to the stack. This is the same as
  2556. // TryResolveInst, except that it may resolve symbolic constants as canonical
  2557. // constants instead of as constants associated with a particular generic.
  2558. //
  2559. // TODO: Consider refactoring the body to a helper in order to eliminate
  2560. // recursion.
  2561. // NOLINTNEXTLINE(misc-no-recursion)
  2562. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  2563. SemIR::InstId inst_id,
  2564. SemIR::ConstantId const_id)
  2565. -> ResolveResult {
  2566. if (SemIR::IsSingletonInstId(inst_id)) {
  2567. CARBON_CHECK(!const_id.has_value());
  2568. // Constants for builtins can be directly copied.
  2569. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  2570. }
  2571. auto untyped_inst = resolver.import_insts().Get(inst_id);
  2572. CARBON_KIND_SWITCH(untyped_inst) {
  2573. case CARBON_KIND(SemIR::AdaptDecl inst): {
  2574. return TryResolveTypedInst(resolver, inst, inst_id);
  2575. }
  2576. case CARBON_KIND(SemIR::ArrayType inst): {
  2577. return TryResolveTypedInst(resolver, inst);
  2578. }
  2579. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  2580. return TryResolveTypedInst(resolver, inst, const_id);
  2581. }
  2582. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  2583. return TryResolveTypedInst(resolver, inst);
  2584. }
  2585. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  2586. return TryResolveTypedInst(resolver, inst);
  2587. }
  2588. case CARBON_KIND(SemIR::BaseDecl inst): {
  2589. return TryResolveTypedInst(resolver, inst, inst_id);
  2590. }
  2591. case CARBON_KIND(SemIR::BindAlias inst): {
  2592. return TryResolveTypedInst(resolver, inst);
  2593. }
  2594. case SemIR::BindName::Kind: {
  2595. // TODO: Should we be resolving BindNames at all?
  2596. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  2597. }
  2598. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  2599. return TryResolveTypedInst(resolver, inst);
  2600. }
  2601. case CARBON_KIND(SemIR::BoundMethod inst): {
  2602. return TryResolveTypedInst(resolver, inst);
  2603. }
  2604. case CARBON_KIND(SemIR::Call inst): {
  2605. return TryResolveTypedInst(resolver, inst);
  2606. }
  2607. case CARBON_KIND(SemIR::ClassDecl inst): {
  2608. return TryResolveTypedInst(resolver, inst, const_id);
  2609. }
  2610. case CARBON_KIND(SemIR::ClassType inst): {
  2611. return TryResolveTypedInst(resolver, inst);
  2612. }
  2613. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  2614. return TryResolveTypedInst(resolver, inst);
  2615. }
  2616. case CARBON_KIND(SemIR::ConstType inst): {
  2617. return TryResolveTypedInst(resolver, inst);
  2618. }
  2619. case CARBON_KIND(SemIR::ExportDecl inst): {
  2620. return TryResolveTypedInst(resolver, inst);
  2621. }
  2622. case CARBON_KIND(SemIR::FacetAccessType inst): {
  2623. return TryResolveTypedInst(resolver, inst);
  2624. }
  2625. case CARBON_KIND(SemIR::FacetType inst): {
  2626. return TryResolveTypedInst(resolver, inst);
  2627. }
  2628. case CARBON_KIND(SemIR::FacetValue inst): {
  2629. return TryResolveTypedInst(resolver, inst);
  2630. }
  2631. case CARBON_KIND(SemIR::FieldDecl inst): {
  2632. return TryResolveTypedInst(resolver, inst, inst_id);
  2633. }
  2634. case CARBON_KIND(SemIR::FunctionDecl inst): {
  2635. return TryResolveTypedInst(resolver, inst, const_id);
  2636. }
  2637. case CARBON_KIND(SemIR::FunctionType inst): {
  2638. return TryResolveTypedInst(resolver, inst);
  2639. }
  2640. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  2641. return TryResolveTypedInst(resolver, inst);
  2642. }
  2643. case CARBON_KIND(SemIR::GenericClassType inst): {
  2644. return TryResolveTypedInst(resolver, inst);
  2645. }
  2646. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  2647. return TryResolveTypedInst(resolver, inst);
  2648. }
  2649. case CARBON_KIND(SemIR::ImplDecl inst): {
  2650. return TryResolveTypedInst(resolver, inst, const_id);
  2651. }
  2652. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  2653. return TryResolveTypedInst(resolver, inst);
  2654. }
  2655. case CARBON_KIND(SemIR::ImplWitness inst): {
  2656. return TryResolveTypedInst(resolver, inst);
  2657. }
  2658. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  2659. return TryResolveTypedInst(resolver, inst);
  2660. }
  2661. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  2662. return TryResolveTypedInst(resolver, inst, inst_id);
  2663. }
  2664. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  2665. return TryResolveTypedInst(resolver, inst, inst_id);
  2666. }
  2667. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  2668. return TryResolveTypedInst(resolver, inst, const_id);
  2669. }
  2670. case CARBON_KIND(SemIR::IntValue inst): {
  2671. return TryResolveTypedInst(resolver, inst);
  2672. }
  2673. case CARBON_KIND(SemIR::IntType inst): {
  2674. return TryResolveTypedInst(resolver, inst);
  2675. }
  2676. case CARBON_KIND(SemIR::Namespace inst): {
  2677. return TryResolveTypedInst(resolver, inst, inst_id);
  2678. }
  2679. case CARBON_KIND(SemIR::PatternType inst): {
  2680. return TryResolveTypedInst(resolver, inst);
  2681. }
  2682. case CARBON_KIND(SemIR::PointerType inst): {
  2683. return TryResolveTypedInst(resolver, inst);
  2684. }
  2685. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  2686. return TryResolveTypedInst(resolver, inst);
  2687. }
  2688. case CARBON_KIND(SemIR::SpecificFunction inst): {
  2689. return TryResolveTypedInst(resolver, inst);
  2690. }
  2691. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  2692. return TryResolveTypedInst(resolver, inst);
  2693. }
  2694. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  2695. return TryResolveTypedInst(resolver, inst);
  2696. }
  2697. case CARBON_KIND(SemIR::StructType inst): {
  2698. return TryResolveTypedInst(resolver, inst);
  2699. }
  2700. case CARBON_KIND(SemIR::StructValue inst): {
  2701. return TryResolveTypedInst(resolver, inst);
  2702. }
  2703. case CARBON_KIND(SemIR::TupleType inst): {
  2704. return TryResolveTypedInst(resolver, inst);
  2705. }
  2706. case CARBON_KIND(SemIR::TupleValue inst): {
  2707. return TryResolveTypedInst(resolver, inst);
  2708. }
  2709. case CARBON_KIND(SemIR::UnboundElementType inst): {
  2710. return TryResolveTypedInst(resolver, inst);
  2711. }
  2712. case CARBON_KIND(SemIR::Vtable inst): {
  2713. return TryResolveTypedInst(resolver, inst);
  2714. }
  2715. default: {
  2716. // This instruction might have a constant value of a different kind.
  2717. auto constant_inst_id =
  2718. resolver.import_constant_values().GetConstantInstId(inst_id);
  2719. if (constant_inst_id == inst_id) {
  2720. // Produce a diagnostic to provide a source location with the CHECK
  2721. // failure.
  2722. resolver.local_context().TODO(
  2723. SemIR::LocId(AddImportIRInst(resolver, inst_id)),
  2724. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  2725. CARBON_FATAL("TryResolveInst on unsupported instruction kind {0}",
  2726. untyped_inst.kind());
  2727. }
  2728. // Try to resolve the constant value instead. Note that this can only
  2729. // retry once.
  2730. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  2731. constant_inst_id) == constant_inst_id,
  2732. "Constant value of constant instruction should refer to "
  2733. "the same instruction");
  2734. return TryResolveInstCanonical(resolver, constant_inst_id, const_id);
  2735. }
  2736. }
  2737. }
  2738. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  2739. // more has been added to the stack. A similar API is followed for all
  2740. // following TryResolveTypedInst helper functions.
  2741. //
  2742. // `const_id` is `None` unless we've tried to resolve this instruction
  2743. // before, in which case it's the previous result.
  2744. //
  2745. // TODO: Error is returned when support is missing, but that should go away.
  2746. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  2747. SemIR::ConstantId const_id) -> ResolveResult {
  2748. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  2749. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  2750. return TryResolveInstCanonical(resolver, inst_id, const_id);
  2751. }
  2752. // Try to import the generic. This might add new work.
  2753. const auto& symbolic_const =
  2754. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  2755. auto generic_const_id =
  2756. GetLocalConstantId(resolver, symbolic_const.generic_id);
  2757. auto inner_const_id = SemIR::ConstantId::None;
  2758. if (const_id.has_value()) {
  2759. // For the third phase, extract the constant value that
  2760. // TryResolveInstCanonical produced previously.
  2761. inner_const_id = resolver.local_constant_values().GetAttached(
  2762. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  2763. }
  2764. // Import the constant and rebuild the symbolic constant data.
  2765. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  2766. if (!result.const_id.has_value()) {
  2767. // First phase: TryResolveInstCanoncial needs a retry.
  2768. return result;
  2769. }
  2770. if (!const_id.has_value()) {
  2771. // Second phase: we have created an unattached constant. Create a
  2772. // corresponding attached constant.
  2773. if (symbolic_const.generic_id.has_value()) {
  2774. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  2775. {.inst_id =
  2776. resolver.local_constant_values().GetInstId(result.const_id),
  2777. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  2778. .index = symbolic_const.index,
  2779. .dependence = symbolic_const.dependence});
  2780. if (result.decl_id.has_value()) {
  2781. // Overwrite the unattached symbolic constant given initially to the
  2782. // declaration with its final attached symbolic value.
  2783. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  2784. }
  2785. }
  2786. } else {
  2787. // Third phase: perform a consistency check and produce the constant we
  2788. // created in the second phase.
  2789. CARBON_CHECK(result.const_id == inner_const_id,
  2790. "Constant value changed in third phase.");
  2791. result.const_id = const_id;
  2792. }
  2793. return result;
  2794. }
  2795. // Resolves and returns the local contents for an imported instruction block
  2796. // of constant instructions.
  2797. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  2798. SemIR::InstBlockId import_block_id)
  2799. -> llvm::SmallVector<SemIR::InstId> {
  2800. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  2801. llvm::SmallVector<SemIR::InstId> inst_ids;
  2802. inst_ids.reserve(import_block.size());
  2803. for (auto import_inst_id : import_block) {
  2804. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  2805. resolver.ResolveOneInst(import_inst_id)));
  2806. }
  2807. return inst_ids;
  2808. }
  2809. // Resolves and returns a local eval block for a region of an imported
  2810. // generic.
  2811. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  2812. const SemIR::Generic& import_generic,
  2813. SemIR::GenericId generic_id,
  2814. SemIR::GenericInstIndex::Region region)
  2815. -> SemIR::InstBlockId {
  2816. auto import_block_id = import_generic.GetEvalBlock(region);
  2817. if (!import_block_id.has_value()) {
  2818. return SemIR::InstBlockId::None;
  2819. }
  2820. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2821. auto eval_block_id = RebuildGenericEvalBlock(resolver.local_context(),
  2822. generic_id, region, inst_ids);
  2823. // Set the locations of the instructions in the inst block to match those of
  2824. // the imported instructions.
  2825. for (auto [import_inst_id, local_inst_id] :
  2826. llvm::zip(resolver.import_inst_blocks().Get(import_block_id),
  2827. resolver.local_inst_blocks().Get(eval_block_id))) {
  2828. auto import_ir_inst_id = AddImportIRInst(resolver, import_inst_id);
  2829. resolver.local_insts().SetLocId(local_inst_id, import_ir_inst_id);
  2830. }
  2831. return eval_block_id;
  2832. }
  2833. // Fills in the remaining information in a partially-imported generic.
  2834. // NOLINTNEXTLINE(misc-no-recursion)
  2835. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  2836. ImportContext::PendingGeneric pending)
  2837. -> void {
  2838. const auto& import_generic =
  2839. resolver.import_generics().Get(pending.import_id);
  2840. // Load the bindings for the generic eagerly; they're used to form the self
  2841. // specific.
  2842. // TODO: Avoid recursion.
  2843. for (auto binding_id : resolver.local_inst_blocks().Get(
  2844. resolver.local_generics().Get(pending.local_id).bindings_id)) {
  2845. LoadImportRef(resolver.local_context(), binding_id);
  2846. }
  2847. // Don't store the local generic between calls: the generics list can be
  2848. // reallocated by ResolveLocalEvalBlock importing more specifics.
  2849. auto decl_block_id =
  2850. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2851. SemIR::GenericInstIndex::Region::Declaration);
  2852. resolver.local_generics().Get(pending.local_id).decl_block_id = decl_block_id;
  2853. auto local_decl_id = resolver.local_generics().Get(pending.local_id).decl_id;
  2854. auto self_specific_id = MakeSelfSpecific(
  2855. resolver.local_context(), SemIR::LocId(local_decl_id), pending.local_id);
  2856. resolver.local_generics().Get(pending.local_id).self_specific_id =
  2857. self_specific_id;
  2858. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  2859. .local_id = self_specific_id});
  2860. auto definition_block_id =
  2861. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2862. SemIR::GenericInstIndex::Region::Definition);
  2863. resolver.local_generics().Get(pending.local_id).definition_block_id =
  2864. definition_block_id;
  2865. }
  2866. // Resolves and returns a local inst block of constant instructions
  2867. // corresponding to an imported inst block.
  2868. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  2869. SemIR::InstBlockId import_block_id)
  2870. -> SemIR::InstBlockId {
  2871. if (!import_block_id.has_value()) {
  2872. return SemIR::InstBlockId::None;
  2873. }
  2874. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2875. return resolver.local_inst_blocks().Add(inst_ids);
  2876. }
  2877. // Fills in the remaining information in a partially-imported specific.
  2878. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  2879. ImportContext::PendingSpecific pending)
  2880. -> void {
  2881. const auto& import_specific =
  2882. resolver.import_specifics().Get(pending.import_id);
  2883. // Don't store the local specific between calls: the specifics list can be
  2884. // reallocated by ResolveLocalInstBlock importing more specifics.
  2885. if (!resolver.local_specifics()
  2886. .Get(pending.local_id)
  2887. .decl_block_id.has_value()) {
  2888. auto decl_block_id =
  2889. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  2890. resolver.local_specifics().Get(pending.local_id).decl_block_id =
  2891. decl_block_id;
  2892. }
  2893. if (!resolver.local_specifics()
  2894. .Get(pending.local_id)
  2895. .definition_block_id.has_value() &&
  2896. import_specific.definition_block_id.has_value()) {
  2897. auto definition_block_id =
  2898. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  2899. resolver.local_specifics().Get(pending.local_id).definition_block_id =
  2900. definition_block_id;
  2901. }
  2902. }
  2903. // Perform any work that we deferred until the end of the main Resolve loop.
  2904. // NOLINTNEXTLINE(misc-no-recursion)
  2905. auto ImportRefResolver::PerformPendingWork() -> void {
  2906. // Note that the individual Finish steps can add new pending work, so keep
  2907. // going until we have no more work to do.
  2908. while (!pending_generics().empty() || !pending_specifics().empty()) {
  2909. // Process generics in the order that we added them because a later
  2910. // generic might refer to an earlier one, and the calls to
  2911. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  2912. // state.
  2913. // TODO: Import the generic eval block rather than calling
  2914. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  2915. // NOLINTNEXTLINE(modernize-loop-convert)
  2916. for (size_t i = 0; i != pending_generics().size(); ++i) {
  2917. FinishPendingGeneric(*this, pending_generics()[i]);
  2918. }
  2919. pending_generics().clear();
  2920. while (!pending_specifics().empty()) {
  2921. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  2922. }
  2923. }
  2924. }
  2925. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  2926. // loaded (including the one pointed at directly by the ImportRef), and the
  2927. // final instruction's type ID.
  2928. //
  2929. // This addresses cases where an ImportRefUnloaded may point at another
  2930. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  2931. // constant-evaluated version of the instruction to work with.
  2932. static auto GetInstForLoad(Context& context,
  2933. SemIR::ImportIRInstId import_ir_inst_id)
  2934. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  2935. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  2936. {}, SemIR::TypeId::None};
  2937. auto& [import_ir_insts, type_id] = result;
  2938. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  2939. // The first ImportIRInst is added directly because the IR doesn't need to be
  2940. // localized.
  2941. import_ir_insts.push_back(import_ir_inst);
  2942. const auto* cursor_ir =
  2943. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  2944. while (true) {
  2945. auto cursor_inst =
  2946. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  2947. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  2948. if (!import_ref) {
  2949. type_id = cursor_inst.type_id();
  2950. return result;
  2951. }
  2952. import_ir_inst =
  2953. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  2954. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  2955. import_ir_insts.push_back(SemIR::ImportIRInst(
  2956. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  2957. .is_export = false,
  2958. .sem_ir = cursor_ir}),
  2959. import_ir_inst.inst_id()));
  2960. }
  2961. }
  2962. // NOLINTNEXTLINE(misc-no-recursion)
  2963. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  2964. #if LLVM_ADDRESS_SANITIZER_BUILD
  2965. // Under ASan, invalidate all of our value stores on any import in order to
  2966. // flush out bugs where pointers and references to entities are held across
  2967. // imports.
  2968. context.classes().Invalidate();
  2969. context.entity_names().Invalidate();
  2970. context.facet_types().Invalidate();
  2971. context.functions().Invalidate();
  2972. context.generics().Invalidate();
  2973. context.impls().Invalidate();
  2974. context.interfaces().Invalidate();
  2975. context.specifics().Invalidate();
  2976. #endif
  2977. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  2978. if (!inst) {
  2979. return;
  2980. }
  2981. auto [indirect_insts, load_type_id] =
  2982. GetInstForLoad(context, inst->import_ir_inst_id);
  2983. // The last indirect instruction is the one to resolve. Pop it here because
  2984. // Resolve will assign the constant.
  2985. auto load_ir_inst = indirect_insts.pop_back_val();
  2986. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  2987. auto type_id = resolver.ResolveType(load_type_id);
  2988. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  2989. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  2990. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  2991. // TryEvalInst, which we want to avoid with ImportRefs.
  2992. context.sem_ir().insts().Set(
  2993. inst_id,
  2994. SemIR::ImportRefLoaded{.type_id = type_id,
  2995. .import_ir_inst_id = inst->import_ir_inst_id,
  2996. .entity_name_id = inst->entity_name_id});
  2997. // Store the constant for both the ImportRefLoaded and indirect instructions.
  2998. context.constant_values().Set(inst_id, constant_id);
  2999. for (const auto& import_ir_inst : indirect_insts) {
  3000. context.import_ir_constant_values()[import_ir_inst.ir_id().index].Set(
  3001. import_ir_inst.inst_id(), constant_id);
  3002. }
  3003. }
  3004. auto ImportImplsFromApiFile(Context& context) -> void {
  3005. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  3006. auto& import_ir = context.import_irs().Get(import_ir_id);
  3007. if (!import_ir.sem_ir) {
  3008. return;
  3009. }
  3010. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  3011. // Resolve the imported impl to a local impl ID.
  3012. ImportImpl(context, import_ir_id, impl_id);
  3013. }
  3014. }
  3015. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  3016. SemIR::ImplId impl_id) -> void {
  3017. ImportRefResolver resolver(&context, import_ir_id);
  3018. resolver.Resolve(context.import_irs()
  3019. .Get(import_ir_id)
  3020. .sem_ir->impls()
  3021. .Get(impl_id)
  3022. .first_decl_id());
  3023. }
  3024. // Returns whether a parse node associated with an imported instruction of kind
  3025. // `imported_kind` is usable as the location of a corresponding local
  3026. // instruction of kind `local_kind`.
  3027. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  3028. SemIR::InstKind local_kind) -> bool {
  3029. if (imported_kind == local_kind) {
  3030. return true;
  3031. }
  3032. if (imported_kind == SemIR::ImportDecl::Kind &&
  3033. local_kind == SemIR::Namespace::Kind) {
  3034. static_assert(
  3035. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  3036. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  3037. return true;
  3038. }
  3039. return false;
  3040. }
  3041. namespace Internal {
  3042. auto CheckCompatibleImportedNodeKind(Context& context,
  3043. SemIR::ImportIRInstId imported_loc_id,
  3044. SemIR::InstKind kind) -> void {
  3045. auto& import_ir_inst = context.import_ir_insts().Get(imported_loc_id);
  3046. const auto* import_ir =
  3047. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3048. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id()).kind();
  3049. CARBON_CHECK(
  3050. HasCompatibleImportedNodeKind(imported_kind, kind),
  3051. "Node of kind {0} created with location of imported node of kind {1}",
  3052. kind, imported_kind);
  3053. }
  3054. } // namespace Internal
  3055. } // namespace Carbon::Check