import_ref.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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/inst.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. // Adds the ImportIR, excluding the update to the check_ir_map.
  18. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  19. -> SemIR::ImportIRId {
  20. context.import_ir_constant_values().push_back(
  21. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  22. return context.import_irs().Add(import_ir);
  23. }
  24. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  25. auto ir_id = SemIR::ImportIRId::Invalid;
  26. if (import_ir.sem_ir != nullptr) {
  27. ir_id = AddImportIR(context, import_ir);
  28. } else {
  29. // We don't have a check_ir_id, so add without touching check_ir_map.
  30. ir_id = InternalAddImportIR(context, import_ir);
  31. }
  32. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl)
  33. << "ApiForImpl must be the first IR";
  34. }
  35. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  36. -> SemIR::ImportIRId {
  37. auto& ir_id = context.check_ir_map()[import_ir.sem_ir->check_ir_id().index];
  38. if (!ir_id.is_valid()) {
  39. // Note this updates check_ir_map.
  40. ir_id = InternalAddImportIR(context, import_ir);
  41. }
  42. return ir_id;
  43. }
  44. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst)
  45. -> SemIR::InstId {
  46. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  47. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  48. {import_ir_inst_id, SemIR::ImportRefUnloaded{import_ir_inst_id}});
  49. // We can't insert this instruction into whatever block we happen to be in,
  50. // because this function is typically called by name lookup in the middle of
  51. // an otherwise unknown checking step. But we need to add the instruction
  52. // somewhere, because it's referenced by other instructions and needs to be
  53. // visible in textual IR. Adding it to the file block is arbitrary but is the
  54. // best place we have right now.
  55. //
  56. // TODO: Consider adding a dedicated block for import_refs.
  57. context.inst_block_stack().AddInstIdToFileBlock(import_ref_id);
  58. return import_ref_id;
  59. }
  60. // Resolves an instruction from an imported IR into a constant referring to the
  61. // current IR.
  62. //
  63. // Calling Resolve on an instruction operates in an iterative manner, tracking
  64. // Work items on work_stack_. At a high level, the loop is:
  65. //
  66. // 1. If a constant value is already known for the work item, and we're
  67. // processing it for the first time, it's considered resolved.
  68. // - The constant check avoids performance costs of deduplication on add.
  69. // - If `retry` is set, we process it again, because it didn't complete last
  70. // time, even though we have a constant value already.
  71. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  72. // - For instructions that can be forward declared, if we don't already have
  73. // a constant value from a previous attempt at resolution, start by making
  74. // a forward declared constant value to address circular references.
  75. // - Gather all input constants.
  76. // - Gathering constants directly adds unresolved values to work_stack_.
  77. // - If any need to be resolved (HasNewWork), return Retry(): this
  78. // instruction needs two calls to complete.
  79. // - If the constant value is already known because we have made a forward
  80. // declaration, pass it to Retry(). It will be passed to future attempts
  81. // to resolve this instruction so the earlier work can be found, and will
  82. // be made available for other instructions to use.
  83. // - The second attempt to resolve this instruction must produce the same
  84. // constant, because the value may have already been used by resolved
  85. // instructions.
  86. // - Build any necessary IR structures, and return the output constant.
  87. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  88. // remain, and may no longer be at the top of the stack; set `retry` on it so
  89. // we'll make sure to run it again later.
  90. //
  91. // TryResolveInst/TryResolveTypedInst can complete in one call for a given
  92. // instruction, but should always complete within two calls. However, due to the
  93. // chance of a second call, it's important to reserve all expensive logic until
  94. // it's been established that input constants are available; this in particular
  95. // includes GetTypeIdForTypeConstant calls which do a hash table lookup.
  96. //
  97. // TODO: Fix class `extern` handling and merging, rewrite tests.
  98. // - check/testdata/class/cross_package_import.carbon
  99. // - check/testdata/class/extern.carbon
  100. // TODO: Fix function `extern` handling and merging, rewrite tests.
  101. // - check/testdata/function/declaration/import.carbon
  102. // - check/testdata/packages/cross_package_import.carbon
  103. class ImportRefResolver {
  104. public:
  105. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  106. : context_(context),
  107. import_ir_id_(import_ir_id),
  108. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  109. // Iteratively resolves an imported instruction's inner references until a
  110. // constant ID referencing the current IR is produced. See the class comment
  111. // for more details.
  112. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  113. work_stack_.push_back({inst_id});
  114. while (!work_stack_.empty()) {
  115. auto work = work_stack_.back();
  116. CARBON_CHECK(work.inst_id.is_valid());
  117. // Step 1: check for a constant value.
  118. auto existing = FindResolvedConstId(work.inst_id);
  119. if (existing.const_id.is_valid() && !work.retry) {
  120. work_stack_.pop_back();
  121. continue;
  122. }
  123. // Step 2: resolve the instruction.
  124. auto initial_work = work_stack_.size();
  125. auto [new_const_id, finished] =
  126. TryResolveInst(work.inst_id, existing.const_id);
  127. CARBON_CHECK(finished == !HasNewWork(initial_work));
  128. CARBON_CHECK(!existing.const_id.is_valid() ||
  129. existing.const_id == new_const_id)
  130. << "Constant value changed in second pass.";
  131. if (!existing.const_id.is_valid()) {
  132. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  133. }
  134. // Step 3: pop or retry.
  135. if (finished) {
  136. work_stack_.pop_back();
  137. } else {
  138. work_stack_[initial_work - 1].retry = true;
  139. }
  140. }
  141. auto constant_id = import_ir_constant_values().Get(inst_id);
  142. CARBON_CHECK(constant_id.is_valid());
  143. return constant_id;
  144. }
  145. // Wraps constant evaluation with logic to handle types.
  146. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  147. if (!import_type_id.is_valid()) {
  148. return import_type_id;
  149. }
  150. auto import_type_inst_id = import_ir_.types().GetInstId(import_type_id);
  151. CARBON_CHECK(import_type_inst_id.is_valid());
  152. if (import_type_inst_id.is_builtin()) {
  153. // Builtins don't require constant resolution; we can use them directly.
  154. return context_.GetBuiltinType(import_type_inst_id.builtin_kind());
  155. } else {
  156. return context_.GetTypeIdForTypeConstant(Resolve(import_type_inst_id));
  157. }
  158. }
  159. private:
  160. // A step in work_stack_.
  161. struct Work {
  162. // The instruction to work on.
  163. SemIR::InstId inst_id;
  164. // True if another pass was requested last time this was run.
  165. bool retry = false;
  166. };
  167. // The result of attempting to resolve an imported instruction to a constant.
  168. struct ResolveResult {
  169. // Try resolving this function again. If `const_id` is specified, it will be
  170. // passed to the next resolution attempt.
  171. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  172. -> ResolveResult {
  173. return {.const_id = const_id, .finished = false};
  174. }
  175. // The new constant value, if known.
  176. SemIR::ConstantId const_id;
  177. // Whether resolution has finished. If false, `TryResolveInst` will be
  178. // called again. Note that this is not strictly necessary, and we can get
  179. // the same information by checking whether new work was added to the stack.
  180. // However, we use this for consistency checks between resolve actions and
  181. // the work stack.
  182. bool finished = true;
  183. };
  184. // The constant found by FindResolvedConstId.
  185. struct ResolvedConstId {
  186. // The constant for the instruction. Invalid if not yet resolved.
  187. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  188. // Instructions which are indirect but equivalent to the current instruction
  189. // being resolved, and should have their constant set to the same. Empty
  190. // when const_id is valid.
  191. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  192. };
  193. // Looks to see if an instruction has been resolved. If a constant is only
  194. // found indirectly, sets the constant for any indirect steps that don't
  195. // already have the constant. If a constant isn't found, returns the indirect
  196. // instructions so that they can have the resolved constant assigned later.
  197. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  198. ResolvedConstId result;
  199. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  200. existing_const_id.is_valid()) {
  201. result.const_id = existing_const_id;
  202. return result;
  203. }
  204. const auto* cursor_ir = &import_ir_;
  205. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  206. auto cursor_inst_id = inst_id;
  207. while (true) {
  208. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  209. if (!loc_id.is_import_ir_inst_id()) {
  210. return result;
  211. }
  212. auto ir_inst =
  213. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  214. const auto* prev_ir = cursor_ir;
  215. auto prev_inst_id = cursor_inst_id;
  216. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  217. cursor_ir_id = context_.check_ir_map()[cursor_ir->check_ir_id().index];
  218. if (!cursor_ir_id.is_valid()) {
  219. // TODO: Should we figure out a location to assign here?
  220. cursor_ir_id = AddImportIR(
  221. context_, {.node_id = Parse::NodeId::Invalid, .sem_ir = cursor_ir});
  222. }
  223. cursor_inst_id = ir_inst.inst_id;
  224. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id)
  225. << cursor_ir->insts().Get(cursor_inst_id);
  226. if (auto const_id =
  227. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  228. cursor_inst_id);
  229. const_id.is_valid()) {
  230. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  231. result.const_id = const_id;
  232. result.indirect_insts.clear();
  233. return result;
  234. } else {
  235. result.indirect_insts.push_back(
  236. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  237. }
  238. }
  239. }
  240. // Sets a resolved constant into the current and indirect instructions.
  241. auto SetResolvedConstId(SemIR::InstId inst_id,
  242. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  243. SemIR::ConstantId const_id) -> void {
  244. import_ir_constant_values().Set(inst_id, const_id);
  245. for (auto indirect_inst : indirect_insts) {
  246. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  247. indirect_inst.inst_id, const_id);
  248. }
  249. }
  250. // Returns true if new unresolved constants were found.
  251. //
  252. // At the start of a function, do:
  253. // auto initial_work = work_stack_.size();
  254. // Then when determining:
  255. // if (HasNewWork(initial_work)) { ... }
  256. auto HasNewWork(size_t initial_work) -> bool {
  257. CARBON_CHECK(initial_work <= work_stack_.size())
  258. << "Work shouldn't decrease";
  259. return initial_work < work_stack_.size();
  260. }
  261. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  262. return context_.import_ir_insts().Add(
  263. {.ir_id = import_ir_id_, .inst_id = inst_id});
  264. }
  265. // Returns the ConstantId for an InstId. Adds unresolved constants to
  266. // work_stack_.
  267. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  268. auto const_id = import_ir_constant_values().Get(inst_id);
  269. if (!const_id.is_valid()) {
  270. work_stack_.push_back({inst_id});
  271. }
  272. return const_id;
  273. }
  274. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  275. // work_stack_.
  276. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  277. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  278. }
  279. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  280. // to work_stack_.
  281. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  282. -> llvm::SmallVector<SemIR::ConstantId> {
  283. llvm::SmallVector<SemIR::ConstantId> const_ids;
  284. if (!param_refs_id.is_valid() ||
  285. param_refs_id == SemIR::InstBlockId::Empty) {
  286. return const_ids;
  287. }
  288. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  289. const_ids.reserve(param_refs.size());
  290. for (auto inst_id : param_refs) {
  291. const_ids.push_back(
  292. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  293. // If the parameter is a symbolic binding, build the BindSymbolicName
  294. // constant.
  295. auto bind_id = inst_id;
  296. if (auto addr =
  297. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  298. bind_id = addr->inner_id;
  299. }
  300. GetLocalConstantId(bind_id);
  301. }
  302. return const_ids;
  303. }
  304. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  305. // a version of param_refs_id localized to the current IR.
  306. auto GetLocalParamRefsId(
  307. SemIR::InstBlockId param_refs_id,
  308. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  309. -> SemIR::InstBlockId {
  310. if (!param_refs_id.is_valid() ||
  311. param_refs_id == SemIR::InstBlockId::Empty) {
  312. return param_refs_id;
  313. }
  314. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  315. llvm::SmallVector<SemIR::InstId> new_param_refs;
  316. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  317. // Figure out the param structure. This echoes
  318. // Function::GetParamFromParamRefId.
  319. // TODO: Consider a different parameter handling to simplify import logic.
  320. auto inst = import_ir_.insts().Get(ref_id);
  321. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  322. auto bind_id = ref_id;
  323. auto param_id = ref_id;
  324. if (addr_inst) {
  325. bind_id = addr_inst->inner_id;
  326. param_id = bind_id;
  327. inst = import_ir_.insts().Get(bind_id);
  328. }
  329. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  330. if (bind_inst) {
  331. param_id = bind_inst->value_id;
  332. inst = import_ir_.insts().Get(param_id);
  333. }
  334. auto param_inst = inst.As<SemIR::Param>();
  335. // Rebuild the param instruction.
  336. auto name_id = GetLocalNameId(param_inst.name_id);
  337. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  338. auto new_param_id = context_.AddInstInNoBlock(
  339. {AddImportIRInst(param_id), SemIR::Param{type_id, name_id}});
  340. if (bind_inst) {
  341. switch (bind_inst->kind) {
  342. case SemIR::BindName::Kind: {
  343. auto bind_name_id = context_.bind_names().Add(
  344. {.name_id = name_id,
  345. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  346. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  347. new_param_id = context_.AddInstInNoBlock(
  348. {AddImportIRInst(bind_id),
  349. SemIR::BindName{type_id, bind_name_id, new_param_id}});
  350. break;
  351. }
  352. case SemIR::BindSymbolicName::Kind: {
  353. // The symbolic name will be created on first reference, so might
  354. // already exist. Update the value in it to refer to the parameter.
  355. auto new_bind_inst_id = GetLocalConstantId(bind_id).inst_id();
  356. auto new_bind_inst =
  357. context_.insts().GetAs<SemIR::BindSymbolicName>(
  358. new_bind_inst_id);
  359. new_bind_inst.value_id = new_param_id;
  360. // This is not before constant use, but doesn't change the
  361. // constant value of the instruction.
  362. context_.ReplaceInstBeforeConstantUse(new_bind_inst_id,
  363. new_bind_inst);
  364. new_param_id = new_bind_inst_id;
  365. break;
  366. }
  367. default: {
  368. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  369. }
  370. }
  371. }
  372. if (addr_inst) {
  373. new_param_id = context_.AddInstInNoBlock(
  374. {AddImportIRInst(ref_id),
  375. SemIR::AddrPattern{type_id, new_param_id}});
  376. }
  377. new_param_refs.push_back(new_param_id);
  378. }
  379. return context_.inst_blocks().Add(new_param_refs);
  380. }
  381. // Translates a NameId from the import IR to a local NameId.
  382. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  383. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  384. return SemIR::NameId::ForIdentifier(
  385. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  386. }
  387. return import_name_id;
  388. }
  389. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  390. // unresolved constants to the work stack.
  391. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  392. -> SemIR::NameScopeId {
  393. auto inst_id = import_ir_.name_scopes().GetInstIdIfValid(name_scope_id);
  394. if (!inst_id.is_valid()) {
  395. // Map scopes that aren't associated with an instruction to invalid
  396. // scopes. For now, such scopes aren't used, and we don't have a good way
  397. // to remap them.
  398. return SemIR::NameScopeId::Invalid;
  399. }
  400. if (import_ir_.insts().Is<SemIR::ImplDecl>(inst_id)) {
  401. // TODO: Import the scope for an `impl` definition.
  402. return SemIR::NameScopeId::Invalid;
  403. }
  404. auto const_id = GetLocalConstantId(inst_id);
  405. if (!const_id.is_valid()) {
  406. return SemIR::NameScopeId::Invalid;
  407. }
  408. auto name_scope_inst = context_.insts().Get(const_id.inst_id());
  409. CARBON_KIND_SWITCH(name_scope_inst) {
  410. case CARBON_KIND(SemIR::Namespace inst): {
  411. return inst.name_scope_id;
  412. }
  413. case CARBON_KIND(SemIR::ClassType inst): {
  414. return context_.classes().Get(inst.class_id).scope_id;
  415. }
  416. case CARBON_KIND(SemIR::InterfaceType inst): {
  417. return context_.interfaces().Get(inst.interface_id).scope_id;
  418. }
  419. default:
  420. if (const_id == SemIR::ConstantId::Error) {
  421. return SemIR::NameScopeId::Invalid;
  422. }
  423. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  424. << name_scope_inst;
  425. }
  426. }
  427. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  428. // lookup.
  429. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  430. SemIR::NameScope& new_scope) -> void {
  431. for (auto [entry_name_id, entry_inst_id] : import_scope.names) {
  432. auto ref_id = AddImportRef(
  433. context_, {.ir_id = import_ir_id_, .inst_id = entry_inst_id});
  434. CARBON_CHECK(
  435. new_scope.names.insert({GetLocalNameId(entry_name_id), ref_id})
  436. .second);
  437. }
  438. }
  439. // Given a block ID for a list of associated entities of a witness, returns a
  440. // version localized to the current IR.
  441. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  442. -> SemIR::InstBlockId {
  443. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  444. return SemIR::InstBlockId::Empty;
  445. }
  446. auto associated_entities =
  447. import_ir_.inst_blocks().Get(associated_entities_id);
  448. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  449. new_associated_entities.reserve(associated_entities.size());
  450. for (auto inst_id : associated_entities) {
  451. new_associated_entities.push_back(
  452. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id}));
  453. }
  454. return context_.inst_blocks().Add(new_associated_entities);
  455. }
  456. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  457. // more has been added to the stack. A similar API is followed for all
  458. // following TryResolveTypedInst helper functions.
  459. //
  460. // `const_id` is Invalid unless we've tried to resolve this instruction
  461. // before, in which case it's the previous result.
  462. //
  463. // TODO: Error is returned when support is missing, but that should go away.
  464. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  465. -> ResolveResult {
  466. if (inst_id.is_builtin()) {
  467. CARBON_CHECK(!const_id.is_valid());
  468. // Constants for builtins can be directly copied.
  469. return {context_.constant_values().Get(inst_id)};
  470. }
  471. auto untyped_inst = import_ir_.insts().Get(inst_id);
  472. CARBON_KIND_SWITCH(untyped_inst) {
  473. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  474. return TryResolveTypedInst(inst);
  475. }
  476. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  477. return TryResolveTypedInst(inst);
  478. }
  479. case CARBON_KIND(SemIR::BaseDecl inst): {
  480. return TryResolveTypedInst(inst, inst_id);
  481. }
  482. case CARBON_KIND(SemIR::BindAlias inst): {
  483. return TryResolveTypedInst(inst);
  484. }
  485. case CARBON_KIND(SemIR::BindName inst): {
  486. // TODO: This always returns `ConstantId::NotConstant`.
  487. return {TryEvalInst(context_, inst_id, inst)};
  488. }
  489. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  490. return TryResolveTypedInst(inst, inst_id);
  491. }
  492. case CARBON_KIND(SemIR::ClassDecl inst): {
  493. return TryResolveTypedInst(inst, const_id);
  494. }
  495. case CARBON_KIND(SemIR::ClassType inst): {
  496. return TryResolveTypedInst(inst);
  497. }
  498. case CARBON_KIND(SemIR::ConstType inst): {
  499. return TryResolveTypedInst(inst);
  500. }
  501. case CARBON_KIND(SemIR::FieldDecl inst): {
  502. return TryResolveTypedInst(inst, inst_id);
  503. }
  504. case CARBON_KIND(SemIR::FunctionDecl inst): {
  505. return TryResolveTypedInst(inst);
  506. }
  507. case CARBON_KIND(SemIR::FunctionType inst): {
  508. return TryResolveTypedInst(inst);
  509. }
  510. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  511. return TryResolveTypedInst(inst, inst_id);
  512. }
  513. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  514. return TryResolveTypedInst(inst, const_id);
  515. }
  516. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  517. return TryResolveTypedInst(inst);
  518. }
  519. case CARBON_KIND(SemIR::InterfaceType inst): {
  520. return TryResolveTypedInst(inst);
  521. }
  522. case CARBON_KIND(SemIR::PointerType inst): {
  523. return TryResolveTypedInst(inst);
  524. }
  525. case CARBON_KIND(SemIR::StructType inst): {
  526. return TryResolveTypedInst(inst, inst_id);
  527. }
  528. case CARBON_KIND(SemIR::TupleType inst): {
  529. return TryResolveTypedInst(inst);
  530. }
  531. case CARBON_KIND(SemIR::UnboundElementType inst): {
  532. return TryResolveTypedInst(inst);
  533. }
  534. default:
  535. context_.TODO(
  536. SemIR::LocId(AddImportIRInst(inst_id)),
  537. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  538. return {SemIR::ConstantId::Error};
  539. }
  540. }
  541. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  542. auto initial_work = work_stack_.size();
  543. auto type_const_id = GetLocalConstantId(inst.type_id);
  544. if (HasNewWork(initial_work)) {
  545. return ResolveResult::Retry();
  546. }
  547. // Add a lazy reference to the target declaration.
  548. auto decl_id = AddImportRef(
  549. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id});
  550. auto inst_id = context_.AddInstInNoBlock(
  551. {AddImportIRInst(inst.decl_id),
  552. SemIR::AssociatedEntity{
  553. context_.GetTypeIdForTypeConstant(type_const_id), inst.index,
  554. decl_id}});
  555. return {context_.constant_values().Get(inst_id)};
  556. }
  557. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  558. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  559. auto initial_work = work_stack_.size();
  560. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  561. auto interface_const_id = GetLocalConstantId(
  562. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  563. if (HasNewWork(initial_work)) {
  564. return ResolveResult::Retry();
  565. }
  566. // TODO: Should this track the source?
  567. auto inst_id = context_.AddInstInNoBlock(
  568. SemIR::LocIdAndInst::NoLoc(SemIR::AssociatedEntityType{
  569. SemIR::TypeId::TypeType,
  570. context_.insts()
  571. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  572. .interface_id,
  573. context_.GetTypeIdForTypeConstant(entity_type_const_id)}));
  574. return {context_.constant_values().Get(inst_id)};
  575. }
  576. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  577. -> ResolveResult {
  578. auto initial_work = work_stack_.size();
  579. auto type_const_id = GetLocalConstantId(inst.type_id);
  580. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  581. if (HasNewWork(initial_work)) {
  582. return ResolveResult::Retry();
  583. }
  584. // Import the instruction in order to update contained base_type_id.
  585. auto inst_id = context_.AddInstInNoBlock(
  586. {AddImportIRInst(import_inst_id),
  587. SemIR::BaseDecl{context_.GetTypeIdForTypeConstant(type_const_id),
  588. context_.GetTypeIdForTypeConstant(base_type_const_id),
  589. inst.index}});
  590. return {context_.constant_values().Get(inst_id)};
  591. }
  592. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  593. auto initial_work = work_stack_.size();
  594. auto value_id = GetLocalConstantId(inst.value_id);
  595. if (HasNewWork(initial_work)) {
  596. return ResolveResult::Retry();
  597. }
  598. return {value_id};
  599. }
  600. auto TryResolveTypedInst(SemIR::BindSymbolicName inst,
  601. SemIR::InstId import_inst_id) -> ResolveResult {
  602. auto initial_work = work_stack_.size();
  603. auto type_id = GetLocalConstantId(inst.type_id);
  604. if (HasNewWork(initial_work)) {
  605. return ResolveResult::Retry();
  606. }
  607. const auto& import_bind_info =
  608. import_ir_.bind_names().Get(inst.bind_name_id);
  609. auto name_id = GetLocalNameId(import_bind_info.name_id);
  610. auto bind_name_id = context_.bind_names().Add(
  611. {.name_id = name_id,
  612. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  613. .bind_index = import_bind_info.bind_index});
  614. auto new_bind_id = context_.AddInstInNoBlock(
  615. {AddImportIRInst(import_inst_id),
  616. SemIR::BindSymbolicName{context_.GetTypeIdForTypeConstant(type_id),
  617. bind_name_id, SemIR::InstId::Invalid}});
  618. return {context_.constant_values().Get(new_bind_id)};
  619. }
  620. // Makes an incomplete class. This is necessary even with classes with a
  621. // complete declaration, because things such as `Self` may refer back to the
  622. // type.
  623. auto MakeIncompleteClass(const SemIR::Class& import_class)
  624. -> SemIR::ConstantId {
  625. auto class_decl =
  626. SemIR::ClassDecl{SemIR::TypeId::TypeType, SemIR::ClassId::Invalid,
  627. SemIR::InstBlockId::Empty};
  628. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  629. {AddImportIRInst(import_class.decl_id), class_decl});
  630. // Regardless of whether ClassDecl is a complete type, we first need an
  631. // incomplete type so that any references have something to point at.
  632. class_decl.class_id = context_.classes().Add({
  633. .name_id = GetLocalNameId(import_class.name_id),
  634. // Set in the second pass once we've imported them.
  635. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  636. .implicit_param_refs_id = SemIR::InstBlockId::Invalid,
  637. .param_refs_id = SemIR::InstBlockId::Invalid,
  638. // `.self_type_id` depends on the ClassType, so is set below.
  639. .self_type_id = SemIR::TypeId::Invalid,
  640. .decl_id = class_decl_id,
  641. .inheritance_kind = import_class.inheritance_kind,
  642. });
  643. // Write the class ID into the ClassDecl.
  644. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  645. auto self_const_id = context_.constant_values().Get(class_decl_id);
  646. // Build the `Self` type using the resulting type constant.
  647. auto& class_info = context_.classes().Get(class_decl.class_id);
  648. class_info.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  649. return self_const_id;
  650. }
  651. // Fills out the class definition for an incomplete class.
  652. auto AddClassDefinition(const SemIR::Class& import_class,
  653. SemIR::Class& new_class,
  654. SemIR::ConstantId object_repr_const_id,
  655. SemIR::ConstantId base_const_id) -> void {
  656. new_class.definition_id = new_class.decl_id;
  657. new_class.object_repr_id =
  658. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  659. new_class.scope_id =
  660. context_.name_scopes().Add(new_class.decl_id, SemIR::NameId::Invalid,
  661. new_class.enclosing_scope_id);
  662. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  663. const auto& import_scope =
  664. import_ir_.name_scopes().Get(import_class.scope_id);
  665. // Push a block so that we can add scoped instructions to it.
  666. context_.inst_block_stack().Push();
  667. AddNameScopeImportRefs(import_scope, new_scope);
  668. new_class.body_block_id = context_.inst_block_stack().Pop();
  669. if (import_class.base_id.is_valid()) {
  670. new_class.base_id = base_const_id.inst_id();
  671. // Add the base scope to extended scopes.
  672. auto base_inst_id = context_.types().GetInstId(
  673. context_.insts()
  674. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  675. .base_type_id);
  676. const auto& base_class = context_.classes().Get(
  677. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  678. new_scope.extended_scopes.push_back(base_class.scope_id);
  679. }
  680. CARBON_CHECK(new_scope.extended_scopes.size() ==
  681. import_scope.extended_scopes.size());
  682. }
  683. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  684. SemIR::ConstantId class_const_id) -> ResolveResult {
  685. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  686. // On the first pass, create a forward declaration of the class for any
  687. // recursive references.
  688. if (!class_const_id.is_valid()) {
  689. class_const_id = MakeIncompleteClass(import_class);
  690. }
  691. // Load constants for the definition.
  692. auto initial_work = work_stack_.size();
  693. auto enclosing_scope_id =
  694. GetLocalNameScopeId(import_class.enclosing_scope_id);
  695. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  696. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  697. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  698. GetLocalParamConstantIds(import_class.param_refs_id);
  699. auto object_repr_const_id =
  700. import_class.object_repr_id.is_valid()
  701. ? GetLocalConstantId(import_class.object_repr_id)
  702. : SemIR::ConstantId::Invalid;
  703. auto base_const_id = import_class.base_id.is_valid()
  704. ? GetLocalConstantId(import_class.base_id)
  705. : SemIR::ConstantId::Invalid;
  706. if (HasNewWork(initial_work)) {
  707. return ResolveResult::Retry(class_const_id);
  708. }
  709. auto& new_class = context_.classes().Get(
  710. context_.insts()
  711. .GetAs<SemIR::ClassType>(class_const_id.inst_id())
  712. .class_id);
  713. new_class.enclosing_scope_id = enclosing_scope_id;
  714. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  715. import_class.implicit_param_refs_id, implicit_param_const_ids);
  716. new_class.param_refs_id =
  717. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  718. if (import_class.is_defined()) {
  719. AddClassDefinition(import_class, new_class, object_repr_const_id,
  720. base_const_id);
  721. }
  722. return {class_const_id};
  723. }
  724. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  725. auto initial_work = work_stack_.size();
  726. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  727. auto class_const_id =
  728. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  729. if (HasNewWork(initial_work)) {
  730. return ResolveResult::Retry();
  731. }
  732. return {class_const_id};
  733. }
  734. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  735. auto initial_work = work_stack_.size();
  736. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  737. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  738. if (HasNewWork(initial_work)) {
  739. return ResolveResult::Retry();
  740. }
  741. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  742. // TODO: Should ConstType have a wrapper for this similar to the others?
  743. return {
  744. TryEvalInst(context_, SemIR::InstId::Invalid,
  745. SemIR::ConstType{SemIR::TypeId::TypeType, inner_type_id})};
  746. }
  747. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  748. -> ResolveResult {
  749. auto initial_work = work_stack_.size();
  750. auto const_id = GetLocalConstantId(inst.type_id);
  751. if (HasNewWork(initial_work)) {
  752. return ResolveResult::Retry();
  753. }
  754. auto inst_id = context_.AddInstInNoBlock(
  755. {AddImportIRInst(import_inst_id),
  756. SemIR::FieldDecl{context_.GetTypeIdForTypeConstant(const_id),
  757. GetLocalNameId(inst.name_id), inst.index}});
  758. return {context_.constant_values().Get(inst_id)};
  759. }
  760. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  761. auto initial_work = work_stack_.size();
  762. const auto& function = import_ir_.functions().Get(inst.function_id);
  763. auto return_type_const_id = SemIR::ConstantId::Invalid;
  764. if (function.return_type_id.is_valid()) {
  765. return_type_const_id = GetLocalConstantId(function.return_type_id);
  766. }
  767. auto enclosing_scope_id = GetLocalNameScopeId(function.enclosing_scope_id);
  768. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  769. GetLocalParamConstantIds(function.implicit_param_refs_id);
  770. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  771. GetLocalParamConstantIds(function.param_refs_id);
  772. if (HasNewWork(initial_work)) {
  773. return ResolveResult::Retry();
  774. }
  775. // Add the function declaration.
  776. auto function_decl =
  777. SemIR::FunctionDecl{SemIR::TypeId::Invalid, SemIR::FunctionId::Invalid,
  778. SemIR::InstBlockId::Empty};
  779. // Prefer pointing diagnostics towards a definition.
  780. auto import_ir_inst_id = AddImportIRInst(function.definition_id.is_valid()
  781. ? function.definition_id
  782. : function.decl_id);
  783. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  784. {import_ir_inst_id, function_decl});
  785. auto new_return_type_id =
  786. return_type_const_id.is_valid()
  787. ? context_.GetTypeIdForTypeConstant(return_type_const_id)
  788. : SemIR::TypeId::Invalid;
  789. auto new_return_storage = SemIR::InstId::Invalid;
  790. if (function.return_storage_id.is_valid()) {
  791. // Recreate the return slot from scratch.
  792. // TODO: Once we import function definitions, we'll need to make sure we
  793. // use the same return storage variable in the declaration and definition.
  794. new_return_storage = context_.AddInstInNoBlock(
  795. {AddImportIRInst(function.return_storage_id),
  796. SemIR::VarStorage{new_return_type_id, SemIR::NameId::ReturnSlot}});
  797. }
  798. function_decl.function_id = context_.functions().Add(
  799. {.name_id = GetLocalNameId(function.name_id),
  800. .enclosing_scope_id = enclosing_scope_id,
  801. .decl_id = function_decl_id,
  802. .implicit_param_refs_id = GetLocalParamRefsId(
  803. function.implicit_param_refs_id, implicit_param_const_ids),
  804. .param_refs_id =
  805. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  806. .return_type_id = new_return_type_id,
  807. .return_storage_id = new_return_storage,
  808. .is_extern = function.is_extern,
  809. .return_slot = function.return_slot,
  810. .builtin_kind = function.builtin_kind,
  811. .definition_id = function.definition_id.is_valid()
  812. ? function_decl_id
  813. : SemIR::InstId::Invalid});
  814. function_decl.type_id = context_.GetFunctionType(function_decl.function_id);
  815. // Write the function ID into the FunctionDecl.
  816. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  817. return {context_.constant_values().Get(function_decl_id)};
  818. }
  819. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  820. auto initial_work = work_stack_.size();
  821. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  822. auto fn_const_id = GetLocalConstantId(
  823. import_ir_.functions().Get(inst.function_id).decl_id);
  824. if (HasNewWork(initial_work)) {
  825. return ResolveResult::Retry();
  826. }
  827. auto fn_val = context_.insts().Get(fn_const_id.inst_id());
  828. CARBON_CHECK(context_.types().Is<SemIR::FunctionType>(fn_val.type_id()));
  829. return {context_.types().GetConstantId(fn_val.type_id())};
  830. }
  831. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  832. SemIR::InstId inst_id) -> ResolveResult {
  833. auto initial_work = work_stack_.size();
  834. // Return the constant for the instruction of the imported constant.
  835. auto constant_id = import_ir_.constant_values().Get(inst_id);
  836. if (!constant_id.is_valid()) {
  837. return {SemIR::ConstantId::Error};
  838. }
  839. if (!constant_id.is_constant()) {
  840. context_.TODO(inst_id,
  841. "Non-constant ImportRefLoaded (comes up with var)");
  842. return {SemIR::ConstantId::Error};
  843. }
  844. auto new_constant_id = GetLocalConstantId(constant_id.inst_id());
  845. if (HasNewWork(initial_work)) {
  846. return ResolveResult::Retry();
  847. }
  848. return {new_constant_id};
  849. }
  850. // Make a declaration of an interface. This is done as a separate step from
  851. // importing the interface definition in order to resolve cycles.
  852. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  853. -> SemIR::ConstantId {
  854. auto interface_decl = SemIR::InterfaceDecl{SemIR::TypeId::TypeType,
  855. SemIR::InterfaceId::Invalid,
  856. SemIR::InstBlockId::Empty};
  857. auto interface_decl_id = context_.AddPlaceholderInstInNoBlock(
  858. {AddImportIRInst(import_interface.decl_id), interface_decl});
  859. // Start with an incomplete interface.
  860. SemIR::Interface new_interface = {
  861. .name_id = GetLocalNameId(import_interface.name_id),
  862. // Set in the second pass once we've imported it.
  863. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  864. .decl_id = interface_decl_id,
  865. };
  866. // Write the interface ID into the InterfaceDecl.
  867. interface_decl.interface_id = context_.interfaces().Add(new_interface);
  868. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  869. // Set the constant value for the imported interface.
  870. return context_.constant_values().Get(interface_decl_id);
  871. }
  872. // Imports the definition for an interface that has been imported as a forward
  873. // declaration.
  874. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  875. SemIR::Interface& new_interface,
  876. SemIR::ConstantId self_param_id) -> void {
  877. new_interface.scope_id = context_.name_scopes().Add(
  878. new_interface.decl_id, SemIR::NameId::Invalid,
  879. new_interface.enclosing_scope_id);
  880. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  881. const auto& import_scope =
  882. import_ir_.name_scopes().Get(import_interface.scope_id);
  883. // Push a block so that we can add scoped instructions to it.
  884. context_.inst_block_stack().Push();
  885. AddNameScopeImportRefs(import_scope, new_scope);
  886. new_interface.associated_entities_id =
  887. AddAssociatedEntities(import_interface.associated_entities_id);
  888. new_interface.body_block_id = context_.inst_block_stack().Pop();
  889. new_interface.self_param_id = self_param_id.inst_id();
  890. CARBON_CHECK(import_scope.extended_scopes.empty())
  891. << "Interfaces don't currently have extended scopes to support.";
  892. }
  893. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  894. SemIR::ConstantId interface_const_id)
  895. -> ResolveResult {
  896. const auto& import_interface =
  897. import_ir_.interfaces().Get(inst.interface_id);
  898. // On the first pass, create a forward declaration of the interface.
  899. if (!interface_const_id.is_valid()) {
  900. interface_const_id = MakeInterfaceDecl(import_interface);
  901. }
  902. auto initial_work = work_stack_.size();
  903. auto enclosing_scope_id =
  904. GetLocalNameScopeId(import_interface.enclosing_scope_id);
  905. auto self_param_id = GetLocalConstantId(import_interface.self_param_id);
  906. if (HasNewWork(initial_work)) {
  907. return ResolveResult::Retry(interface_const_id);
  908. }
  909. auto& new_interface = context_.interfaces().Get(
  910. context_.insts()
  911. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  912. .interface_id);
  913. new_interface.enclosing_scope_id = enclosing_scope_id;
  914. if (import_interface.is_defined()) {
  915. AddInterfaceDefinition(import_interface, new_interface, self_param_id);
  916. }
  917. return {interface_const_id};
  918. }
  919. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  920. auto initial_work = work_stack_.size();
  921. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  922. auto interface_const_id = GetLocalConstantId(
  923. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  924. if (HasNewWork(initial_work)) {
  925. return ResolveResult::Retry();
  926. }
  927. return {interface_const_id};
  928. }
  929. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  930. auto initial_work = work_stack_.size();
  931. llvm::SmallVector<SemIR::InstId> elements;
  932. auto import_elements = import_ir_.inst_blocks().Get(inst.elements_id);
  933. elements.reserve(import_elements.size());
  934. for (auto import_elem_id : import_elements) {
  935. if (auto const_id = GetLocalConstantId(import_elem_id);
  936. const_id.is_valid()) {
  937. elements.push_back(const_id.inst_id());
  938. }
  939. }
  940. if (HasNewWork(initial_work)) {
  941. return ResolveResult::Retry();
  942. }
  943. CARBON_CHECK(elements.size() == import_elements.size())
  944. << "Failed to import an element without adding new work.";
  945. auto elements_id = context_.inst_blocks().Add(elements);
  946. return {TryEvalInst(
  947. context_, SemIR::InstId::Invalid,
  948. SemIR::InterfaceWitness{
  949. context_.GetBuiltinType(SemIR::BuiltinKind::WitnessType),
  950. elements_id})};
  951. }
  952. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  953. auto initial_work = work_stack_.size();
  954. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  955. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  956. if (HasNewWork(initial_work)) {
  957. return ResolveResult::Retry();
  958. }
  959. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  960. return {context_.types().GetConstantId(
  961. context_.GetPointerType(pointee_type_id))};
  962. }
  963. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  964. -> ResolveResult {
  965. // Collect all constants first, locating unresolved ones in a single pass.
  966. auto initial_work = work_stack_.size();
  967. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  968. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  969. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  970. field_const_ids.reserve(orig_fields.size());
  971. for (auto field_id : orig_fields) {
  972. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  973. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  974. }
  975. if (HasNewWork(initial_work)) {
  976. return ResolveResult::Retry();
  977. }
  978. // Prepare a vector of fields for GetStructType.
  979. // TODO: Should we have field constants so that we can deduplicate fields
  980. // without creating instructions here?
  981. llvm::SmallVector<SemIR::InstId> fields;
  982. fields.reserve(orig_fields.size());
  983. for (auto [field_id, field_const_id] :
  984. llvm::zip(orig_fields, field_const_ids)) {
  985. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  986. auto name_id = GetLocalNameId(field.name_id);
  987. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  988. fields.push_back(context_.AddInstInNoBlock(
  989. {AddImportIRInst(import_inst_id),
  990. SemIR::StructTypeField{.name_id = name_id,
  991. .field_type_id = field_type_id}}));
  992. }
  993. return {context_.types().GetConstantId(
  994. context_.GetStructType(context_.inst_blocks().Add(fields)))};
  995. }
  996. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  997. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  998. // Collect all constants first, locating unresolved ones in a single pass.
  999. auto initial_work = work_stack_.size();
  1000. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1001. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1002. elem_const_ids.reserve(orig_elem_type_ids.size());
  1003. for (auto elem_type_id : orig_elem_type_ids) {
  1004. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1005. }
  1006. if (HasNewWork(initial_work)) {
  1007. return ResolveResult::Retry();
  1008. }
  1009. // Prepare a vector of the tuple types for GetTupleType.
  1010. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1011. elem_type_ids.reserve(orig_elem_type_ids.size());
  1012. for (auto elem_const_id : elem_const_ids) {
  1013. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1014. }
  1015. return {
  1016. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids))};
  1017. }
  1018. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1019. auto initial_work = work_stack_.size();
  1020. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1021. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1022. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1023. if (HasNewWork(initial_work)) {
  1024. return ResolveResult::Retry();
  1025. }
  1026. return {context_.types().GetConstantId(context_.GetUnboundElementType(
  1027. context_.GetTypeIdForTypeConstant(class_const_id),
  1028. context_.GetTypeIdForTypeConstant(elem_const_id)))};
  1029. }
  1030. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1031. return context_.import_ir_constant_values()[import_ir_id_.index];
  1032. }
  1033. Context& context_;
  1034. SemIR::ImportIRId import_ir_id_;
  1035. const SemIR::File& import_ir_;
  1036. llvm::SmallVector<Work> work_stack_;
  1037. };
  1038. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1039. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1040. if (!inst) {
  1041. return;
  1042. }
  1043. auto import_ir_inst = context.import_ir_insts().Get(inst->import_ir_inst_id);
  1044. const SemIR::File& import_ir =
  1045. *context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1046. auto import_inst = import_ir.insts().Get(import_ir_inst.inst_id);
  1047. ImportRefResolver resolver(context, import_ir_inst.ir_id);
  1048. auto type_id = resolver.ResolveType(import_inst.type_id());
  1049. auto constant_id = resolver.Resolve(import_ir_inst.inst_id);
  1050. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1051. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1052. // TryEvalInst, which we want to avoid with ImportRefs.
  1053. context.sem_ir().insts().Set(
  1054. inst_id, SemIR::ImportRefLoaded{type_id, inst->import_ir_inst_id});
  1055. // Store the constant for both the ImportRefLoaded and imported instruction.
  1056. context.constant_values().Set(inst_id, constant_id);
  1057. }
  1058. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1059. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1060. const SemIR::File& import_ir,
  1061. SemIR::ImplId import_impl_id) -> void {
  1062. // Resolve the imported impl to a local impl ID.
  1063. ImportRefResolver resolver(context, import_ir_id);
  1064. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1065. auto self_id = resolver.ResolveType(import_impl.self_id);
  1066. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1067. // Import the definition if the impl is defined.
  1068. // TODO: Do we need to check for multiple definitions?
  1069. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1070. if (import_impl.is_defined()) {
  1071. // TODO: Create a scope for the `impl` if necessary.
  1072. // TODO: Consider importing the definition_id.
  1073. auto& impl = context.impls().Get(impl_id);
  1074. impl.witness_id = AddImportRef(
  1075. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id});
  1076. }
  1077. }
  1078. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1079. // and this file elsewhere.
  1080. auto ImportImpls(Context& context) -> void {
  1081. for (auto [import_index, import_ir] :
  1082. llvm::enumerate(context.import_irs().array_ref())) {
  1083. if (!import_ir.sem_ir) {
  1084. continue;
  1085. }
  1086. auto import_ir_id = SemIR::ImportIRId(import_index);
  1087. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1088. auto impl_id = SemIR::ImplId(impl_index);
  1089. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1090. }
  1091. }
  1092. }
  1093. } // namespace Carbon::Check