import_ref.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  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/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Adds the ImportIR, excluding the update to the check_ir_map.
  20. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  21. -> SemIR::ImportIRId {
  22. context.import_ir_constant_values().push_back(
  23. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  24. return context.import_irs().Add(import_ir);
  25. }
  26. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  27. auto ir_id = SemIR::ImportIRId::Invalid;
  28. if (import_ir.sem_ir != nullptr) {
  29. ir_id = AddImportIR(context, import_ir);
  30. } else {
  31. // We don't have a check_ir_id, so add without touching check_ir_map.
  32. ir_id = InternalAddImportIR(context, import_ir);
  33. }
  34. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl)
  35. << "ApiForImpl must be the first IR";
  36. }
  37. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  38. -> SemIR::ImportIRId {
  39. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  40. if (!ir_id.is_valid()) {
  41. // Note this updates check_ir_map.
  42. ir_id = InternalAddImportIR(context, import_ir);
  43. } else if (import_ir.is_export) {
  44. // We're processing an `export import`. In case the IR was indirectly added
  45. // as a non-export, mark it as an export.
  46. context.import_irs().Get(ir_id).is_export = true;
  47. }
  48. return ir_id;
  49. }
  50. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  51. SemIR::EntityNameId entity_name_id) -> SemIR::InstId {
  52. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  53. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  54. .entity_name_id = entity_name_id};
  55. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  56. SemIR::LocIdAndInst(import_ir_inst_id, inst));
  57. // ImportRefs have a dedicated block because this may be called during
  58. // processing where the instruction shouldn't be inserted in the current inst
  59. // block.
  60. context.import_ref_ids().push_back(import_ref_id);
  61. return import_ref_id;
  62. }
  63. auto GetCanonicalImportIRInst(Context& context, const SemIR::File* cursor_ir,
  64. SemIR::InstId cursor_inst_id)
  65. -> SemIR::ImportIRInst {
  66. while (true) {
  67. auto inst = cursor_ir->insts().Get(cursor_inst_id);
  68. CARBON_KIND_SWITCH(inst) {
  69. case CARBON_KIND(SemIR::ExportDecl bind_export): {
  70. cursor_inst_id = bind_export.value_id;
  71. continue;
  72. }
  73. case SemIR::ImportRefLoaded::Kind:
  74. case SemIR::ImportRefUnloaded::Kind: {
  75. auto import_ref = inst.As<SemIR::AnyImportRef>();
  76. auto import_ir_inst =
  77. cursor_ir->import_ir_insts().Get(import_ref.import_ir_inst_id);
  78. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  79. cursor_inst_id = import_ir_inst.inst_id;
  80. continue;
  81. }
  82. default: {
  83. auto ir_id = SemIR::ImportIRId::Invalid;
  84. if (cursor_ir != &context.sem_ir()) {
  85. // This uses AddImportIR in case it was indirectly found, which can
  86. // happen with two or more steps of exports.
  87. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  88. .is_export = false,
  89. .sem_ir = cursor_ir});
  90. }
  91. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  92. }
  93. }
  94. }
  95. }
  96. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  97. SemIR::ImportIRInst prev_import_ir_inst,
  98. SemIR::ImportIRId new_ir_id,
  99. const SemIR::File* new_import_ir,
  100. SemIR::InstId new_inst_id) -> void {
  101. auto new_import_ir_inst =
  102. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  103. if (new_import_ir_inst == prev_import_ir_inst) {
  104. return;
  105. }
  106. auto conflict_id =
  107. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id},
  108. SemIR::EntityNameId::Invalid);
  109. context.DiagnoseDuplicateName(conflict_id, prev_id);
  110. }
  111. // Resolves an instruction from an imported IR into a constant referring to the
  112. // current IR.
  113. //
  114. // Calling Resolve on an instruction operates in an iterative manner, tracking
  115. // Work items on work_stack_. At a high level, the loop is:
  116. //
  117. // 1. If a constant value is already known for the work item, and we're
  118. // processing it for the first time, it's considered resolved.
  119. // - The constant check avoids performance costs of deduplication on add.
  120. // - If `retry` is set, we process it again, because it didn't complete last
  121. // time, even though we have a constant value already.
  122. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  123. // - For instructions that can be forward declared, if we don't already have
  124. // a constant value from a previous attempt at resolution, start by making
  125. // a forward declared constant value to address circular references.
  126. // - Gather all input constants.
  127. // - Gathering constants directly adds unresolved values to work_stack_.
  128. // - If any need to be resolved (HasNewWork), return Retry(): this
  129. // instruction needs two calls to complete.
  130. // - If the constant value is already known because we have made a forward
  131. // declaration, pass it to Retry(). It will be passed to future attempts
  132. // to resolve this instruction so the earlier work can be found, and will
  133. // be made available for other instructions to use.
  134. // - The second attempt to resolve this instruction must produce the same
  135. // constant, because the value may have already been used by resolved
  136. // instructions.
  137. // - Build any necessary IR structures, and return the output constant.
  138. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  139. // remain, and may no longer be at the top of the stack; set `retry` on it so
  140. // we'll make sure to run it again later.
  141. //
  142. // TryResolveInst/TryResolveTypedInst can complete in one call for a given
  143. // instruction, but should always complete within two calls. However, due to the
  144. // chance of a second call, it's important to reserve all expensive logic until
  145. // it's been established that input constants are available; this in particular
  146. // includes GetTypeIdForTypeConstant calls which do a hash table lookup.
  147. //
  148. // TODO: Fix class `extern` handling and merging, rewrite tests.
  149. // - check/testdata/class/cross_package_import.carbon
  150. // - check/testdata/class/extern.carbon
  151. // TODO: Fix function `extern` handling and merging, rewrite tests.
  152. // - check/testdata/function/declaration/import.carbon
  153. // - check/testdata/packages/cross_package_import.carbon
  154. class ImportRefResolver {
  155. public:
  156. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  157. : context_(context),
  158. import_ir_id_(import_ir_id),
  159. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  160. // Iteratively resolves an imported instruction's inner references until a
  161. // constant ID referencing the current IR is produced. See the class comment
  162. // for more details.
  163. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  164. work_stack_.push_back({.inst_id = inst_id});
  165. while (!work_stack_.empty()) {
  166. auto work = work_stack_.back();
  167. CARBON_CHECK(work.inst_id.is_valid());
  168. // Step 1: check for a constant value.
  169. auto existing = FindResolvedConstId(work.inst_id);
  170. if (existing.const_id.is_valid() && !work.retry) {
  171. work_stack_.pop_back();
  172. continue;
  173. }
  174. // Step 2: resolve the instruction.
  175. auto initial_work = work_stack_.size();
  176. auto [new_const_id, finished] =
  177. TryResolveInst(work.inst_id, existing.const_id);
  178. CARBON_CHECK(finished == !HasNewWork(initial_work));
  179. CARBON_CHECK(!existing.const_id.is_valid() ||
  180. existing.const_id == new_const_id)
  181. << "Constant value changed in second pass.";
  182. if (!existing.const_id.is_valid()) {
  183. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  184. }
  185. // Step 3: pop or retry.
  186. if (finished) {
  187. work_stack_.pop_back();
  188. } else {
  189. work_stack_[initial_work - 1].retry = true;
  190. }
  191. }
  192. auto constant_id = import_ir_constant_values().Get(inst_id);
  193. CARBON_CHECK(constant_id.is_valid());
  194. return constant_id;
  195. }
  196. // Wraps constant evaluation with logic to handle types.
  197. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  198. if (!import_type_id.is_valid()) {
  199. return import_type_id;
  200. }
  201. auto import_type_inst_id = import_ir_.types().GetInstId(import_type_id);
  202. CARBON_CHECK(import_type_inst_id.is_valid());
  203. if (import_type_inst_id.is_builtin()) {
  204. // Builtins don't require constant resolution; we can use them directly.
  205. return context_.GetBuiltinType(import_type_inst_id.builtin_inst_kind());
  206. } else {
  207. return context_.GetTypeIdForTypeConstant(Resolve(import_type_inst_id));
  208. }
  209. }
  210. private:
  211. // A step in work_stack_.
  212. struct Work {
  213. // The instruction to work on.
  214. SemIR::InstId inst_id;
  215. // True if another pass was requested last time this was run.
  216. bool retry = false;
  217. };
  218. // The result of attempting to resolve an imported instruction to a constant.
  219. struct ResolveResult {
  220. // Try resolving this function again. If `const_id` is specified, it will be
  221. // passed to the next resolution attempt.
  222. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  223. -> ResolveResult {
  224. return {.const_id = const_id, .finished = false};
  225. }
  226. // The new constant value, if known.
  227. SemIR::ConstantId const_id;
  228. // Whether resolution has finished. If false, `TryResolveInst` will be
  229. // called again. Note that this is not strictly necessary, and we can get
  230. // the same information by checking whether new work was added to the stack.
  231. // However, we use this for consistency checks between resolve actions and
  232. // the work stack.
  233. bool finished = true;
  234. };
  235. // The constant found by FindResolvedConstId.
  236. struct ResolvedConstId {
  237. // The constant for the instruction. Invalid if not yet resolved.
  238. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  239. // Instructions which are indirect but equivalent to the current instruction
  240. // being resolved, and should have their constant set to the same. Empty
  241. // when const_id is valid.
  242. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  243. };
  244. // Looks to see if an instruction has been resolved. If a constant is only
  245. // found indirectly, sets the constant for any indirect steps that don't
  246. // already have the constant. If a constant isn't found, returns the indirect
  247. // instructions so that they can have the resolved constant assigned later.
  248. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  249. ResolvedConstId result;
  250. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  251. existing_const_id.is_valid()) {
  252. result.const_id = existing_const_id;
  253. return result;
  254. }
  255. const auto* cursor_ir = &import_ir_;
  256. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  257. auto cursor_inst_id = inst_id;
  258. while (true) {
  259. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  260. if (!loc_id.is_import_ir_inst_id()) {
  261. return result;
  262. }
  263. auto ir_inst =
  264. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  265. const auto* prev_ir = cursor_ir;
  266. auto prev_inst_id = cursor_inst_id;
  267. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  268. cursor_ir_id = context_.GetImportIRId(*cursor_ir);
  269. if (!cursor_ir_id.is_valid()) {
  270. // TODO: Should we figure out a location to assign here?
  271. cursor_ir_id = AddImportIR(context_, {.decl_id = SemIR::InstId::Invalid,
  272. .is_export = false,
  273. .sem_ir = cursor_ir});
  274. }
  275. cursor_inst_id = ir_inst.inst_id;
  276. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id)
  277. << cursor_ir->insts().Get(cursor_inst_id);
  278. if (auto const_id =
  279. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  280. cursor_inst_id);
  281. const_id.is_valid()) {
  282. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  283. result.const_id = const_id;
  284. result.indirect_insts.clear();
  285. return result;
  286. } else {
  287. result.indirect_insts.push_back(
  288. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  289. }
  290. }
  291. }
  292. // Sets a resolved constant into the current and indirect instructions.
  293. auto SetResolvedConstId(SemIR::InstId inst_id,
  294. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  295. SemIR::ConstantId const_id) -> void {
  296. import_ir_constant_values().Set(inst_id, const_id);
  297. for (auto indirect_inst : indirect_insts) {
  298. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  299. indirect_inst.inst_id, const_id);
  300. }
  301. }
  302. // Returns true if new unresolved constants were found.
  303. //
  304. // At the start of a function, do:
  305. // auto initial_work = work_stack_.size();
  306. // Then when determining:
  307. // if (HasNewWork(initial_work)) { ... }
  308. auto HasNewWork(size_t initial_work) -> bool {
  309. CARBON_CHECK(initial_work <= work_stack_.size())
  310. << "Work shouldn't decrease";
  311. return initial_work < work_stack_.size();
  312. }
  313. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  314. return context_.import_ir_insts().Add(
  315. {.ir_id = import_ir_id_, .inst_id = inst_id});
  316. }
  317. // Returns the ConstantId for an InstId. Adds unresolved constants to
  318. // work_stack_.
  319. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  320. auto const_id = import_ir_constant_values().Get(inst_id);
  321. if (!const_id.is_valid()) {
  322. work_stack_.push_back({.inst_id = inst_id});
  323. }
  324. return const_id;
  325. }
  326. // Returns the local constant InstId for an imported InstId.
  327. auto GetLocalConstantInstId(SemIR::InstId inst_id) -> SemIR::InstId {
  328. auto const_id = import_ir_constant_values().Get(inst_id);
  329. if (!const_id.is_valid()) {
  330. work_stack_.push_back({.inst_id = inst_id});
  331. return SemIR::InstId::Invalid;
  332. }
  333. return context_.constant_values().GetInstId(const_id);
  334. }
  335. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  336. // work_stack_.
  337. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  338. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  339. }
  340. // Gets the local constant values corresponding to an imported inst block.
  341. auto GetLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  342. -> llvm::SmallVector<SemIR::InstId> {
  343. llvm::SmallVector<SemIR::InstId> inst_ids;
  344. if (!import_block_id.is_valid() ||
  345. import_block_id == SemIR::InstBlockId::Empty) {
  346. return inst_ids;
  347. }
  348. // Import all the values in the block.
  349. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  350. inst_ids.reserve(import_block.size());
  351. for (auto import_inst_id : import_block) {
  352. auto const_id = GetLocalConstantId(import_inst_id);
  353. inst_ids.push_back(context_.constant_values().GetInstIdIfValid(const_id));
  354. }
  355. return inst_ids;
  356. }
  357. // Gets a local canonical instruction block ID corresponding to an imported
  358. // inst block whose contents were already imported, for example by
  359. // GetLocalInstBlockContents.
  360. auto GetLocalCanonicalInstBlockId(SemIR::InstBlockId import_block_id,
  361. llvm::ArrayRef<SemIR::InstId> contents)
  362. -> SemIR::InstBlockId {
  363. if (!import_block_id.is_valid()) {
  364. return SemIR::InstBlockId::Invalid;
  365. }
  366. return context_.inst_blocks().AddCanonical(contents);
  367. }
  368. // Gets a local version of an imported generic.
  369. auto GetLocalGeneric(SemIR::GenericId generic_id) -> SemIR::GenericId {
  370. if (!generic_id.is_valid()) {
  371. return SemIR::GenericId::Invalid;
  372. }
  373. // TODO: Support importing generics. Note that this comes up in the prelude,
  374. // so for now we fall back to producing `Invalid` and treating imported
  375. // generics as non-generic.
  376. return SemIR::GenericId::Invalid;
  377. }
  378. // Gets a local argument list corresponding to the arguments of an imported
  379. // specific.
  380. auto GetLocalSpecificArgs(SemIR::SpecificId specific_id)
  381. -> llvm::SmallVector<SemIR::InstId> {
  382. if (!specific_id.is_valid()) {
  383. return {};
  384. }
  385. return GetLocalInstBlockContents(
  386. import_ir_.specifics().Get(specific_id).args_id);
  387. }
  388. // Gets a local specific whose arguments were already imported by
  389. // GetLocalSpecificArgs. Does not add any new work.
  390. auto GetLocalSpecific(SemIR::SpecificId specific_id,
  391. llvm::ArrayRef<SemIR::InstId> args)
  392. -> SemIR::SpecificId {
  393. if (!specific_id.is_valid()) {
  394. return SemIR::SpecificId::Invalid;
  395. }
  396. const auto& specific = import_ir_.specifics().Get(specific_id);
  397. // TODO: Import the generic.
  398. auto generic_id = SemIR::GenericId::Invalid;
  399. auto args_id = GetLocalCanonicalInstBlockId(specific.args_id, args);
  400. // TODO: Also import the specific.
  401. return context_.specifics().GetOrAdd(generic_id, args_id);
  402. }
  403. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  404. // to work_stack_.
  405. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  406. -> llvm::SmallVector<SemIR::ConstantId> {
  407. llvm::SmallVector<SemIR::ConstantId> const_ids;
  408. if (!param_refs_id.is_valid() ||
  409. param_refs_id == SemIR::InstBlockId::Empty) {
  410. return const_ids;
  411. }
  412. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  413. const_ids.reserve(param_refs.size());
  414. for (auto inst_id : param_refs) {
  415. const_ids.push_back(
  416. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  417. // If the parameter is a symbolic binding, build the BindSymbolicName
  418. // constant.
  419. auto bind_id = inst_id;
  420. if (auto addr =
  421. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  422. bind_id = addr->inner_id;
  423. }
  424. GetLocalConstantId(bind_id);
  425. }
  426. return const_ids;
  427. }
  428. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  429. // a version of param_refs_id localized to the current IR.
  430. auto GetLocalParamRefsId(
  431. SemIR::InstBlockId param_refs_id,
  432. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  433. -> SemIR::InstBlockId {
  434. if (!param_refs_id.is_valid() ||
  435. param_refs_id == SemIR::InstBlockId::Empty) {
  436. return param_refs_id;
  437. }
  438. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  439. llvm::SmallVector<SemIR::InstId> new_param_refs;
  440. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  441. // Figure out the param structure. This echoes
  442. // Function::GetParamFromParamRefId.
  443. // TODO: Consider a different parameter handling to simplify import logic.
  444. auto inst = import_ir_.insts().Get(ref_id);
  445. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  446. auto bind_id = ref_id;
  447. auto param_id = ref_id;
  448. if (addr_inst) {
  449. bind_id = addr_inst->inner_id;
  450. param_id = bind_id;
  451. inst = import_ir_.insts().Get(bind_id);
  452. }
  453. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  454. if (bind_inst) {
  455. param_id = bind_inst->value_id;
  456. inst = import_ir_.insts().Get(param_id);
  457. }
  458. auto param_inst = inst.As<SemIR::Param>();
  459. // Rebuild the param instruction.
  460. auto name_id = GetLocalNameId(param_inst.name_id);
  461. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  462. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  463. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  464. if (bind_inst) {
  465. switch (bind_inst->kind) {
  466. case SemIR::BindName::Kind: {
  467. auto entity_name_id = context_.entity_names().Add(
  468. {.name_id = name_id,
  469. .parent_scope_id = SemIR::NameScopeId::Invalid,
  470. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  471. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  472. AddImportIRInst(bind_id), {.type_id = type_id,
  473. .entity_name_id = entity_name_id,
  474. .value_id = new_param_id});
  475. break;
  476. }
  477. case SemIR::BindSymbolicName::Kind: {
  478. // We already imported a constant value for this symbolic binding.
  479. // We can reuse most of it.
  480. auto new_bind_inst_id = GetLocalConstantInstId(bind_id);
  481. auto new_bind_inst =
  482. context_.insts().GetAs<SemIR::BindSymbolicName>(
  483. new_bind_inst_id);
  484. new_bind_inst.value_id = new_param_id;
  485. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  486. new_bind_inst);
  487. break;
  488. }
  489. default: {
  490. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  491. }
  492. }
  493. }
  494. if (addr_inst) {
  495. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  496. AddImportIRInst(ref_id),
  497. {.type_id = type_id, .inner_id = new_param_id});
  498. }
  499. new_param_refs.push_back(new_param_id);
  500. }
  501. return context_.inst_blocks().Add(new_param_refs);
  502. }
  503. // Translates a NameId from the import IR to a local NameId.
  504. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  505. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  506. return SemIR::NameId::ForIdentifier(
  507. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  508. }
  509. return import_name_id;
  510. }
  511. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  512. // unresolved constants to the work stack.
  513. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  514. -> SemIR::NameScopeId {
  515. // Get the instruction that created the scope.
  516. auto [inst_id, inst] =
  517. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  518. if (!inst) {
  519. // Map scopes that aren't associated with an instruction to invalid
  520. // scopes. For now, such scopes aren't used, and we don't have a good way
  521. // to remap them.
  522. return SemIR::NameScopeId::Invalid;
  523. }
  524. // Get the constant value for the scope.
  525. auto const_id = SemIR::ConstantId::Invalid;
  526. CARBON_KIND_SWITCH(*inst) {
  527. case SemIR::ImplDecl::Kind:
  528. // TODO: Import the scope for an `impl` definition.
  529. return SemIR::NameScopeId::Invalid;
  530. case SemIR::Namespace::Kind:
  531. // If the namespace has already been imported, we can use its constant.
  532. // However, if it hasn't, we use Invalid instead of adding it to the
  533. // work stack. That's expected to be okay when resolving references.
  534. const_id = import_ir_constant_values().Get(inst_id);
  535. break;
  536. default:
  537. const_id = GetLocalConstantId(inst_id);
  538. }
  539. if (!const_id.is_valid()) {
  540. return SemIR::NameScopeId::Invalid;
  541. }
  542. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  543. auto name_scope_inst = context_.insts().Get(const_inst_id);
  544. CARBON_KIND_SWITCH(name_scope_inst) {
  545. case CARBON_KIND(SemIR::Namespace inst): {
  546. return inst.name_scope_id;
  547. }
  548. case CARBON_KIND(SemIR::ClassType inst): {
  549. return context_.classes().Get(inst.class_id).scope_id;
  550. }
  551. case CARBON_KIND(SemIR::InterfaceType inst): {
  552. return context_.interfaces().Get(inst.interface_id).scope_id;
  553. }
  554. case SemIR::StructValue::Kind: {
  555. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  556. CARBON_KIND_SWITCH(type_inst) {
  557. case CARBON_KIND(SemIR::GenericClassType inst): {
  558. return context_.classes().Get(inst.class_id).scope_id;
  559. }
  560. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  561. return context_.interfaces().Get(inst.interface_id).scope_id;
  562. }
  563. default: {
  564. break;
  565. }
  566. }
  567. break;
  568. }
  569. default: {
  570. if (const_inst_id == SemIR::InstId::BuiltinError) {
  571. return SemIR::NameScopeId::Invalid;
  572. }
  573. break;
  574. }
  575. }
  576. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  577. << name_scope_inst;
  578. }
  579. // Given an imported entity base, returns an incomplete, local version of it.
  580. //
  581. // Most fields are set in the second pass once they're imported. Import enough
  582. // of the parameter lists that we know whether this interface is a generic
  583. // interface and can build the right constant value for it.
  584. //
  585. // TODO: Add a better way to represent a generic prior to importing the
  586. // parameters.
  587. auto GetIncompleteLocalEntityBase(
  588. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  589. -> SemIR::EntityWithParamsBase {
  590. return {
  591. .name_id = GetLocalNameId(import_base.name_id),
  592. .parent_scope_id = SemIR::NameScopeId::Invalid,
  593. .generic_id = GetLocalGeneric(import_base.generic_id),
  594. .first_param_node_id = Parse::NodeId::Invalid,
  595. .last_param_node_id = Parse::NodeId::Invalid,
  596. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  597. ? SemIR::InstBlockId::Empty
  598. : SemIR::InstBlockId::Invalid,
  599. .param_refs_id = import_base.param_refs_id.is_valid()
  600. ? SemIR::InstBlockId::Empty
  601. : SemIR::InstBlockId::Invalid,
  602. .decl_id = decl_id,
  603. };
  604. }
  605. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  606. // lookup.
  607. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  608. SemIR::NameScope& new_scope) -> void {
  609. for (auto entry : import_scope.names) {
  610. auto ref_id = AddImportRef(
  611. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  612. SemIR::EntityNameId::Invalid);
  613. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  614. .inst_id = ref_id,
  615. .access_kind = entry.access_kind});
  616. }
  617. }
  618. // Given a block ID for a list of associated entities of a witness, returns a
  619. // version localized to the current IR.
  620. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  621. -> SemIR::InstBlockId {
  622. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  623. return SemIR::InstBlockId::Empty;
  624. }
  625. auto associated_entities =
  626. import_ir_.inst_blocks().Get(associated_entities_id);
  627. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  628. new_associated_entities.reserve(associated_entities.size());
  629. for (auto inst_id : associated_entities) {
  630. new_associated_entities.push_back(
  631. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  632. SemIR::EntityNameId::Invalid));
  633. }
  634. return context_.inst_blocks().Add(new_associated_entities);
  635. }
  636. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  637. // more has been added to the stack. A similar API is followed for all
  638. // following TryResolveTypedInst helper functions.
  639. //
  640. // `const_id` is Invalid unless we've tried to resolve this instruction
  641. // before, in which case it's the previous result.
  642. //
  643. // TODO: Error is returned when support is missing, but that should go away.
  644. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  645. -> ResolveResult {
  646. if (inst_id.is_builtin()) {
  647. CARBON_CHECK(!const_id.is_valid());
  648. // Constants for builtins can be directly copied.
  649. return {.const_id = context_.constant_values().Get(inst_id)};
  650. }
  651. auto untyped_inst = import_ir_.insts().Get(inst_id);
  652. CARBON_KIND_SWITCH(untyped_inst) {
  653. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  654. return TryResolveTypedInst(inst);
  655. }
  656. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  657. return TryResolveTypedInst(inst);
  658. }
  659. case CARBON_KIND(SemIR::BaseDecl inst): {
  660. return TryResolveTypedInst(inst, inst_id);
  661. }
  662. case CARBON_KIND(SemIR::BindAlias inst): {
  663. return TryResolveTypedInst(inst);
  664. }
  665. case CARBON_KIND(SemIR::BindName inst): {
  666. // TODO: This always returns `ConstantId::NotConstant`.
  667. return {.const_id = TryEvalInst(context_, inst_id, inst)};
  668. }
  669. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  670. return TryResolveTypedInst(inst);
  671. }
  672. case CARBON_KIND(SemIR::ClassDecl inst): {
  673. return TryResolveTypedInst(inst, const_id);
  674. }
  675. case CARBON_KIND(SemIR::ClassType inst): {
  676. return TryResolveTypedInst(inst);
  677. }
  678. case CARBON_KIND(SemIR::ConstType inst): {
  679. return TryResolveTypedInst(inst);
  680. }
  681. case CARBON_KIND(SemIR::ExportDecl inst): {
  682. return TryResolveTypedInst(inst);
  683. }
  684. case CARBON_KIND(SemIR::FieldDecl inst): {
  685. return TryResolveTypedInst(inst, inst_id);
  686. }
  687. case CARBON_KIND(SemIR::FunctionDecl inst): {
  688. return TryResolveTypedInst(inst);
  689. }
  690. case CARBON_KIND(SemIR::FunctionType inst): {
  691. return TryResolveTypedInst(inst);
  692. }
  693. case CARBON_KIND(SemIR::GenericClassType inst): {
  694. return TryResolveTypedInst(inst);
  695. }
  696. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  697. return TryResolveTypedInst(inst);
  698. }
  699. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  700. return TryResolveTypedInst(inst, inst_id);
  701. }
  702. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  703. return TryResolveTypedInst(inst, const_id);
  704. }
  705. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  706. return TryResolveTypedInst(inst);
  707. }
  708. case CARBON_KIND(SemIR::InterfaceType inst): {
  709. return TryResolveTypedInst(inst);
  710. }
  711. case CARBON_KIND(SemIR::IntLiteral inst): {
  712. return TryResolveTypedInst(inst);
  713. }
  714. case CARBON_KIND(SemIR::Namespace inst): {
  715. CARBON_FATAL() << "Namespaces shouldn't need resolution this way: "
  716. << inst;
  717. }
  718. case CARBON_KIND(SemIR::PointerType inst): {
  719. return TryResolveTypedInst(inst);
  720. }
  721. case CARBON_KIND(SemIR::StructType inst): {
  722. return TryResolveTypedInst(inst, inst_id);
  723. }
  724. case CARBON_KIND(SemIR::StructValue inst): {
  725. return TryResolveTypedInst(inst);
  726. }
  727. case CARBON_KIND(SemIR::TupleType inst): {
  728. return TryResolveTypedInst(inst);
  729. }
  730. case CARBON_KIND(SemIR::TupleValue inst): {
  731. return TryResolveTypedInst(inst);
  732. }
  733. case CARBON_KIND(SemIR::UnboundElementType inst): {
  734. return TryResolveTypedInst(inst);
  735. }
  736. default:
  737. context_.TODO(
  738. SemIR::LocId(AddImportIRInst(inst_id)),
  739. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  740. return {.const_id = SemIR::ConstantId::Error};
  741. }
  742. }
  743. // Produce a resolve result for the given instruction that describes a
  744. // constant value. This should only be used for instructions that describe
  745. // constants, and not for instructions that represent declarations. For a
  746. // declaration, we need an associated location, so AddInstInNoBlock should be
  747. // used instead.
  748. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  749. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  750. CARBON_CHECK(result.is_constant()) << inst << " is not constant";
  751. return {.const_id = result};
  752. }
  753. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  754. template <typename InstT>
  755. auto ResolveAs(InstT inst) -> ResolveResult {
  756. return ResolveAsUntyped(inst);
  757. }
  758. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  759. auto initial_work = work_stack_.size();
  760. auto type_const_id = GetLocalConstantId(inst.type_id);
  761. if (HasNewWork(initial_work)) {
  762. return ResolveResult::Retry();
  763. }
  764. // Add a lazy reference to the target declaration.
  765. auto decl_id = AddImportRef(
  766. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  767. SemIR::EntityNameId::Invalid);
  768. return ResolveAs<SemIR::AssociatedEntity>(
  769. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  770. .index = inst.index,
  771. .decl_id = decl_id});
  772. }
  773. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  774. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  775. auto initial_work = work_stack_.size();
  776. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  777. auto interface_inst_id = GetLocalConstantInstId(
  778. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  779. if (HasNewWork(initial_work)) {
  780. return ResolveResult::Retry();
  781. }
  782. return ResolveAs<SemIR::AssociatedEntityType>(
  783. {.type_id = SemIR::TypeId::TypeType,
  784. .interface_id = context_.insts()
  785. .GetAs<SemIR::InterfaceType>(interface_inst_id)
  786. .interface_id,
  787. .entity_type_id =
  788. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  789. }
  790. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  791. -> ResolveResult {
  792. auto initial_work = work_stack_.size();
  793. auto type_const_id = GetLocalConstantId(inst.type_id);
  794. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  795. if (HasNewWork(initial_work)) {
  796. return ResolveResult::Retry();
  797. }
  798. // Import the instruction in order to update contained base_type_id and
  799. // track the import location.
  800. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  801. AddImportIRInst(import_inst_id),
  802. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  803. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  804. .index = inst.index});
  805. return {.const_id = context_.constant_values().Get(inst_id)};
  806. }
  807. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  808. auto initial_work = work_stack_.size();
  809. auto value_id = GetLocalConstantId(inst.value_id);
  810. if (HasNewWork(initial_work)) {
  811. return ResolveResult::Retry();
  812. }
  813. return {.const_id = value_id};
  814. }
  815. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  816. auto initial_work = work_stack_.size();
  817. auto type_id = GetLocalConstantId(inst.type_id);
  818. if (HasNewWork(initial_work)) {
  819. return ResolveResult::Retry();
  820. }
  821. const auto& import_entity_name =
  822. import_ir_.entity_names().Get(inst.entity_name_id);
  823. auto name_id = GetLocalNameId(import_entity_name.name_id);
  824. auto entity_name_id = context_.entity_names().Add(
  825. {.name_id = name_id,
  826. .parent_scope_id = SemIR::NameScopeId::Invalid,
  827. .bind_index = import_entity_name.bind_index});
  828. return ResolveAs<SemIR::BindSymbolicName>(
  829. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  830. .entity_name_id = entity_name_id,
  831. .value_id = SemIR::InstId::Invalid});
  832. }
  833. // Makes an incomplete class. This is necessary even with classes with a
  834. // complete declaration, because things such as `Self` may refer back to the
  835. // type.
  836. auto MakeIncompleteClass(const SemIR::Class& import_class)
  837. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  838. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  839. .class_id = SemIR::ClassId::Invalid,
  840. .decl_block_id = SemIR::InstBlockId::Empty};
  841. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  842. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  843. // Regardless of whether ClassDecl is a complete type, we first need an
  844. // incomplete type so that any references have something to point at.
  845. class_decl.class_id = context_.classes().Add(
  846. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  847. {.self_type_id = SemIR::TypeId::Invalid,
  848. .inheritance_kind = import_class.inheritance_kind}});
  849. if (import_class.is_generic()) {
  850. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  851. }
  852. // Write the class ID into the ClassDecl.
  853. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  854. auto self_const_id = context_.constant_values().Get(class_decl_id);
  855. return {class_decl.class_id, self_const_id};
  856. }
  857. // Fills out the class definition for an incomplete class.
  858. auto AddClassDefinition(const SemIR::Class& import_class,
  859. SemIR::Class& new_class,
  860. SemIR::ConstantId object_repr_const_id,
  861. SemIR::InstId base_id) -> void {
  862. new_class.definition_id = new_class.decl_id;
  863. new_class.object_repr_id =
  864. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  865. new_class.scope_id = context_.name_scopes().Add(
  866. new_class.decl_id, SemIR::NameId::Invalid, new_class.parent_scope_id);
  867. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  868. const auto& import_scope =
  869. import_ir_.name_scopes().Get(import_class.scope_id);
  870. // Push a block so that we can add scoped instructions to it.
  871. context_.inst_block_stack().Push();
  872. AddNameScopeImportRefs(import_scope, new_scope);
  873. new_class.body_block_id = context_.inst_block_stack().Pop();
  874. if (import_class.base_id.is_valid()) {
  875. new_class.base_id = base_id;
  876. // Add the base scope to extended scopes.
  877. auto base_inst_id = context_.types().GetInstId(
  878. context_.insts()
  879. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  880. .base_type_id);
  881. const auto& base_class = context_.classes().Get(
  882. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  883. new_scope.extended_scopes.push_back(base_class.scope_id);
  884. }
  885. CARBON_CHECK(new_scope.extended_scopes.size() ==
  886. import_scope.extended_scopes.size());
  887. }
  888. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  889. SemIR::ConstantId class_const_id) -> ResolveResult {
  890. // TODO: The handling of interfaces repeats a lot with the handling of
  891. // classes, and will likely also be repeated for named constraints and
  892. // choice types. Factor out some of this functionality.
  893. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  894. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  895. if (!class_const_id.is_valid()) {
  896. // On the first pass, create a forward declaration of the class for any
  897. // recursive references.
  898. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  899. } else {
  900. // On the second pass, compute the class ID from the constant value of the
  901. // declaration.
  902. auto class_const_inst = context_.insts().Get(
  903. context_.constant_values().GetInstId(class_const_id));
  904. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  905. class_id = class_type->class_id;
  906. } else {
  907. auto generic_class_type =
  908. context_.types().GetAs<SemIR::GenericClassType>(
  909. class_const_inst.type_id());
  910. class_id = generic_class_type.class_id;
  911. }
  912. }
  913. // Load constants for the definition.
  914. auto initial_work = work_stack_.size();
  915. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  916. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  917. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  918. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  919. GetLocalParamConstantIds(import_class.param_refs_id);
  920. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  921. auto object_repr_const_id =
  922. import_class.object_repr_id.is_valid()
  923. ? GetLocalConstantId(import_class.object_repr_id)
  924. : SemIR::ConstantId::Invalid;
  925. auto base_id = import_class.base_id.is_valid()
  926. ? GetLocalConstantInstId(import_class.base_id)
  927. : SemIR::InstId::Invalid;
  928. if (HasNewWork(initial_work)) {
  929. return ResolveResult::Retry(class_const_id);
  930. }
  931. auto& new_class = context_.classes().Get(class_id);
  932. new_class.parent_scope_id = parent_scope_id;
  933. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  934. import_class.implicit_param_refs_id, implicit_param_const_ids);
  935. new_class.param_refs_id =
  936. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  937. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  938. if (import_class.is_defined()) {
  939. AddClassDefinition(import_class, new_class, object_repr_const_id,
  940. base_id);
  941. }
  942. return {.const_id = class_const_id};
  943. }
  944. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  945. auto initial_work = work_stack_.size();
  946. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  947. auto class_const_id =
  948. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  949. auto args = GetLocalSpecificArgs(inst.specific_id);
  950. if (HasNewWork(initial_work)) {
  951. return ResolveResult::Retry();
  952. }
  953. // Find the corresponding class type. For a non-generic class, this is the
  954. // type of the class declaration. For a generic class, build a class type
  955. // referencing this specialization of the generic class.
  956. auto class_const_inst = context_.insts().Get(
  957. context_.constant_values().GetInstId(class_const_id));
  958. if (class_const_inst.Is<SemIR::ClassType>()) {
  959. return {.const_id = class_const_id};
  960. } else {
  961. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  962. class_const_inst.type_id());
  963. auto specific_id = GetLocalSpecific(inst.specific_id, args);
  964. return ResolveAs<SemIR::ClassType>(
  965. {.type_id = SemIR::TypeId::TypeType,
  966. .class_id = generic_class_type.class_id,
  967. .specific_id = specific_id});
  968. }
  969. }
  970. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  971. auto initial_work = work_stack_.size();
  972. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  973. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  974. if (HasNewWork(initial_work)) {
  975. return ResolveResult::Retry();
  976. }
  977. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  978. return ResolveAs<SemIR::ConstType>(
  979. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  980. }
  981. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  982. auto initial_work = work_stack_.size();
  983. auto value_id = GetLocalConstantId(inst.value_id);
  984. if (HasNewWork(initial_work)) {
  985. return ResolveResult::Retry();
  986. }
  987. return {.const_id = value_id};
  988. }
  989. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  990. -> ResolveResult {
  991. auto initial_work = work_stack_.size();
  992. auto const_id = GetLocalConstantId(inst.type_id);
  993. if (HasNewWork(initial_work)) {
  994. return ResolveResult::Retry();
  995. }
  996. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  997. AddImportIRInst(import_inst_id),
  998. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  999. .name_id = GetLocalNameId(inst.name_id),
  1000. .index = inst.index});
  1001. return {.const_id = context_.constant_values().Get(inst_id)};
  1002. }
  1003. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  1004. auto initial_work = work_stack_.size();
  1005. const auto& function = import_ir_.functions().Get(inst.function_id);
  1006. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1007. if (function.return_storage_id.is_valid()) {
  1008. return_type_const_id =
  1009. GetLocalConstantId(function.GetDeclaredReturnType(import_ir_));
  1010. }
  1011. auto parent_scope_id = GetLocalNameScopeId(function.parent_scope_id);
  1012. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1013. GetLocalParamConstantIds(function.implicit_param_refs_id);
  1014. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1015. GetLocalParamConstantIds(function.param_refs_id);
  1016. if (HasNewWork(initial_work)) {
  1017. return ResolveResult::Retry();
  1018. }
  1019. // Add the function declaration.
  1020. SemIR::FunctionDecl function_decl = {
  1021. .type_id = SemIR::TypeId::Invalid,
  1022. .function_id = SemIR::FunctionId::Invalid,
  1023. .decl_block_id = SemIR::InstBlockId::Empty};
  1024. auto import_ir_inst_id = AddImportIRInst(function.latest_decl_id());
  1025. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  1026. SemIR::LocIdAndInst(import_ir_inst_id, function_decl));
  1027. // TODO: Implement import for generics.
  1028. auto generic_id = GetLocalGeneric(function.generic_id);
  1029. auto new_return_storage = SemIR::InstId::Invalid;
  1030. if (function.return_storage_id.is_valid()) {
  1031. // Recreate the return slot from scratch.
  1032. // TODO: Once we import function definitions, we'll need to make sure we
  1033. // use the same return storage variable in the declaration and definition.
  1034. new_return_storage = context_.AddInstInNoBlock<SemIR::VarStorage>(
  1035. AddImportIRInst(function.return_storage_id),
  1036. {.type_id = context_.GetTypeIdForTypeConstant(return_type_const_id),
  1037. .name_id = SemIR::NameId::ReturnSlot});
  1038. }
  1039. function_decl.function_id = context_.functions().Add(
  1040. {{.name_id = GetLocalNameId(function.name_id),
  1041. .parent_scope_id = parent_scope_id,
  1042. .generic_id = generic_id,
  1043. .first_param_node_id = Parse::NodeId::Invalid,
  1044. .last_param_node_id = Parse::NodeId::Invalid,
  1045. .implicit_param_refs_id = GetLocalParamRefsId(
  1046. function.implicit_param_refs_id, implicit_param_const_ids),
  1047. .param_refs_id =
  1048. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  1049. .decl_id = function_decl_id,
  1050. .definition_id = function.definition_id.is_valid()
  1051. ? function_decl_id
  1052. : SemIR::InstId::Invalid},
  1053. {.return_storage_id = new_return_storage,
  1054. .is_extern = function.is_extern,
  1055. .builtin_function_kind = function.builtin_function_kind}});
  1056. // TODO: Import this or recompute it.
  1057. auto specific_id = SemIR::SpecificId::Invalid;
  1058. function_decl.type_id =
  1059. context_.GetFunctionType(function_decl.function_id, specific_id);
  1060. // Write the function ID into the FunctionDecl.
  1061. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1062. return {.const_id = context_.constant_values().Get(function_decl_id)};
  1063. }
  1064. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1065. auto initial_work = work_stack_.size();
  1066. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1067. auto fn_val_id = GetLocalConstantInstId(
  1068. import_ir_.functions().Get(inst.function_id).decl_id);
  1069. if (HasNewWork(initial_work)) {
  1070. return ResolveResult::Retry();
  1071. }
  1072. auto fn_val = context_.insts().Get(fn_val_id);
  1073. CARBON_CHECK(context_.types().Is<SemIR::FunctionType>(fn_val.type_id()));
  1074. // TODO: Import the correct specific and build a function type constant
  1075. // using it.
  1076. return {.const_id = context_.types().GetConstantId(fn_val.type_id())};
  1077. }
  1078. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1079. auto initial_work = work_stack_.size();
  1080. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1081. auto class_val_id =
  1082. GetLocalConstantInstId(import_ir_.classes().Get(inst.class_id).decl_id);
  1083. if (HasNewWork(initial_work)) {
  1084. return ResolveResult::Retry();
  1085. }
  1086. auto class_val = context_.insts().Get(class_val_id);
  1087. CARBON_CHECK(
  1088. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1089. return {.const_id = context_.types().GetConstantId(class_val.type_id())};
  1090. }
  1091. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1092. auto initial_work = work_stack_.size();
  1093. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1094. auto interface_val_id = GetLocalConstantInstId(
  1095. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1096. if (HasNewWork(initial_work)) {
  1097. return ResolveResult::Retry();
  1098. }
  1099. auto interface_val = context_.insts().Get(interface_val_id);
  1100. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1101. interface_val.type_id()));
  1102. return {.const_id =
  1103. context_.types().GetConstantId(interface_val.type_id())};
  1104. }
  1105. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1106. SemIR::InstId inst_id) -> ResolveResult {
  1107. auto initial_work = work_stack_.size();
  1108. // Return the constant for the instruction of the imported constant.
  1109. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1110. if (!constant_id.is_valid()) {
  1111. return {.const_id = SemIR::ConstantId::Error};
  1112. }
  1113. if (!constant_id.is_constant()) {
  1114. context_.TODO(inst_id,
  1115. "Non-constant ImportRefLoaded (comes up with var)");
  1116. return {.const_id = SemIR::ConstantId::Error};
  1117. }
  1118. auto new_constant_id =
  1119. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1120. if (HasNewWork(initial_work)) {
  1121. return ResolveResult::Retry();
  1122. }
  1123. return {.const_id = new_constant_id};
  1124. }
  1125. // Make a declaration of an interface. This is done as a separate step from
  1126. // importing the interface definition in order to resolve cycles.
  1127. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1128. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1129. SemIR::InterfaceDecl interface_decl = {
  1130. .type_id = SemIR::TypeId::TypeType,
  1131. .interface_id = SemIR::InterfaceId::Invalid,
  1132. .decl_block_id = SemIR::InstBlockId::Empty};
  1133. auto interface_decl_id =
  1134. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1135. AddImportIRInst(import_interface.decl_id), interface_decl));
  1136. // Start with an incomplete interface.
  1137. interface_decl.interface_id = context_.interfaces().Add(
  1138. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1139. {}});
  1140. if (import_interface.is_generic()) {
  1141. interface_decl.type_id =
  1142. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1143. }
  1144. // Write the interface ID into the InterfaceDecl.
  1145. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1146. return {interface_decl.interface_id,
  1147. context_.constant_values().Get(interface_decl_id)};
  1148. }
  1149. // Imports the definition for an interface that has been imported as a forward
  1150. // declaration.
  1151. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1152. SemIR::Interface& new_interface,
  1153. SemIR::InstId self_param_id) -> void {
  1154. new_interface.scope_id = context_.name_scopes().Add(
  1155. new_interface.decl_id, SemIR::NameId::Invalid,
  1156. new_interface.parent_scope_id);
  1157. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1158. const auto& import_scope =
  1159. import_ir_.name_scopes().Get(import_interface.scope_id);
  1160. // Push a block so that we can add scoped instructions to it.
  1161. context_.inst_block_stack().Push();
  1162. AddNameScopeImportRefs(import_scope, new_scope);
  1163. new_interface.associated_entities_id =
  1164. AddAssociatedEntities(import_interface.associated_entities_id);
  1165. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1166. new_interface.self_param_id = self_param_id;
  1167. CARBON_CHECK(import_scope.extended_scopes.empty())
  1168. << "Interfaces don't currently have extended scopes to support.";
  1169. }
  1170. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1171. SemIR::ConstantId interface_const_id)
  1172. -> ResolveResult {
  1173. const auto& import_interface =
  1174. import_ir_.interfaces().Get(inst.interface_id);
  1175. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1176. if (!interface_const_id.is_valid()) {
  1177. // On the first pass, create a forward declaration of the interface.
  1178. std::tie(interface_id, interface_const_id) =
  1179. MakeInterfaceDecl(import_interface);
  1180. } else {
  1181. // On the second pass, compute the interface ID from the constant value of
  1182. // the declaration.
  1183. auto interface_const_inst = context_.insts().Get(
  1184. context_.constant_values().GetInstId(interface_const_id));
  1185. if (auto interface_type =
  1186. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1187. interface_id = interface_type->interface_id;
  1188. } else {
  1189. auto generic_interface_type =
  1190. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1191. interface_const_inst.type_id());
  1192. interface_id = generic_interface_type.interface_id;
  1193. }
  1194. }
  1195. auto initial_work = work_stack_.size();
  1196. auto parent_scope_id =
  1197. GetLocalNameScopeId(import_interface.parent_scope_id);
  1198. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1199. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1200. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1201. GetLocalParamConstantIds(import_interface.param_refs_id);
  1202. std::optional<SemIR::InstId> self_param_id;
  1203. if (import_interface.is_defined()) {
  1204. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1205. }
  1206. if (HasNewWork(initial_work)) {
  1207. return ResolveResult::Retry(interface_const_id);
  1208. }
  1209. auto& new_interface = context_.interfaces().Get(interface_id);
  1210. new_interface.parent_scope_id = parent_scope_id;
  1211. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1212. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1213. new_interface.param_refs_id =
  1214. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1215. if (import_interface.is_defined()) {
  1216. CARBON_CHECK(self_param_id);
  1217. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1218. }
  1219. return {.const_id = interface_const_id};
  1220. }
  1221. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1222. auto initial_work = work_stack_.size();
  1223. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1224. auto interface_const_id = GetLocalConstantId(
  1225. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1226. auto args = GetLocalSpecificArgs(inst.specific_id);
  1227. if (HasNewWork(initial_work)) {
  1228. return ResolveResult::Retry();
  1229. }
  1230. // Find the corresponding interface type. For a non-generic interface, this
  1231. // is the type of the interface declaration. For a generic interface, build
  1232. // a interface type referencing this specialization of the generic
  1233. // interface.
  1234. auto interface_const_inst = context_.insts().Get(
  1235. context_.constant_values().GetInstId(interface_const_id));
  1236. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1237. return {.const_id = interface_const_id};
  1238. } else {
  1239. auto generic_interface_type =
  1240. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1241. interface_const_inst.type_id());
  1242. auto specific_id = GetLocalSpecific(inst.specific_id, args);
  1243. return ResolveAs<SemIR::InterfaceType>(
  1244. {.type_id = SemIR::TypeId::TypeType,
  1245. .interface_id = generic_interface_type.interface_id,
  1246. .specific_id = specific_id});
  1247. }
  1248. }
  1249. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1250. auto initial_work = work_stack_.size();
  1251. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1252. if (HasNewWork(initial_work)) {
  1253. return ResolveResult::Retry();
  1254. }
  1255. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1256. return ResolveAs<SemIR::InterfaceWitness>(
  1257. {.type_id =
  1258. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1259. .elements_id = elements_id});
  1260. }
  1261. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1262. auto initial_work = work_stack_.size();
  1263. auto type_id = GetLocalConstantId(inst.type_id);
  1264. if (HasNewWork(initial_work)) {
  1265. return ResolveResult::Retry();
  1266. }
  1267. return ResolveAs<SemIR::IntLiteral>(
  1268. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1269. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1270. }
  1271. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1272. auto initial_work = work_stack_.size();
  1273. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1274. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1275. if (HasNewWork(initial_work)) {
  1276. return ResolveResult::Retry();
  1277. }
  1278. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1279. return ResolveAs<SemIR::PointerType>(
  1280. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1281. }
  1282. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1283. -> ResolveResult {
  1284. // Collect all constants first, locating unresolved ones in a single pass.
  1285. auto initial_work = work_stack_.size();
  1286. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1287. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1288. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1289. field_const_ids.reserve(orig_fields.size());
  1290. for (auto field_id : orig_fields) {
  1291. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1292. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1293. }
  1294. if (HasNewWork(initial_work)) {
  1295. return ResolveResult::Retry();
  1296. }
  1297. // Prepare a vector of fields for GetStructType.
  1298. // TODO: Should we have field constants so that we can deduplicate fields
  1299. // without creating instructions here?
  1300. llvm::SmallVector<SemIR::InstId> fields;
  1301. fields.reserve(orig_fields.size());
  1302. for (auto [field_id, field_const_id] :
  1303. llvm::zip(orig_fields, field_const_ids)) {
  1304. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1305. auto name_id = GetLocalNameId(field.name_id);
  1306. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1307. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1308. AddImportIRInst(import_inst_id),
  1309. {.name_id = name_id, .field_type_id = field_type_id}));
  1310. }
  1311. return ResolveAs<SemIR::StructType>(
  1312. {.type_id = SemIR::TypeId::TypeType,
  1313. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1314. }
  1315. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1316. auto initial_work = work_stack_.size();
  1317. auto type_id = GetLocalConstantId(inst.type_id);
  1318. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1319. if (HasNewWork(initial_work)) {
  1320. return ResolveResult::Retry();
  1321. }
  1322. return ResolveAs<SemIR::StructValue>(
  1323. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1324. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1325. }
  1326. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1327. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1328. // Collect all constants first, locating unresolved ones in a single pass.
  1329. auto initial_work = work_stack_.size();
  1330. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1331. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1332. elem_const_ids.reserve(orig_elem_type_ids.size());
  1333. for (auto elem_type_id : orig_elem_type_ids) {
  1334. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1335. }
  1336. if (HasNewWork(initial_work)) {
  1337. return ResolveResult::Retry();
  1338. }
  1339. // Prepare a vector of the tuple types for GetTupleType.
  1340. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1341. elem_type_ids.reserve(orig_elem_type_ids.size());
  1342. for (auto elem_const_id : elem_const_ids) {
  1343. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1344. }
  1345. return {.const_id = context_.types().GetConstantId(
  1346. context_.GetTupleType(elem_type_ids))};
  1347. }
  1348. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1349. auto initial_work = work_stack_.size();
  1350. auto type_id = GetLocalConstantId(inst.type_id);
  1351. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1352. if (HasNewWork(initial_work)) {
  1353. return ResolveResult::Retry();
  1354. }
  1355. return ResolveAs<SemIR::TupleValue>(
  1356. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1357. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1358. }
  1359. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1360. auto initial_work = work_stack_.size();
  1361. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1362. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1363. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1364. if (HasNewWork(initial_work)) {
  1365. return ResolveResult::Retry();
  1366. }
  1367. return ResolveAs<SemIR::UnboundElementType>(
  1368. {.type_id = SemIR::TypeId::TypeType,
  1369. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1370. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1371. }
  1372. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1373. return context_.import_ir_constant_values()[import_ir_id_.index];
  1374. }
  1375. Context& context_;
  1376. SemIR::ImportIRId import_ir_id_;
  1377. const SemIR::File& import_ir_;
  1378. llvm::SmallVector<Work> work_stack_;
  1379. };
  1380. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1381. // loaded (including the one pointed at directly by the ImportRef), and the
  1382. // final instruction's type ID.
  1383. //
  1384. // This addresses cases where an ImportRefUnloaded may point at another
  1385. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1386. // constant-evaluated version of the instruction to work with.
  1387. static auto GetInstForLoad(Context& context,
  1388. SemIR::ImportIRInstId import_ir_inst_id)
  1389. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1390. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1391. {}, SemIR::TypeId::Invalid};
  1392. auto& [import_ir_insts, type_id] = result;
  1393. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1394. // The first ImportIRInst is added directly because the IR doesn't need to be
  1395. // localized.
  1396. import_ir_insts.push_back(import_ir_inst);
  1397. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1398. while (true) {
  1399. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1400. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1401. if (!import_ref) {
  1402. type_id = cursor_inst.type_id();
  1403. return result;
  1404. }
  1405. import_ir_inst =
  1406. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1407. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1408. import_ir_insts.push_back(
  1409. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1410. .is_export = false,
  1411. .sem_ir = cursor_ir}),
  1412. .inst_id = import_ir_inst.inst_id});
  1413. }
  1414. }
  1415. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1416. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1417. if (!inst) {
  1418. return;
  1419. }
  1420. auto [indirect_insts, load_type_id] =
  1421. GetInstForLoad(context, inst->import_ir_inst_id);
  1422. // The last indirect instruction is the one to resolve. Pop it here because
  1423. // Resolve will assign the constant.
  1424. auto load_ir_inst = indirect_insts.pop_back_val();
  1425. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1426. // The resolver calls into Context to create instructions. Don't register
  1427. // those instructions as part of the enclosing generic scope if they're
  1428. // dependent on a generic parameter.
  1429. context.generic_region_stack().Push();
  1430. auto type_id = resolver.ResolveType(load_type_id);
  1431. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1432. context.generic_region_stack().Pop();
  1433. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1434. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1435. // TryEvalInst, which we want to avoid with ImportRefs.
  1436. context.sem_ir().insts().Set(
  1437. inst_id,
  1438. SemIR::ImportRefLoaded{.type_id = type_id,
  1439. .import_ir_inst_id = inst->import_ir_inst_id,
  1440. .entity_name_id = inst->entity_name_id});
  1441. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1442. context.constant_values().Set(inst_id, constant_id);
  1443. for (const auto& import_ir_inst : indirect_insts) {
  1444. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1445. import_ir_inst.inst_id, constant_id);
  1446. }
  1447. }
  1448. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1449. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1450. const SemIR::File& import_ir,
  1451. SemIR::ImplId import_impl_id) -> void {
  1452. // Resolve the imported impl to a local impl ID.
  1453. ImportRefResolver resolver(context, import_ir_id);
  1454. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1455. auto self_id = resolver.ResolveType(import_impl.self_id);
  1456. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1457. // Import the definition if the impl is defined.
  1458. // TODO: Do we need to check for multiple definitions?
  1459. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1460. if (import_impl.is_defined()) {
  1461. // TODO: Create a scope for the `impl` if necessary.
  1462. // TODO: Consider importing the definition_id.
  1463. auto& impl = context.impls().Get(impl_id);
  1464. impl.witness_id = AddImportRef(
  1465. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1466. SemIR::EntityNameId::Invalid);
  1467. }
  1468. }
  1469. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1470. // and this file elsewhere.
  1471. auto ImportImpls(Context& context) -> void {
  1472. for (auto [import_index, import_ir] :
  1473. llvm::enumerate(context.import_irs().array_ref())) {
  1474. if (!import_ir.sem_ir) {
  1475. continue;
  1476. }
  1477. auto import_ir_id = SemIR::ImportIRId(import_index);
  1478. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1479. auto impl_id = SemIR::ImplId(impl_index);
  1480. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1481. }
  1482. }
  1483. }
  1484. } // namespace Carbon::Check