import_ref.cpp 68 KB

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