import_ref.cpp 43 KB

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