import_ref.cpp 117 KB

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