import_ref.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  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. // The symbolic name will be created on first reference, so might
  479. // already exist. Update the value in it to refer to the parameter.
  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. // This is not before constant use, but doesn't change the
  486. // constant value of the instruction.
  487. context_.ReplaceInstBeforeConstantUse(new_bind_inst_id,
  488. new_bind_inst);
  489. new_param_id = new_bind_inst_id;
  490. break;
  491. }
  492. default: {
  493. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  494. }
  495. }
  496. }
  497. if (addr_inst) {
  498. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  499. AddImportIRInst(ref_id),
  500. {.type_id = type_id, .inner_id = new_param_id});
  501. }
  502. new_param_refs.push_back(new_param_id);
  503. }
  504. return context_.inst_blocks().Add(new_param_refs);
  505. }
  506. // Translates a NameId from the import IR to a local NameId.
  507. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  508. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  509. return SemIR::NameId::ForIdentifier(
  510. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  511. }
  512. return import_name_id;
  513. }
  514. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  515. // unresolved constants to the work stack.
  516. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  517. -> SemIR::NameScopeId {
  518. // Get the instruction that created the scope.
  519. auto [inst_id, inst] =
  520. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  521. if (!inst) {
  522. // Map scopes that aren't associated with an instruction to invalid
  523. // scopes. For now, such scopes aren't used, and we don't have a good way
  524. // to remap them.
  525. return SemIR::NameScopeId::Invalid;
  526. }
  527. // Get the constant value for the scope.
  528. auto const_id = SemIR::ConstantId::Invalid;
  529. CARBON_KIND_SWITCH(*inst) {
  530. case SemIR::ImplDecl::Kind:
  531. // TODO: Import the scope for an `impl` definition.
  532. return SemIR::NameScopeId::Invalid;
  533. case SemIR::Namespace::Kind:
  534. // If the namespace has already been imported, we can use its constant.
  535. // However, if it hasn't, we use Invalid instead of adding it to the
  536. // work stack. That's expected to be okay when resolving references.
  537. const_id = import_ir_constant_values().Get(inst_id);
  538. break;
  539. default:
  540. const_id = GetLocalConstantId(inst_id);
  541. }
  542. if (!const_id.is_valid()) {
  543. return SemIR::NameScopeId::Invalid;
  544. }
  545. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  546. auto name_scope_inst = context_.insts().Get(const_inst_id);
  547. CARBON_KIND_SWITCH(name_scope_inst) {
  548. case CARBON_KIND(SemIR::Namespace inst): {
  549. return inst.name_scope_id;
  550. }
  551. case CARBON_KIND(SemIR::ClassType inst): {
  552. return context_.classes().Get(inst.class_id).scope_id;
  553. }
  554. case CARBON_KIND(SemIR::InterfaceType inst): {
  555. return context_.interfaces().Get(inst.interface_id).scope_id;
  556. }
  557. case SemIR::StructValue::Kind: {
  558. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  559. CARBON_KIND_SWITCH(type_inst) {
  560. case CARBON_KIND(SemIR::GenericClassType inst): {
  561. return context_.classes().Get(inst.class_id).scope_id;
  562. }
  563. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  564. return context_.interfaces().Get(inst.interface_id).scope_id;
  565. }
  566. default: {
  567. break;
  568. }
  569. }
  570. break;
  571. }
  572. default: {
  573. if (const_inst_id == SemIR::InstId::BuiltinError) {
  574. return SemIR::NameScopeId::Invalid;
  575. }
  576. break;
  577. }
  578. }
  579. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  580. << name_scope_inst;
  581. }
  582. // Given an imported entity base, returns an incomplete, local version of it.
  583. //
  584. // Most fields are set in the second pass once they're imported. Import enough
  585. // of the parameter lists that we know whether this interface is a generic
  586. // interface and can build the right constant value for it.
  587. //
  588. // TODO: Add a better way to represent a generic prior to importing the
  589. // parameters.
  590. auto GetIncompleteLocalEntityBase(
  591. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  592. -> SemIR::EntityWithParamsBase {
  593. return {
  594. .name_id = GetLocalNameId(import_base.name_id),
  595. .parent_scope_id = SemIR::NameScopeId::Invalid,
  596. .generic_id = GetLocalGeneric(import_base.generic_id),
  597. .first_param_node_id = Parse::NodeId::Invalid,
  598. .last_param_node_id = Parse::NodeId::Invalid,
  599. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  600. ? SemIR::InstBlockId::Empty
  601. : SemIR::InstBlockId::Invalid,
  602. .param_refs_id = import_base.param_refs_id.is_valid()
  603. ? SemIR::InstBlockId::Empty
  604. : SemIR::InstBlockId::Invalid,
  605. .decl_id = decl_id,
  606. };
  607. }
  608. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  609. // lookup.
  610. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  611. SemIR::NameScope& new_scope) -> void {
  612. for (auto entry : import_scope.names) {
  613. auto ref_id = AddImportRef(
  614. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  615. SemIR::EntityNameId::Invalid);
  616. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  617. .inst_id = ref_id,
  618. .access_kind = entry.access_kind});
  619. }
  620. }
  621. // Given a block ID for a list of associated entities of a witness, returns a
  622. // version localized to the current IR.
  623. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  624. -> SemIR::InstBlockId {
  625. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  626. return SemIR::InstBlockId::Empty;
  627. }
  628. auto associated_entities =
  629. import_ir_.inst_blocks().Get(associated_entities_id);
  630. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  631. new_associated_entities.reserve(associated_entities.size());
  632. for (auto inst_id : associated_entities) {
  633. new_associated_entities.push_back(
  634. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  635. SemIR::EntityNameId::Invalid));
  636. }
  637. return context_.inst_blocks().Add(new_associated_entities);
  638. }
  639. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  640. // more has been added to the stack. A similar API is followed for all
  641. // following TryResolveTypedInst helper functions.
  642. //
  643. // `const_id` is Invalid unless we've tried to resolve this instruction
  644. // before, in which case it's the previous result.
  645. //
  646. // TODO: Error is returned when support is missing, but that should go away.
  647. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  648. -> ResolveResult {
  649. if (inst_id.is_builtin()) {
  650. CARBON_CHECK(!const_id.is_valid());
  651. // Constants for builtins can be directly copied.
  652. return {.const_id = context_.constant_values().Get(inst_id)};
  653. }
  654. auto untyped_inst = import_ir_.insts().Get(inst_id);
  655. CARBON_KIND_SWITCH(untyped_inst) {
  656. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  657. return TryResolveTypedInst(inst);
  658. }
  659. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  660. return TryResolveTypedInst(inst);
  661. }
  662. case CARBON_KIND(SemIR::BaseDecl inst): {
  663. return TryResolveTypedInst(inst, inst_id);
  664. }
  665. case CARBON_KIND(SemIR::BindAlias inst): {
  666. return TryResolveTypedInst(inst);
  667. }
  668. case CARBON_KIND(SemIR::BindName inst): {
  669. // TODO: This always returns `ConstantId::NotConstant`.
  670. return {.const_id = TryEvalInst(context_, inst_id, inst)};
  671. }
  672. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  673. return TryResolveTypedInst(inst);
  674. }
  675. case CARBON_KIND(SemIR::ClassDecl inst): {
  676. return TryResolveTypedInst(inst, const_id);
  677. }
  678. case CARBON_KIND(SemIR::ClassType inst): {
  679. return TryResolveTypedInst(inst);
  680. }
  681. case CARBON_KIND(SemIR::ConstType inst): {
  682. return TryResolveTypedInst(inst);
  683. }
  684. case CARBON_KIND(SemIR::ExportDecl inst): {
  685. return TryResolveTypedInst(inst);
  686. }
  687. case CARBON_KIND(SemIR::FieldDecl inst): {
  688. return TryResolveTypedInst(inst, inst_id);
  689. }
  690. case CARBON_KIND(SemIR::FunctionDecl inst): {
  691. return TryResolveTypedInst(inst);
  692. }
  693. case CARBON_KIND(SemIR::FunctionType inst): {
  694. return TryResolveTypedInst(inst);
  695. }
  696. case CARBON_KIND(SemIR::GenericClassType inst): {
  697. return TryResolveTypedInst(inst);
  698. }
  699. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  700. return TryResolveTypedInst(inst);
  701. }
  702. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  703. return TryResolveTypedInst(inst, inst_id);
  704. }
  705. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  706. return TryResolveTypedInst(inst, const_id);
  707. }
  708. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  709. return TryResolveTypedInst(inst);
  710. }
  711. case CARBON_KIND(SemIR::InterfaceType inst): {
  712. return TryResolveTypedInst(inst);
  713. }
  714. case CARBON_KIND(SemIR::IntLiteral inst): {
  715. return TryResolveTypedInst(inst);
  716. }
  717. case CARBON_KIND(SemIR::Namespace inst): {
  718. CARBON_FATAL() << "Namespaces shouldn't need resolution this way: "
  719. << inst;
  720. }
  721. case CARBON_KIND(SemIR::PointerType inst): {
  722. return TryResolveTypedInst(inst);
  723. }
  724. case CARBON_KIND(SemIR::StructType inst): {
  725. return TryResolveTypedInst(inst, inst_id);
  726. }
  727. case CARBON_KIND(SemIR::StructValue inst): {
  728. return TryResolveTypedInst(inst);
  729. }
  730. case CARBON_KIND(SemIR::TupleType inst): {
  731. return TryResolveTypedInst(inst);
  732. }
  733. case CARBON_KIND(SemIR::TupleValue inst): {
  734. return TryResolveTypedInst(inst);
  735. }
  736. case CARBON_KIND(SemIR::UnboundElementType inst): {
  737. return TryResolveTypedInst(inst);
  738. }
  739. default:
  740. context_.TODO(
  741. SemIR::LocId(AddImportIRInst(inst_id)),
  742. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  743. return {.const_id = SemIR::ConstantId::Error};
  744. }
  745. }
  746. // Produce a resolve result for the given instruction that describes a
  747. // constant value. This should only be used for instructions that describe
  748. // constants, and not for instructions that represent declarations. For a
  749. // declaration, we need an associated location, so AddInstInNoBlock should be
  750. // used instead.
  751. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  752. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  753. CARBON_CHECK(result.is_constant()) << inst << " is not constant";
  754. return {.const_id = result};
  755. }
  756. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  757. template <typename InstT>
  758. auto ResolveAs(InstT inst) -> ResolveResult {
  759. return ResolveAsUntyped(inst);
  760. }
  761. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  762. auto initial_work = work_stack_.size();
  763. auto type_const_id = GetLocalConstantId(inst.type_id);
  764. if (HasNewWork(initial_work)) {
  765. return ResolveResult::Retry();
  766. }
  767. // Add a lazy reference to the target declaration.
  768. auto decl_id = AddImportRef(
  769. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  770. SemIR::EntityNameId::Invalid);
  771. return ResolveAs<SemIR::AssociatedEntity>(
  772. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  773. .index = inst.index,
  774. .decl_id = decl_id});
  775. }
  776. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  777. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  778. auto initial_work = work_stack_.size();
  779. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  780. auto interface_inst_id = GetLocalConstantInstId(
  781. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  782. if (HasNewWork(initial_work)) {
  783. return ResolveResult::Retry();
  784. }
  785. return ResolveAs<SemIR::AssociatedEntityType>(
  786. {.type_id = SemIR::TypeId::TypeType,
  787. .interface_id = context_.insts()
  788. .GetAs<SemIR::InterfaceType>(interface_inst_id)
  789. .interface_id,
  790. .entity_type_id =
  791. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  792. }
  793. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  794. -> ResolveResult {
  795. auto initial_work = work_stack_.size();
  796. auto type_const_id = GetLocalConstantId(inst.type_id);
  797. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  798. if (HasNewWork(initial_work)) {
  799. return ResolveResult::Retry();
  800. }
  801. // Import the instruction in order to update contained base_type_id and
  802. // track the import location.
  803. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  804. AddImportIRInst(import_inst_id),
  805. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  806. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  807. .index = inst.index});
  808. return {.const_id = context_.constant_values().Get(inst_id)};
  809. }
  810. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  811. auto initial_work = work_stack_.size();
  812. auto value_id = GetLocalConstantId(inst.value_id);
  813. if (HasNewWork(initial_work)) {
  814. return ResolveResult::Retry();
  815. }
  816. return {.const_id = value_id};
  817. }
  818. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  819. auto initial_work = work_stack_.size();
  820. auto type_id = GetLocalConstantId(inst.type_id);
  821. if (HasNewWork(initial_work)) {
  822. return ResolveResult::Retry();
  823. }
  824. const auto& import_entity_name =
  825. import_ir_.entity_names().Get(inst.entity_name_id);
  826. auto name_id = GetLocalNameId(import_entity_name.name_id);
  827. auto entity_name_id = context_.entity_names().Add(
  828. {.name_id = name_id,
  829. .parent_scope_id = SemIR::NameScopeId::Invalid,
  830. .bind_index = import_entity_name.bind_index});
  831. return ResolveAs<SemIR::BindSymbolicName>(
  832. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  833. .entity_name_id = entity_name_id,
  834. .value_id = SemIR::InstId::Invalid});
  835. }
  836. // Makes an incomplete class. This is necessary even with classes with a
  837. // complete declaration, because things such as `Self` may refer back to the
  838. // type.
  839. auto MakeIncompleteClass(const SemIR::Class& import_class)
  840. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  841. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  842. .class_id = SemIR::ClassId::Invalid,
  843. .decl_block_id = SemIR::InstBlockId::Empty};
  844. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  845. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  846. // Regardless of whether ClassDecl is a complete type, we first need an
  847. // incomplete type so that any references have something to point at.
  848. class_decl.class_id = context_.classes().Add(
  849. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  850. {.self_type_id = SemIR::TypeId::Invalid,
  851. .inheritance_kind = import_class.inheritance_kind}});
  852. if (import_class.is_generic()) {
  853. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  854. }
  855. // Write the class ID into the ClassDecl.
  856. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  857. auto self_const_id = context_.constant_values().Get(class_decl_id);
  858. return {class_decl.class_id, self_const_id};
  859. }
  860. // Fills out the class definition for an incomplete class.
  861. auto AddClassDefinition(const SemIR::Class& import_class,
  862. SemIR::Class& new_class,
  863. SemIR::ConstantId object_repr_const_id,
  864. SemIR::InstId base_id) -> void {
  865. new_class.definition_id = new_class.decl_id;
  866. new_class.object_repr_id =
  867. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  868. new_class.scope_id = context_.name_scopes().Add(
  869. new_class.decl_id, SemIR::NameId::Invalid, new_class.parent_scope_id);
  870. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  871. const auto& import_scope =
  872. import_ir_.name_scopes().Get(import_class.scope_id);
  873. // Push a block so that we can add scoped instructions to it.
  874. context_.inst_block_stack().Push();
  875. AddNameScopeImportRefs(import_scope, new_scope);
  876. new_class.body_block_id = context_.inst_block_stack().Pop();
  877. if (import_class.base_id.is_valid()) {
  878. new_class.base_id = base_id;
  879. // Add the base scope to extended scopes.
  880. auto base_inst_id = context_.types().GetInstId(
  881. context_.insts()
  882. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  883. .base_type_id);
  884. const auto& base_class = context_.classes().Get(
  885. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  886. new_scope.extended_scopes.push_back(base_class.scope_id);
  887. }
  888. CARBON_CHECK(new_scope.extended_scopes.size() ==
  889. import_scope.extended_scopes.size());
  890. }
  891. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  892. SemIR::ConstantId class_const_id) -> ResolveResult {
  893. // TODO: The handling of interfaces repeats a lot with the handling of
  894. // classes, and will likely also be repeated for named constraints and
  895. // choice types. Factor out some of this functionality.
  896. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  897. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  898. if (!class_const_id.is_valid()) {
  899. // On the first pass, create a forward declaration of the class for any
  900. // recursive references.
  901. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  902. } else {
  903. // On the second pass, compute the class ID from the constant value of the
  904. // declaration.
  905. auto class_const_inst = context_.insts().Get(
  906. context_.constant_values().GetInstId(class_const_id));
  907. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  908. class_id = class_type->class_id;
  909. } else {
  910. auto generic_class_type =
  911. context_.types().GetAs<SemIR::GenericClassType>(
  912. class_const_inst.type_id());
  913. class_id = generic_class_type.class_id;
  914. }
  915. }
  916. // Load constants for the definition.
  917. auto initial_work = work_stack_.size();
  918. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  919. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  920. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  921. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  922. GetLocalParamConstantIds(import_class.param_refs_id);
  923. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  924. auto object_repr_const_id =
  925. import_class.object_repr_id.is_valid()
  926. ? GetLocalConstantId(import_class.object_repr_id)
  927. : SemIR::ConstantId::Invalid;
  928. auto base_id = import_class.base_id.is_valid()
  929. ? GetLocalConstantInstId(import_class.base_id)
  930. : SemIR::InstId::Invalid;
  931. if (HasNewWork(initial_work)) {
  932. return ResolveResult::Retry(class_const_id);
  933. }
  934. auto& new_class = context_.classes().Get(class_id);
  935. new_class.parent_scope_id = parent_scope_id;
  936. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  937. import_class.implicit_param_refs_id, implicit_param_const_ids);
  938. new_class.param_refs_id =
  939. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  940. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  941. if (import_class.is_defined()) {
  942. AddClassDefinition(import_class, new_class, object_repr_const_id,
  943. base_id);
  944. }
  945. return {.const_id = class_const_id};
  946. }
  947. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  948. auto initial_work = work_stack_.size();
  949. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  950. auto class_const_id =
  951. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  952. auto args = GetLocalSpecificArgs(inst.specific_id);
  953. if (HasNewWork(initial_work)) {
  954. return ResolveResult::Retry();
  955. }
  956. // Find the corresponding class type. For a non-generic class, this is the
  957. // type of the class declaration. For a generic class, build a class type
  958. // referencing this specialization of the generic class.
  959. auto class_const_inst = context_.insts().Get(
  960. context_.constant_values().GetInstId(class_const_id));
  961. if (class_const_inst.Is<SemIR::ClassType>()) {
  962. return {.const_id = class_const_id};
  963. } else {
  964. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  965. class_const_inst.type_id());
  966. auto specific_id = GetLocalSpecific(inst.specific_id, args);
  967. return ResolveAs<SemIR::ClassType>(
  968. {.type_id = SemIR::TypeId::TypeType,
  969. .class_id = generic_class_type.class_id,
  970. .specific_id = specific_id});
  971. }
  972. }
  973. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  974. auto initial_work = work_stack_.size();
  975. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  976. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  977. if (HasNewWork(initial_work)) {
  978. return ResolveResult::Retry();
  979. }
  980. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  981. return ResolveAs<SemIR::ConstType>(
  982. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  983. }
  984. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  985. auto initial_work = work_stack_.size();
  986. auto value_id = GetLocalConstantId(inst.value_id);
  987. if (HasNewWork(initial_work)) {
  988. return ResolveResult::Retry();
  989. }
  990. return {.const_id = value_id};
  991. }
  992. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  993. -> ResolveResult {
  994. auto initial_work = work_stack_.size();
  995. auto const_id = GetLocalConstantId(inst.type_id);
  996. if (HasNewWork(initial_work)) {
  997. return ResolveResult::Retry();
  998. }
  999. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  1000. AddImportIRInst(import_inst_id),
  1001. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1002. .name_id = GetLocalNameId(inst.name_id),
  1003. .index = inst.index});
  1004. return {.const_id = context_.constant_values().Get(inst_id)};
  1005. }
  1006. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  1007. auto initial_work = work_stack_.size();
  1008. const auto& function = import_ir_.functions().Get(inst.function_id);
  1009. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1010. if (function.return_storage_id.is_valid()) {
  1011. return_type_const_id =
  1012. GetLocalConstantId(function.GetDeclaredReturnType(import_ir_));
  1013. }
  1014. auto parent_scope_id = GetLocalNameScopeId(function.parent_scope_id);
  1015. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1016. GetLocalParamConstantIds(function.implicit_param_refs_id);
  1017. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1018. GetLocalParamConstantIds(function.param_refs_id);
  1019. if (HasNewWork(initial_work)) {
  1020. return ResolveResult::Retry();
  1021. }
  1022. // Add the function declaration.
  1023. SemIR::FunctionDecl function_decl = {
  1024. .type_id = SemIR::TypeId::Invalid,
  1025. .function_id = SemIR::FunctionId::Invalid,
  1026. .decl_block_id = SemIR::InstBlockId::Empty};
  1027. auto import_ir_inst_id = AddImportIRInst(function.latest_decl_id());
  1028. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  1029. SemIR::LocIdAndInst(import_ir_inst_id, function_decl));
  1030. // TODO: Implement import for generics.
  1031. auto generic_id = GetLocalGeneric(function.generic_id);
  1032. auto new_return_storage = SemIR::InstId::Invalid;
  1033. if (function.return_storage_id.is_valid()) {
  1034. // Recreate the return slot from scratch.
  1035. // TODO: Once we import function definitions, we'll need to make sure we
  1036. // use the same return storage variable in the declaration and definition.
  1037. new_return_storage = context_.AddInstInNoBlock<SemIR::VarStorage>(
  1038. AddImportIRInst(function.return_storage_id),
  1039. {.type_id = context_.GetTypeIdForTypeConstant(return_type_const_id),
  1040. .name_id = SemIR::NameId::ReturnSlot});
  1041. }
  1042. function_decl.function_id = context_.functions().Add(
  1043. {{.name_id = GetLocalNameId(function.name_id),
  1044. .parent_scope_id = parent_scope_id,
  1045. .generic_id = generic_id,
  1046. .first_param_node_id = Parse::NodeId::Invalid,
  1047. .last_param_node_id = Parse::NodeId::Invalid,
  1048. .implicit_param_refs_id = GetLocalParamRefsId(
  1049. function.implicit_param_refs_id, implicit_param_const_ids),
  1050. .param_refs_id =
  1051. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  1052. .decl_id = function_decl_id,
  1053. .definition_id = function.definition_id.is_valid()
  1054. ? function_decl_id
  1055. : SemIR::InstId::Invalid},
  1056. {.return_storage_id = new_return_storage,
  1057. .is_extern = function.is_extern,
  1058. .return_slot = function.return_slot,
  1059. .builtin_function_kind = function.builtin_function_kind}});
  1060. // TODO: Import this or recompute it.
  1061. auto specific_id = SemIR::SpecificId::Invalid;
  1062. function_decl.type_id =
  1063. context_.GetFunctionType(function_decl.function_id, specific_id);
  1064. // Write the function ID into the FunctionDecl.
  1065. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1066. return {.const_id = context_.constant_values().Get(function_decl_id)};
  1067. }
  1068. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1069. auto initial_work = work_stack_.size();
  1070. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1071. auto fn_val_id = GetLocalConstantInstId(
  1072. import_ir_.functions().Get(inst.function_id).decl_id);
  1073. if (HasNewWork(initial_work)) {
  1074. return ResolveResult::Retry();
  1075. }
  1076. auto fn_val = context_.insts().Get(fn_val_id);
  1077. CARBON_CHECK(context_.types().Is<SemIR::FunctionType>(fn_val.type_id()));
  1078. // TODO: Import the correct specific and build a function type constant
  1079. // using it.
  1080. return {.const_id = context_.types().GetConstantId(fn_val.type_id())};
  1081. }
  1082. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1083. auto initial_work = work_stack_.size();
  1084. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1085. auto class_val_id =
  1086. GetLocalConstantInstId(import_ir_.classes().Get(inst.class_id).decl_id);
  1087. if (HasNewWork(initial_work)) {
  1088. return ResolveResult::Retry();
  1089. }
  1090. auto class_val = context_.insts().Get(class_val_id);
  1091. CARBON_CHECK(
  1092. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1093. return {.const_id = context_.types().GetConstantId(class_val.type_id())};
  1094. }
  1095. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1096. auto initial_work = work_stack_.size();
  1097. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1098. auto interface_val_id = GetLocalConstantInstId(
  1099. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1100. if (HasNewWork(initial_work)) {
  1101. return ResolveResult::Retry();
  1102. }
  1103. auto interface_val = context_.insts().Get(interface_val_id);
  1104. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1105. interface_val.type_id()));
  1106. return {.const_id =
  1107. context_.types().GetConstantId(interface_val.type_id())};
  1108. }
  1109. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1110. SemIR::InstId inst_id) -> ResolveResult {
  1111. auto initial_work = work_stack_.size();
  1112. // Return the constant for the instruction of the imported constant.
  1113. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1114. if (!constant_id.is_valid()) {
  1115. return {.const_id = SemIR::ConstantId::Error};
  1116. }
  1117. if (!constant_id.is_constant()) {
  1118. context_.TODO(inst_id,
  1119. "Non-constant ImportRefLoaded (comes up with var)");
  1120. return {.const_id = SemIR::ConstantId::Error};
  1121. }
  1122. auto new_constant_id =
  1123. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1124. if (HasNewWork(initial_work)) {
  1125. return ResolveResult::Retry();
  1126. }
  1127. return {.const_id = new_constant_id};
  1128. }
  1129. // Make a declaration of an interface. This is done as a separate step from
  1130. // importing the interface definition in order to resolve cycles.
  1131. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1132. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1133. SemIR::InterfaceDecl interface_decl = {
  1134. .type_id = SemIR::TypeId::TypeType,
  1135. .interface_id = SemIR::InterfaceId::Invalid,
  1136. .decl_block_id = SemIR::InstBlockId::Empty};
  1137. auto interface_decl_id =
  1138. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1139. AddImportIRInst(import_interface.decl_id), interface_decl));
  1140. // Start with an incomplete interface.
  1141. interface_decl.interface_id = context_.interfaces().Add(
  1142. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1143. {}});
  1144. if (import_interface.is_generic()) {
  1145. interface_decl.type_id =
  1146. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1147. }
  1148. // Write the interface ID into the InterfaceDecl.
  1149. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1150. return {interface_decl.interface_id,
  1151. context_.constant_values().Get(interface_decl_id)};
  1152. }
  1153. // Imports the definition for an interface that has been imported as a forward
  1154. // declaration.
  1155. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1156. SemIR::Interface& new_interface,
  1157. SemIR::InstId self_param_id) -> void {
  1158. new_interface.scope_id = context_.name_scopes().Add(
  1159. new_interface.decl_id, SemIR::NameId::Invalid,
  1160. new_interface.parent_scope_id);
  1161. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1162. const auto& import_scope =
  1163. import_ir_.name_scopes().Get(import_interface.scope_id);
  1164. // Push a block so that we can add scoped instructions to it.
  1165. context_.inst_block_stack().Push();
  1166. AddNameScopeImportRefs(import_scope, new_scope);
  1167. new_interface.associated_entities_id =
  1168. AddAssociatedEntities(import_interface.associated_entities_id);
  1169. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1170. new_interface.self_param_id = self_param_id;
  1171. CARBON_CHECK(import_scope.extended_scopes.empty())
  1172. << "Interfaces don't currently have extended scopes to support.";
  1173. }
  1174. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1175. SemIR::ConstantId interface_const_id)
  1176. -> ResolveResult {
  1177. const auto& import_interface =
  1178. import_ir_.interfaces().Get(inst.interface_id);
  1179. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1180. if (!interface_const_id.is_valid()) {
  1181. // On the first pass, create a forward declaration of the interface.
  1182. std::tie(interface_id, interface_const_id) =
  1183. MakeInterfaceDecl(import_interface);
  1184. } else {
  1185. // On the second pass, compute the interface ID from the constant value of
  1186. // the declaration.
  1187. auto interface_const_inst = context_.insts().Get(
  1188. context_.constant_values().GetInstId(interface_const_id));
  1189. if (auto interface_type =
  1190. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1191. interface_id = interface_type->interface_id;
  1192. } else {
  1193. auto generic_interface_type =
  1194. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1195. interface_const_inst.type_id());
  1196. interface_id = generic_interface_type.interface_id;
  1197. }
  1198. }
  1199. auto initial_work = work_stack_.size();
  1200. auto parent_scope_id =
  1201. GetLocalNameScopeId(import_interface.parent_scope_id);
  1202. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1203. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1204. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1205. GetLocalParamConstantIds(import_interface.param_refs_id);
  1206. std::optional<SemIR::InstId> self_param_id;
  1207. if (import_interface.is_defined()) {
  1208. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1209. }
  1210. if (HasNewWork(initial_work)) {
  1211. return ResolveResult::Retry(interface_const_id);
  1212. }
  1213. auto& new_interface = context_.interfaces().Get(interface_id);
  1214. new_interface.parent_scope_id = parent_scope_id;
  1215. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1216. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1217. new_interface.param_refs_id =
  1218. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1219. if (import_interface.is_defined()) {
  1220. CARBON_CHECK(self_param_id);
  1221. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1222. }
  1223. return {.const_id = interface_const_id};
  1224. }
  1225. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1226. auto initial_work = work_stack_.size();
  1227. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1228. auto interface_const_id = GetLocalConstantId(
  1229. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1230. auto args = GetLocalSpecificArgs(inst.specific_id);
  1231. if (HasNewWork(initial_work)) {
  1232. return ResolveResult::Retry();
  1233. }
  1234. // Find the corresponding interface type. For a non-generic interface, this
  1235. // is the type of the interface declaration. For a generic interface, build
  1236. // a interface type referencing this specialization of the generic
  1237. // interface.
  1238. auto interface_const_inst = context_.insts().Get(
  1239. context_.constant_values().GetInstId(interface_const_id));
  1240. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1241. return {.const_id = interface_const_id};
  1242. } else {
  1243. auto generic_interface_type =
  1244. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1245. interface_const_inst.type_id());
  1246. auto specific_id = GetLocalSpecific(inst.specific_id, args);
  1247. return ResolveAs<SemIR::InterfaceType>(
  1248. {.type_id = SemIR::TypeId::TypeType,
  1249. .interface_id = generic_interface_type.interface_id,
  1250. .specific_id = specific_id});
  1251. }
  1252. }
  1253. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1254. auto initial_work = work_stack_.size();
  1255. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1256. if (HasNewWork(initial_work)) {
  1257. return ResolveResult::Retry();
  1258. }
  1259. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1260. return ResolveAs<SemIR::InterfaceWitness>(
  1261. {.type_id =
  1262. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1263. .elements_id = elements_id});
  1264. }
  1265. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1266. auto initial_work = work_stack_.size();
  1267. auto type_id = GetLocalConstantId(inst.type_id);
  1268. if (HasNewWork(initial_work)) {
  1269. return ResolveResult::Retry();
  1270. }
  1271. return ResolveAs<SemIR::IntLiteral>(
  1272. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1273. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1274. }
  1275. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1276. auto initial_work = work_stack_.size();
  1277. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1278. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1279. if (HasNewWork(initial_work)) {
  1280. return ResolveResult::Retry();
  1281. }
  1282. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1283. return ResolveAs<SemIR::PointerType>(
  1284. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1285. }
  1286. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1287. -> ResolveResult {
  1288. // Collect all constants first, locating unresolved ones in a single pass.
  1289. auto initial_work = work_stack_.size();
  1290. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1291. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1292. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1293. field_const_ids.reserve(orig_fields.size());
  1294. for (auto field_id : orig_fields) {
  1295. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1296. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1297. }
  1298. if (HasNewWork(initial_work)) {
  1299. return ResolveResult::Retry();
  1300. }
  1301. // Prepare a vector of fields for GetStructType.
  1302. // TODO: Should we have field constants so that we can deduplicate fields
  1303. // without creating instructions here?
  1304. llvm::SmallVector<SemIR::InstId> fields;
  1305. fields.reserve(orig_fields.size());
  1306. for (auto [field_id, field_const_id] :
  1307. llvm::zip(orig_fields, field_const_ids)) {
  1308. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1309. auto name_id = GetLocalNameId(field.name_id);
  1310. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1311. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1312. AddImportIRInst(import_inst_id),
  1313. {.name_id = name_id, .field_type_id = field_type_id}));
  1314. }
  1315. return ResolveAs<SemIR::StructType>(
  1316. {.type_id = SemIR::TypeId::TypeType,
  1317. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1318. }
  1319. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1320. auto initial_work = work_stack_.size();
  1321. auto type_id = GetLocalConstantId(inst.type_id);
  1322. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1323. if (HasNewWork(initial_work)) {
  1324. return ResolveResult::Retry();
  1325. }
  1326. return ResolveAs<SemIR::StructValue>(
  1327. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1328. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1329. }
  1330. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1331. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1332. // Collect all constants first, locating unresolved ones in a single pass.
  1333. auto initial_work = work_stack_.size();
  1334. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1335. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1336. elem_const_ids.reserve(orig_elem_type_ids.size());
  1337. for (auto elem_type_id : orig_elem_type_ids) {
  1338. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1339. }
  1340. if (HasNewWork(initial_work)) {
  1341. return ResolveResult::Retry();
  1342. }
  1343. // Prepare a vector of the tuple types for GetTupleType.
  1344. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1345. elem_type_ids.reserve(orig_elem_type_ids.size());
  1346. for (auto elem_const_id : elem_const_ids) {
  1347. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1348. }
  1349. return {.const_id = context_.types().GetConstantId(
  1350. context_.GetTupleType(elem_type_ids))};
  1351. }
  1352. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1353. auto initial_work = work_stack_.size();
  1354. auto type_id = GetLocalConstantId(inst.type_id);
  1355. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1356. if (HasNewWork(initial_work)) {
  1357. return ResolveResult::Retry();
  1358. }
  1359. return ResolveAs<SemIR::TupleValue>(
  1360. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1361. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1362. }
  1363. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1364. auto initial_work = work_stack_.size();
  1365. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1366. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1367. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1368. if (HasNewWork(initial_work)) {
  1369. return ResolveResult::Retry();
  1370. }
  1371. return ResolveAs<SemIR::UnboundElementType>(
  1372. {.type_id = SemIR::TypeId::TypeType,
  1373. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1374. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1375. }
  1376. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1377. return context_.import_ir_constant_values()[import_ir_id_.index];
  1378. }
  1379. Context& context_;
  1380. SemIR::ImportIRId import_ir_id_;
  1381. const SemIR::File& import_ir_;
  1382. llvm::SmallVector<Work> work_stack_;
  1383. };
  1384. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1385. // loaded (including the one pointed at directly by the ImportRef), and the
  1386. // final instruction's type ID.
  1387. //
  1388. // This addresses cases where an ImportRefUnloaded may point at another
  1389. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1390. // constant-evaluated version of the instruction to work with.
  1391. static auto GetInstForLoad(Context& context,
  1392. SemIR::ImportIRInstId import_ir_inst_id)
  1393. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1394. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1395. {}, SemIR::TypeId::Invalid};
  1396. auto& [import_ir_insts, type_id] = result;
  1397. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1398. // The first ImportIRInst is added directly because the IR doesn't need to be
  1399. // localized.
  1400. import_ir_insts.push_back(import_ir_inst);
  1401. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1402. while (true) {
  1403. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1404. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1405. if (!import_ref) {
  1406. type_id = cursor_inst.type_id();
  1407. return result;
  1408. }
  1409. import_ir_inst =
  1410. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1411. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1412. import_ir_insts.push_back(
  1413. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1414. .is_export = false,
  1415. .sem_ir = cursor_ir}),
  1416. .inst_id = import_ir_inst.inst_id});
  1417. }
  1418. }
  1419. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1420. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1421. if (!inst) {
  1422. return;
  1423. }
  1424. auto [indirect_insts, load_type_id] =
  1425. GetInstForLoad(context, inst->import_ir_inst_id);
  1426. // The last indirect instruction is the one to resolve. Pop it here because
  1427. // Resolve will assign the constant.
  1428. auto load_ir_inst = indirect_insts.pop_back_val();
  1429. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1430. // The resolver calls into Context to create instructions. Don't register
  1431. // those instructions as part of the enclosing generic scope if they're
  1432. // dependent on a generic parameter.
  1433. context.generic_region_stack().Push();
  1434. auto type_id = resolver.ResolveType(load_type_id);
  1435. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1436. context.generic_region_stack().Pop();
  1437. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1438. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1439. // TryEvalInst, which we want to avoid with ImportRefs.
  1440. context.sem_ir().insts().Set(
  1441. inst_id,
  1442. SemIR::ImportRefLoaded{.type_id = type_id,
  1443. .import_ir_inst_id = inst->import_ir_inst_id,
  1444. .entity_name_id = inst->entity_name_id});
  1445. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1446. context.constant_values().Set(inst_id, constant_id);
  1447. for (const auto& import_ir_inst : indirect_insts) {
  1448. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1449. import_ir_inst.inst_id, constant_id);
  1450. }
  1451. }
  1452. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1453. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1454. const SemIR::File& import_ir,
  1455. SemIR::ImplId import_impl_id) -> void {
  1456. // Resolve the imported impl to a local impl ID.
  1457. ImportRefResolver resolver(context, import_ir_id);
  1458. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1459. auto self_id = resolver.ResolveType(import_impl.self_id);
  1460. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1461. // Import the definition if the impl is defined.
  1462. // TODO: Do we need to check for multiple definitions?
  1463. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1464. if (import_impl.is_defined()) {
  1465. // TODO: Create a scope for the `impl` if necessary.
  1466. // TODO: Consider importing the definition_id.
  1467. auto& impl = context.impls().Get(impl_id);
  1468. impl.witness_id = AddImportRef(
  1469. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1470. SemIR::EntityNameId::Invalid);
  1471. }
  1472. }
  1473. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1474. // and this file elsewhere.
  1475. auto ImportImpls(Context& context) -> void {
  1476. for (auto [import_index, import_ir] :
  1477. llvm::enumerate(context.import_irs().array_ref())) {
  1478. if (!import_ir.sem_ir) {
  1479. continue;
  1480. }
  1481. auto import_ir_id = SemIR::ImportIRId(import_index);
  1482. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1483. auto impl_id = SemIR::ImplId(impl_index);
  1484. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1485. }
  1486. }
  1487. }
  1488. } // namespace Carbon::Check