import_ref.cpp 98 KB

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