import_ref.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/import_ref.h"
  5. #include "common/check.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/parse/node_ids.h"
  11. #include "toolchain/sem_ir/constant.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/import_ir.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/inst_kind.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Adds the ImportIR, excluding the update to the check_ir_map.
  20. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  21. -> SemIR::ImportIRId {
  22. context.import_ir_constant_values().push_back(
  23. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  24. return context.import_irs().Add(import_ir);
  25. }
  26. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  27. auto ir_id = SemIR::ImportIRId::Invalid;
  28. if (import_ir.sem_ir != nullptr) {
  29. ir_id = AddImportIR(context, import_ir);
  30. } else {
  31. // We don't have a check_ir_id, so add without touching check_ir_map.
  32. ir_id = InternalAddImportIR(context, import_ir);
  33. }
  34. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl,
  35. "ApiForImpl must be the first IR");
  36. }
  37. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  38. -> SemIR::ImportIRId {
  39. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  40. if (!ir_id.is_valid()) {
  41. // Note this updates check_ir_map.
  42. ir_id = InternalAddImportIR(context, import_ir);
  43. } else if (import_ir.is_export) {
  44. // We're processing an `export import`. In case the IR was indirectly added
  45. // as a non-export, mark it as an export.
  46. context.import_irs().Get(ir_id).is_export = true;
  47. }
  48. return ir_id;
  49. }
  50. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  51. SemIR::EntityNameId entity_name_id) -> SemIR::InstId {
  52. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  53. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  54. .entity_name_id = entity_name_id};
  55. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  56. context.MakeImportedLocAndInst(import_ir_inst_id, inst));
  57. // ImportRefs have a dedicated block because this may be called during
  58. // processing where the instruction shouldn't be inserted in the current inst
  59. // block.
  60. context.import_ref_ids().push_back(import_ref_id);
  61. return import_ref_id;
  62. }
  63. auto GetCanonicalImportIRInst(Context& context, const SemIR::File* cursor_ir,
  64. SemIR::InstId cursor_inst_id)
  65. -> SemIR::ImportIRInst {
  66. while (true) {
  67. auto inst = cursor_ir->insts().Get(cursor_inst_id);
  68. CARBON_KIND_SWITCH(inst) {
  69. case CARBON_KIND(SemIR::ExportDecl bind_export): {
  70. cursor_inst_id = bind_export.value_id;
  71. continue;
  72. }
  73. case SemIR::ImportRefLoaded::Kind:
  74. case SemIR::ImportRefUnloaded::Kind: {
  75. auto import_ref = inst.As<SemIR::AnyImportRef>();
  76. auto import_ir_inst =
  77. cursor_ir->import_ir_insts().Get(import_ref.import_ir_inst_id);
  78. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  79. cursor_inst_id = import_ir_inst.inst_id;
  80. continue;
  81. }
  82. default: {
  83. auto ir_id = SemIR::ImportIRId::Invalid;
  84. if (cursor_ir != &context.sem_ir()) {
  85. // This uses AddImportIR in case it was indirectly found, which can
  86. // happen with two or more steps of exports.
  87. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  88. .is_export = false,
  89. .sem_ir = cursor_ir});
  90. }
  91. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  92. }
  93. }
  94. }
  95. }
  96. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  97. SemIR::ImportIRInst prev_import_ir_inst,
  98. SemIR::ImportIRId new_ir_id,
  99. const SemIR::File* new_import_ir,
  100. SemIR::InstId new_inst_id) -> void {
  101. auto new_import_ir_inst =
  102. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  103. if (new_import_ir_inst == prev_import_ir_inst) {
  104. return;
  105. }
  106. auto conflict_id =
  107. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id},
  108. SemIR::EntityNameId::Invalid);
  109. context.DiagnoseDuplicateName(conflict_id, prev_id);
  110. }
  111. // Returns an instruction that has the specified constant value.
  112. static auto GetInstWithConstantValue(const SemIR::File& file,
  113. SemIR::ConstantId const_id)
  114. -> SemIR::InstId {
  115. if (!const_id.is_valid()) {
  116. return SemIR::InstId::Invalid;
  117. }
  118. // For template constants, the corresponding instruction has the desired
  119. // constant value.
  120. if (!const_id.is_symbolic()) {
  121. return file.constant_values().GetInstId(const_id);
  122. }
  123. // For abstract symbolic constants, the corresponding instruction has the
  124. // desired constant value.
  125. const auto& symbolic_const =
  126. file.constant_values().GetSymbolicConstant(const_id);
  127. if (!symbolic_const.generic_id.is_valid()) {
  128. return file.constant_values().GetInstId(const_id);
  129. }
  130. // For a symbolic constant in a generic, pick the corresponding instruction
  131. // out of the eval block for the generic.
  132. const auto& generic = file.generics().Get(symbolic_const.generic_id);
  133. auto block = generic.GetEvalBlock(symbolic_const.index.region());
  134. return file.inst_blocks().Get(block)[symbolic_const.index.index()];
  135. }
  136. // Resolves an instruction from an imported IR into a constant referring to the
  137. // current IR.
  138. //
  139. // Calling Resolve on an instruction operates in an iterative manner, tracking
  140. // Work items on work_stack_. At a high level, the loop is:
  141. //
  142. // 1. If a constant value is already known for the work item and was not set by
  143. // this work item, it's considered resolved.
  144. // - The constant check avoids performance costs of deduplication on add.
  145. // - If we've processed this work item before, then we now process it again.
  146. // It didn't complete last time, even though we have a constant value
  147. // already.
  148. //
  149. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  150. // in three phases. The first and second phases can add work to the worklist
  151. // and end in a retry, in which case those phases will be rerun once the
  152. // added work is done. The rerun cannot also end in a retry, so this results
  153. // in at most three calls, but in practice one or two calls is almost always
  154. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  155. // it's important to only perform expensive work once, even when the same
  156. // phase is rerun.
  157. //
  158. // - First phase:
  159. // - Gather all input constants necessary to form the constant value of the
  160. // instruction. Gathering constants directly adds unresolved values to
  161. // work_stack_.
  162. // - If HasNewWork() reports that any work was added, then return Retry():
  163. // this instruction needs another call to complete. Gather the
  164. // now-resolved constants and continue to the next step once the retry
  165. // happens.
  166. //
  167. // - Second phase:
  168. // - Build the constant value of the instruction.
  169. // - Gather all input constants necessary to finish importing the
  170. // instruction. This is only necessary for instructions like classes that
  171. // can be forward-declared. For these instructions, we first import the
  172. // constant value and then later import the rest of the declaration in
  173. // order to break cycles.
  174. // - If HasNewWork() reports that any work was added, then return
  175. // Retry(constant_value): this instruction needs another call to
  176. // complete. Gather the now-resolved constants and continue to the next
  177. // step once the retry happens.
  178. //
  179. // - Third phase:
  180. // - After the second phase, the constant value for the instruction is
  181. // already set, and will be passed back into TryResolve*Inst on retry. It
  182. // should not be created again.
  183. // - Fill in any remaining information to complete the import of the
  184. // instruction. For example, when importing a class declaration, build
  185. // the class scope and information about the definition.
  186. // - Return ResolveAs/ResolveAsConstant to finish the resolution process.
  187. // This will cause the Resolve loop to set a constant value if we didn't
  188. // retry at the end of the second phase.
  189. //
  190. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  191. // remain, and may no longer be at the top of the stack; update the state of
  192. // the work item to track what work still needs to be done.
  193. //
  194. // The same instruction can be enqueued for resolution multiple times. However,
  195. // we will only reach the second phase once: once a constant value is set, only
  196. // the resolution step that set it will retry.
  197. //
  198. // TODO: Fix class `extern` handling and merging, rewrite tests.
  199. // - check/testdata/class/cross_package_import.carbon
  200. // - check/testdata/class/extern.carbon
  201. // TODO: Fix function `extern` handling and merging, rewrite tests.
  202. // - check/testdata/function/declaration/import.carbon
  203. // - check/testdata/packages/cross_package_import.carbon
  204. class ImportRefResolver {
  205. public:
  206. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  207. : context_(context),
  208. import_ir_id_(import_ir_id),
  209. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  210. // Iteratively resolves an imported instruction's inner references until a
  211. // constant ID referencing the current IR is produced. See the class comment
  212. // for more details.
  213. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId {
  214. work_stack_.push_back({.inst_id = inst_id});
  215. while (!work_stack_.empty()) {
  216. auto work = work_stack_.back();
  217. CARBON_CHECK(work.inst_id.is_valid());
  218. // Step 1: check for a constant value.
  219. auto existing = FindResolvedConstId(work.inst_id);
  220. if (existing.const_id.is_valid() && !work.retry_with_constant_value) {
  221. work_stack_.pop_back();
  222. continue;
  223. }
  224. // Step 2: resolve the instruction.
  225. initial_work_ = work_stack_.size();
  226. auto [new_const_id, retry] =
  227. TryResolveInst(work.inst_id, existing.const_id);
  228. CARBON_CHECK(
  229. !existing.const_id.is_valid() || existing.const_id == new_const_id,
  230. "Constant value changed in third phase.");
  231. if (!existing.const_id.is_valid()) {
  232. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  233. }
  234. // Step 3: pop or retry.
  235. if (retry) {
  236. work_stack_[initial_work_ - 1].retry_with_constant_value =
  237. new_const_id.is_valid();
  238. } else {
  239. work_stack_.pop_back();
  240. }
  241. }
  242. auto constant_id = import_ir_constant_values().Get(inst_id);
  243. CARBON_CHECK(constant_id.is_valid());
  244. return constant_id;
  245. }
  246. // Performs resolution for one instruction and then performs all work we
  247. // deferred.
  248. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  249. auto const_id = ResolveOneInst(inst_id);
  250. PerformPendingWork();
  251. return const_id;
  252. }
  253. // Wraps constant evaluation with logic to handle constants.
  254. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  255. return Resolve(GetInstWithConstantValue(import_ir_, import_const_id));
  256. }
  257. // Wraps constant evaluation with logic to handle types.
  258. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  259. if (!import_type_id.is_valid()) {
  260. return import_type_id;
  261. }
  262. auto import_type_const_id =
  263. import_ir_.types().GetConstantId(import_type_id);
  264. CARBON_CHECK(import_type_const_id.is_valid());
  265. if (auto import_type_inst_id =
  266. import_ir_.constant_values().GetInstId(import_type_const_id);
  267. import_type_inst_id.is_builtin()) {
  268. // Builtins don't require constant resolution; we can use them directly.
  269. return context_.GetBuiltinType(import_type_inst_id.builtin_inst_kind());
  270. } else {
  271. return context_.GetTypeIdForTypeConstant(
  272. ResolveConstant(import_type_id.AsConstantId()));
  273. }
  274. }
  275. private:
  276. // The result of attempting to resolve an imported instruction to a constant.
  277. struct ResolveResult {
  278. // The new constant value, if known.
  279. SemIR::ConstantId const_id;
  280. // Whether resolution has been attempted once and needs to be retried.
  281. bool retry = false;
  282. };
  283. // A step in work_stack_.
  284. struct Work {
  285. // The instruction to work on.
  286. SemIR::InstId inst_id;
  287. // Whether this work item set the constant value for the instruction and
  288. // requested a retry.
  289. bool retry_with_constant_value = false;
  290. };
  291. // The constant found by FindResolvedConstId.
  292. struct ResolvedConstId {
  293. // The constant for the instruction. Invalid if not yet resolved.
  294. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  295. // Instructions which are indirect but equivalent to the current instruction
  296. // being resolved, and should have their constant set to the same. Empty
  297. // when const_id is valid.
  298. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  299. };
  300. // Local information associated with an imported parameter.
  301. struct ParamData {
  302. SemIR::ConstantId type_const_id;
  303. SemIR::ConstantId bind_const_id;
  304. };
  305. // Local information associated with an imported generic.
  306. struct GenericData {
  307. llvm::SmallVector<SemIR::InstId> bindings;
  308. };
  309. // Local information associated with an imported specific.
  310. struct SpecificData {
  311. SemIR::ConstantId generic_const_id;
  312. llvm::SmallVector<SemIR::InstId> args;
  313. };
  314. // A generic that we have partially imported.
  315. struct PendingGeneric {
  316. SemIR::GenericId import_id;
  317. SemIR::GenericId local_id;
  318. };
  319. // A specific that we have partially imported.
  320. struct PendingSpecific {
  321. SemIR::SpecificId import_id;
  322. SemIR::SpecificId local_id;
  323. };
  324. // Looks to see if an instruction has been resolved. If a constant is only
  325. // found indirectly, sets the constant for any indirect steps that don't
  326. // already have the constant. If a constant isn't found, returns the indirect
  327. // instructions so that they can have the resolved constant assigned later.
  328. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  329. ResolvedConstId result;
  330. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  331. existing_const_id.is_valid()) {
  332. result.const_id = existing_const_id;
  333. return result;
  334. }
  335. const auto* cursor_ir = &import_ir_;
  336. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  337. auto cursor_inst_id = inst_id;
  338. while (true) {
  339. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  340. if (!loc_id.is_import_ir_inst_id()) {
  341. return result;
  342. }
  343. auto ir_inst =
  344. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  345. const auto* prev_ir = cursor_ir;
  346. auto prev_inst_id = cursor_inst_id;
  347. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  348. cursor_ir_id = context_.GetImportIRId(*cursor_ir);
  349. if (!cursor_ir_id.is_valid()) {
  350. // TODO: Should we figure out a location to assign here?
  351. cursor_ir_id = AddImportIR(context_, {.decl_id = SemIR::InstId::Invalid,
  352. .is_export = false,
  353. .sem_ir = cursor_ir});
  354. }
  355. cursor_inst_id = ir_inst.inst_id;
  356. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id,
  357. "{0}", cursor_ir->insts().Get(cursor_inst_id));
  358. if (auto const_id =
  359. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  360. cursor_inst_id);
  361. const_id.is_valid()) {
  362. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  363. result.const_id = const_id;
  364. result.indirect_insts.clear();
  365. return result;
  366. } else {
  367. result.indirect_insts.push_back(
  368. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  369. }
  370. }
  371. }
  372. // Sets a resolved constant into the current and indirect instructions.
  373. auto SetResolvedConstId(SemIR::InstId inst_id,
  374. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  375. SemIR::ConstantId const_id) -> void {
  376. import_ir_constant_values().Set(inst_id, const_id);
  377. for (auto indirect_inst : indirect_insts) {
  378. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  379. indirect_inst.inst_id, const_id);
  380. }
  381. }
  382. // Returns true if new unresolved constants were found as part of this
  383. // `Resolve` step.
  384. auto HasNewWork() -> bool {
  385. CARBON_CHECK(initial_work_ <= work_stack_.size(),
  386. "Work shouldn't decrease");
  387. return initial_work_ < work_stack_.size();
  388. }
  389. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  390. return context_.import_ir_insts().Add(
  391. {.ir_id = import_ir_id_, .inst_id = inst_id});
  392. }
  393. // Returns the ConstantId for an InstId. Adds unresolved constants to
  394. // work_stack_.
  395. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  396. auto const_id = import_ir_constant_values().Get(inst_id);
  397. if (!const_id.is_valid()) {
  398. work_stack_.push_back({.inst_id = inst_id});
  399. }
  400. return const_id;
  401. }
  402. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  403. // constants to work_stack_.
  404. auto GetLocalConstantId(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  405. return GetLocalConstantId(GetInstWithConstantValue(import_ir_, const_id));
  406. }
  407. // Returns the local constant InstId for an imported InstId.
  408. auto GetLocalConstantInstId(SemIR::InstId inst_id) -> SemIR::InstId {
  409. auto const_id = import_ir_constant_values().Get(inst_id);
  410. if (!const_id.is_valid()) {
  411. work_stack_.push_back({.inst_id = inst_id});
  412. return SemIR::InstId::Invalid;
  413. }
  414. return context_.constant_values().GetInstId(const_id);
  415. }
  416. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  417. // work_stack_.
  418. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  419. return GetLocalConstantId(import_ir_.types().GetConstantId(type_id));
  420. }
  421. // Gets the local constant values corresponding to an imported inst block.
  422. auto GetLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  423. -> llvm::SmallVector<SemIR::InstId> {
  424. llvm::SmallVector<SemIR::InstId> inst_ids;
  425. if (!import_block_id.is_valid() ||
  426. import_block_id == SemIR::InstBlockId::Empty) {
  427. return inst_ids;
  428. }
  429. // Import all the values in the block.
  430. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  431. inst_ids.reserve(import_block.size());
  432. for (auto import_inst_id : import_block) {
  433. auto const_id = GetLocalConstantId(import_inst_id);
  434. inst_ids.push_back(context_.constant_values().GetInstIdIfValid(const_id));
  435. }
  436. return inst_ids;
  437. }
  438. // Gets a local instruction block ID corresponding to an imported inst block
  439. // whose contents were already imported, for example by
  440. // GetLocalInstBlockContents.
  441. auto GetLocalInstBlockId(SemIR::InstBlockId import_block_id,
  442. llvm::ArrayRef<SemIR::InstId> contents)
  443. -> SemIR::InstBlockId {
  444. if (!import_block_id.is_valid()) {
  445. return SemIR::InstBlockId::Invalid;
  446. }
  447. return context_.inst_blocks().Add(contents);
  448. }
  449. // Gets a local canonical instruction block ID corresponding to an imported
  450. // inst block whose contents were already imported, for example by
  451. // GetLocalInstBlockContents.
  452. auto GetLocalCanonicalInstBlockId(SemIR::InstBlockId import_block_id,
  453. llvm::ArrayRef<SemIR::InstId> contents)
  454. -> SemIR::InstBlockId {
  455. if (!import_block_id.is_valid()) {
  456. return SemIR::InstBlockId::Invalid;
  457. }
  458. return context_.inst_blocks().AddCanonical(contents);
  459. }
  460. // Gets an incomplete local version of an imported generic. Most fields are
  461. // set in the third phase.
  462. auto MakeIncompleteGeneric(SemIR::InstId decl_id, SemIR::GenericId generic_id)
  463. -> SemIR::GenericId {
  464. if (!generic_id.is_valid()) {
  465. return SemIR::GenericId::Invalid;
  466. }
  467. return context_.generics().Add(
  468. {.decl_id = decl_id,
  469. .bindings_id = SemIR::InstBlockId::Invalid,
  470. .self_specific_id = SemIR::SpecificId::Invalid});
  471. }
  472. // Gets a local version of the data associated with a generic.
  473. auto GetLocalGenericData(SemIR::GenericId generic_id) -> GenericData {
  474. if (!generic_id.is_valid()) {
  475. return GenericData();
  476. }
  477. const auto& generic = import_ir_.generics().Get(generic_id);
  478. return {.bindings = GetLocalInstBlockContents(generic.bindings_id)};
  479. }
  480. // Adds the given local generic data to the given generic.
  481. auto SetGenericData(SemIR::GenericId import_generic_id,
  482. SemIR::GenericId new_generic_id,
  483. const GenericData& generic_data) -> void {
  484. if (!import_generic_id.is_valid()) {
  485. return;
  486. }
  487. const auto& import_generic = import_ir_.generics().Get(import_generic_id);
  488. auto& new_generic = context_.generics().Get(new_generic_id);
  489. new_generic.bindings_id = GetLocalCanonicalInstBlockId(
  490. import_generic.bindings_id, generic_data.bindings);
  491. // Fill in the remaining information in FinishPendingGeneric.
  492. pending_generics_.push_back(
  493. {.import_id = import_generic_id, .local_id = new_generic_id});
  494. }
  495. // Gets a local constant value corresponding to an imported generic ID. May
  496. // add work to the work stack and return `Invalid`.
  497. auto GetLocalConstantId(SemIR::GenericId generic_id) -> SemIR::ConstantId {
  498. if (!generic_id.is_valid()) {
  499. return SemIR::ConstantId::Invalid;
  500. }
  501. return GetLocalConstantId(
  502. import_ir_.insts()
  503. .Get(import_ir_.generics().Get(generic_id).decl_id)
  504. .type_id());
  505. }
  506. // Gets a local generic ID given the corresponding local constant ID returned
  507. // by GetLocalConstantId for the imported generic. Does not add any new work.
  508. auto GetLocalGenericId(SemIR::ConstantId local_const_id) -> SemIR::GenericId {
  509. if (!local_const_id.is_valid()) {
  510. return SemIR::GenericId::Invalid;
  511. }
  512. auto type = context_.insts().Get(
  513. context_.constant_values().GetInstId(local_const_id));
  514. CARBON_KIND_SWITCH(type) {
  515. case CARBON_KIND(SemIR::FunctionType fn_type): {
  516. return context_.functions().Get(fn_type.function_id).generic_id;
  517. }
  518. case CARBON_KIND(SemIR::GenericClassType class_type): {
  519. return context_.classes().Get(class_type.class_id).generic_id;
  520. }
  521. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  522. return context_.interfaces()
  523. .Get(interface_type.interface_id)
  524. .generic_id;
  525. }
  526. default: {
  527. CARBON_FATAL("Unexpected type for generic declaration: {0}", type);
  528. }
  529. }
  530. }
  531. // Gets local information about an imported specific.
  532. auto GetLocalSpecificData(SemIR::SpecificId specific_id) -> SpecificData {
  533. if (!specific_id.is_valid()) {
  534. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  535. }
  536. const auto& specific = import_ir_.specifics().Get(specific_id);
  537. return {
  538. .generic_const_id = GetLocalConstantId(specific.generic_id),
  539. .args = GetLocalInstBlockContents(specific.args_id),
  540. };
  541. }
  542. // Gets a local specific whose data was already imported by
  543. // GetLocalSpecificData. Does not add any new work.
  544. auto GetOrAddLocalSpecific(SemIR::SpecificId import_specific_id,
  545. const SpecificData& data) -> SemIR::SpecificId {
  546. if (!import_specific_id.is_valid()) {
  547. return SemIR::SpecificId::Invalid;
  548. }
  549. // Form a corresponding local specific ID.
  550. const auto& import_specific =
  551. import_ir_.specifics().Get(import_specific_id);
  552. auto generic_id = GetLocalGenericId(data.generic_const_id);
  553. auto args_id =
  554. GetLocalCanonicalInstBlockId(import_specific.args_id, data.args);
  555. // Get the specific.
  556. auto specific_id = context_.specifics().GetOrAdd(generic_id, args_id);
  557. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  558. auto& specific = context_.specifics().Get(specific_id);
  559. if (!specific.decl_block_id.is_valid() ||
  560. (import_specific.definition_block_id.is_valid() &&
  561. !specific.definition_block_id.is_valid())) {
  562. pending_specifics_.push_back(
  563. {.import_id = import_specific_id, .local_id = specific_id});
  564. }
  565. return specific_id;
  566. }
  567. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  568. // to work_stack_.
  569. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  570. -> llvm::SmallVector<ParamData> {
  571. llvm::SmallVector<ParamData> param_data;
  572. if (!param_refs_id.is_valid() ||
  573. param_refs_id == SemIR::InstBlockId::Empty) {
  574. return param_data;
  575. }
  576. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  577. param_data.reserve(param_refs.size());
  578. for (auto inst_id : param_refs) {
  579. auto type_const_id =
  580. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id());
  581. // If the parameter is a symbolic binding, build the BindSymbolicName
  582. // constant.
  583. auto bind_id = inst_id;
  584. auto bind_inst = import_ir_.insts().Get(bind_id);
  585. if (auto addr = bind_inst.TryAs<SemIR::AddrPattern>()) {
  586. bind_id = addr->inner_id;
  587. bind_inst = import_ir_.insts().Get(bind_id);
  588. }
  589. auto bind_const_id = bind_inst.Is<SemIR::BindSymbolicName>()
  590. ? GetLocalConstantId(bind_id)
  591. : SemIR::ConstantId::Invalid;
  592. param_data.push_back(
  593. {.type_const_id = type_const_id, .bind_const_id = bind_const_id});
  594. }
  595. return param_data;
  596. }
  597. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  598. // a version of param_refs_id localized to the current IR.
  599. auto GetLocalParamRefsId(SemIR::InstBlockId param_refs_id,
  600. const llvm::SmallVector<ParamData>& params_data)
  601. -> SemIR::InstBlockId {
  602. if (!param_refs_id.is_valid() ||
  603. param_refs_id == SemIR::InstBlockId::Empty) {
  604. return param_refs_id;
  605. }
  606. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  607. llvm::SmallVector<SemIR::InstId> new_param_refs;
  608. for (auto [ref_id, param_data] : llvm::zip(param_refs, params_data)) {
  609. // Figure out the param structure. This echoes
  610. // Function::GetParamFromParamRefId.
  611. // TODO: Consider a different parameter handling to simplify import logic.
  612. auto inst = import_ir_.insts().Get(ref_id);
  613. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  614. auto bind_id = ref_id;
  615. auto param_id = ref_id;
  616. if (addr_inst) {
  617. bind_id = addr_inst->inner_id;
  618. param_id = bind_id;
  619. inst = import_ir_.insts().Get(bind_id);
  620. }
  621. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  622. if (bind_inst) {
  623. param_id = bind_inst->value_id;
  624. inst = import_ir_.insts().Get(param_id);
  625. }
  626. auto param_inst = inst.As<SemIR::Param>();
  627. // Rebuild the param instruction.
  628. auto name_id = GetLocalNameId(param_inst.name_id);
  629. auto type_id =
  630. context_.GetTypeIdForTypeConstant(param_data.type_const_id);
  631. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  632. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  633. if (bind_inst) {
  634. switch (bind_inst->kind) {
  635. case SemIR::BindName::Kind: {
  636. auto entity_name_id = context_.entity_names().Add(
  637. {.name_id = name_id,
  638. .parent_scope_id = SemIR::NameScopeId::Invalid,
  639. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  640. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  641. AddImportIRInst(bind_id), {.type_id = type_id,
  642. .entity_name_id = entity_name_id,
  643. .value_id = new_param_id});
  644. break;
  645. }
  646. case SemIR::BindSymbolicName::Kind: {
  647. // We already imported a constant value for this symbolic binding.
  648. // We can reuse most of it, but update the value to point to our
  649. // specific parameter, and preserve the constant value.
  650. auto new_bind_inst =
  651. context_.insts().GetAs<SemIR::BindSymbolicName>(
  652. context_.constant_values().GetInstId(
  653. param_data.bind_const_id));
  654. new_bind_inst.value_id = new_param_id;
  655. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  656. new_bind_inst);
  657. context_.constant_values().Set(new_param_id,
  658. param_data.bind_const_id);
  659. break;
  660. }
  661. default: {
  662. CARBON_FATAL("Unexpected kind: {0}", bind_inst->kind);
  663. }
  664. }
  665. }
  666. if (addr_inst) {
  667. new_param_id = context_.AddInstInNoBlock(
  668. context_.MakeImportedLocAndInst<SemIR::AddrPattern>(
  669. AddImportIRInst(ref_id),
  670. {.type_id = type_id, .inner_id = new_param_id}));
  671. }
  672. new_param_refs.push_back(new_param_id);
  673. }
  674. return context_.inst_blocks().Add(new_param_refs);
  675. }
  676. // Translates a NameId from the import IR to a local NameId.
  677. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  678. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  679. return SemIR::NameId::ForIdentifier(
  680. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  681. }
  682. return import_name_id;
  683. }
  684. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  685. // unresolved constants to the work stack.
  686. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  687. -> SemIR::NameScopeId {
  688. // Get the instruction that created the scope.
  689. auto [inst_id, inst] =
  690. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  691. if (!inst) {
  692. // Map scopes that aren't associated with an instruction to invalid
  693. // scopes. For now, such scopes aren't used, and we don't have a good way
  694. // to remap them.
  695. return SemIR::NameScopeId::Invalid;
  696. }
  697. // Get the constant value for the scope.
  698. auto const_id = SemIR::ConstantId::Invalid;
  699. CARBON_KIND_SWITCH(*inst) {
  700. case SemIR::ImplDecl::Kind:
  701. // TODO: Import the scope for an `impl` definition.
  702. return SemIR::NameScopeId::Invalid;
  703. case SemIR::Namespace::Kind:
  704. // If the namespace has already been imported, we can use its constant.
  705. // However, if it hasn't, we use Invalid instead of adding it to the
  706. // work stack. That's expected to be okay when resolving references.
  707. const_id = import_ir_constant_values().Get(inst_id);
  708. break;
  709. default:
  710. const_id = GetLocalConstantId(inst_id);
  711. }
  712. if (!const_id.is_valid()) {
  713. return SemIR::NameScopeId::Invalid;
  714. }
  715. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  716. auto name_scope_inst = context_.insts().Get(const_inst_id);
  717. CARBON_KIND_SWITCH(name_scope_inst) {
  718. case CARBON_KIND(SemIR::Namespace inst): {
  719. return inst.name_scope_id;
  720. }
  721. case CARBON_KIND(SemIR::ClassType inst): {
  722. return context_.classes().Get(inst.class_id).scope_id;
  723. }
  724. case CARBON_KIND(SemIR::InterfaceType inst): {
  725. return context_.interfaces().Get(inst.interface_id).scope_id;
  726. }
  727. case SemIR::StructValue::Kind: {
  728. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  729. CARBON_KIND_SWITCH(type_inst) {
  730. case CARBON_KIND(SemIR::GenericClassType inst): {
  731. return context_.classes().Get(inst.class_id).scope_id;
  732. }
  733. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  734. return context_.interfaces().Get(inst.interface_id).scope_id;
  735. }
  736. default: {
  737. break;
  738. }
  739. }
  740. break;
  741. }
  742. default: {
  743. if (const_inst_id == SemIR::InstId::BuiltinError) {
  744. return SemIR::NameScopeId::Invalid;
  745. }
  746. break;
  747. }
  748. }
  749. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  750. name_scope_inst);
  751. }
  752. // Given an imported entity base, returns an incomplete, local version of it.
  753. //
  754. // Most fields are set in the third phase once they're imported. Import enough
  755. // of the parameter lists that we know whether this interface is a generic
  756. // interface and can build the right constant value for it.
  757. //
  758. // TODO: Support extern.
  759. // TODO: Add a better way to represent a generic prior to importing the
  760. // parameters.
  761. auto GetIncompleteLocalEntityBase(
  762. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  763. -> SemIR::EntityWithParamsBase {
  764. // Translate the extern_library_id if present.
  765. auto extern_library_id = SemIR::LibraryNameId::Invalid;
  766. if (import_base.extern_library_id.is_valid()) {
  767. if (import_base.extern_library_id.index >= 0) {
  768. auto val = import_ir_.string_literal_values().Get(
  769. import_base.extern_library_id.AsStringLiteralValueId());
  770. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  771. context_.string_literal_values().Add(val));
  772. } else {
  773. extern_library_id = import_base.extern_library_id;
  774. }
  775. }
  776. return {
  777. .name_id = GetLocalNameId(import_base.name_id),
  778. .parent_scope_id = SemIR::NameScopeId::Invalid,
  779. .generic_id = MakeIncompleteGeneric(decl_id, import_base.generic_id),
  780. .first_param_node_id = Parse::NodeId::Invalid,
  781. .last_param_node_id = Parse::NodeId::Invalid,
  782. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  783. ? SemIR::InstBlockId::Empty
  784. : SemIR::InstBlockId::Invalid,
  785. .param_refs_id = import_base.param_refs_id.is_valid()
  786. ? SemIR::InstBlockId::Empty
  787. : SemIR::InstBlockId::Invalid,
  788. .is_extern = import_base.is_extern,
  789. .extern_library_id = extern_library_id,
  790. .non_owning_decl_id = import_base.non_owning_decl_id.is_valid()
  791. ? decl_id
  792. : SemIR::InstId::Invalid,
  793. .first_owning_decl_id = import_base.first_owning_decl_id.is_valid()
  794. ? decl_id
  795. : SemIR::InstId::Invalid,
  796. };
  797. }
  798. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  799. // lookup.
  800. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  801. SemIR::NameScope& new_scope) -> void {
  802. for (auto entry : import_scope.names) {
  803. auto ref_id = AddImportRef(
  804. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  805. SemIR::EntityNameId::Invalid);
  806. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  807. .inst_id = ref_id,
  808. .access_kind = entry.access_kind});
  809. }
  810. }
  811. // Given a block ID for a list of associated entities of a witness, returns a
  812. // version localized to the current IR.
  813. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  814. -> SemIR::InstBlockId {
  815. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  816. return SemIR::InstBlockId::Empty;
  817. }
  818. auto associated_entities =
  819. import_ir_.inst_blocks().Get(associated_entities_id);
  820. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  821. new_associated_entities.reserve(associated_entities.size());
  822. for (auto inst_id : associated_entities) {
  823. new_associated_entities.push_back(
  824. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  825. SemIR::EntityNameId::Invalid));
  826. }
  827. return context_.inst_blocks().Add(new_associated_entities);
  828. }
  829. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  830. // more has been added to the stack. A similar API is followed for all
  831. // following TryResolveTypedInst helper functions.
  832. //
  833. // `const_id` is Invalid unless we've tried to resolve this instruction
  834. // before, in which case it's the previous result.
  835. //
  836. // TODO: Error is returned when support is missing, but that should go away.
  837. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  838. -> ResolveResult {
  839. auto inst_const_id = import_ir_.constant_values().Get(inst_id);
  840. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  841. return TryResolveInstCanonical(inst_id, const_id);
  842. }
  843. // Try to import the generic. This might add new work.
  844. const auto& symbolic_const =
  845. import_ir_.constant_values().GetSymbolicConstant(inst_const_id);
  846. auto generic_const_id = GetLocalConstantId(symbolic_const.generic_id);
  847. auto inner_const_id = SemIR::ConstantId::Invalid;
  848. if (const_id.is_valid()) {
  849. // For the third phase, extract the constant value that
  850. // TryResolveInstCanonical produced previously.
  851. inner_const_id = context_.constant_values().Get(
  852. context_.constant_values().GetSymbolicConstant(const_id).inst_id);
  853. }
  854. // Import the constant and rebuild the symbolic constant data.
  855. auto result = TryResolveInstCanonical(inst_id, inner_const_id);
  856. if (!result.const_id.is_valid()) {
  857. // First phase: TryResolveInstCanoncial needs a retry.
  858. return result;
  859. }
  860. if (!const_id.is_valid()) {
  861. // Second phase: we have created an abstract constant. Create a
  862. // corresponding generic constant.
  863. if (symbolic_const.generic_id.is_valid()) {
  864. result.const_id = context_.constant_values().AddSymbolicConstant(
  865. {.inst_id = context_.constant_values().GetInstId(result.const_id),
  866. .generic_id = GetLocalGenericId(generic_const_id),
  867. .index = symbolic_const.index});
  868. }
  869. } else {
  870. // Third phase: perform a consistency check and produce the constant we
  871. // created in the second phase.
  872. CARBON_CHECK(result.const_id == inner_const_id,
  873. "Constant value changed in third phase.");
  874. result.const_id = const_id;
  875. }
  876. return result;
  877. }
  878. // Tries to resolve the InstId, returning a canonical constant when ready, or
  879. // Invalid if more has been added to the stack. This is the same as
  880. // TryResolveInst, except that it may resolve symbolic constants as canonical
  881. // constants instead of as constants associated with a particular generic.
  882. auto TryResolveInstCanonical(SemIR::InstId inst_id,
  883. SemIR::ConstantId const_id) -> ResolveResult {
  884. if (inst_id.is_builtin()) {
  885. CARBON_CHECK(!const_id.is_valid());
  886. // Constants for builtins can be directly copied.
  887. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  888. }
  889. auto untyped_inst = import_ir_.insts().Get(inst_id);
  890. CARBON_KIND_SWITCH(untyped_inst) {
  891. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  892. return TryResolveTypedInst(inst);
  893. }
  894. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  895. return TryResolveTypedInst(inst);
  896. }
  897. case CARBON_KIND(SemIR::BaseDecl inst): {
  898. return TryResolveTypedInst(inst, inst_id);
  899. }
  900. case CARBON_KIND(SemIR::BindAlias inst): {
  901. return TryResolveTypedInst(inst);
  902. }
  903. case SemIR::BindName::Kind: {
  904. // TODO: Should we be resolving BindNames at all?
  905. return ResolveAsConstant(SemIR::ConstantId::NotConstant);
  906. }
  907. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  908. return TryResolveTypedInst(inst);
  909. }
  910. case CARBON_KIND(SemIR::ClassDecl inst): {
  911. return TryResolveTypedInst(inst, const_id);
  912. }
  913. case CARBON_KIND(SemIR::ClassType inst): {
  914. return TryResolveTypedInst(inst);
  915. }
  916. case CARBON_KIND(SemIR::ConstType inst): {
  917. return TryResolveTypedInst(inst);
  918. }
  919. case CARBON_KIND(SemIR::ExportDecl inst): {
  920. return TryResolveTypedInst(inst);
  921. }
  922. case CARBON_KIND(SemIR::FieldDecl inst): {
  923. return TryResolveTypedInst(inst, inst_id);
  924. }
  925. case CARBON_KIND(SemIR::FunctionDecl inst): {
  926. return TryResolveTypedInst(inst, const_id);
  927. }
  928. case CARBON_KIND(SemIR::FunctionType inst): {
  929. return TryResolveTypedInst(inst);
  930. }
  931. case CARBON_KIND(SemIR::GenericClassType inst): {
  932. return TryResolveTypedInst(inst);
  933. }
  934. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  935. return TryResolveTypedInst(inst);
  936. }
  937. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  938. return TryResolveTypedInst(inst, inst_id);
  939. }
  940. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  941. return TryResolveTypedInst(inst, const_id);
  942. }
  943. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  944. return TryResolveTypedInst(inst);
  945. }
  946. case CARBON_KIND(SemIR::InterfaceType inst): {
  947. return TryResolveTypedInst(inst);
  948. }
  949. case CARBON_KIND(SemIR::IntLiteral inst): {
  950. return TryResolveTypedInst(inst);
  951. }
  952. case CARBON_KIND(SemIR::PointerType inst): {
  953. return TryResolveTypedInst(inst);
  954. }
  955. case CARBON_KIND(SemIR::StructType inst): {
  956. return TryResolveTypedInst(inst, inst_id);
  957. }
  958. case CARBON_KIND(SemIR::StructValue inst): {
  959. return TryResolveTypedInst(inst);
  960. }
  961. case CARBON_KIND(SemIR::TupleType inst): {
  962. return TryResolveTypedInst(inst);
  963. }
  964. case CARBON_KIND(SemIR::TupleValue inst): {
  965. return TryResolveTypedInst(inst);
  966. }
  967. case CARBON_KIND(SemIR::UnboundElementType inst): {
  968. return TryResolveTypedInst(inst);
  969. }
  970. default:
  971. context_.TODO(
  972. SemIR::LocId(AddImportIRInst(inst_id)),
  973. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  974. return {.const_id = SemIR::ConstantId::Error};
  975. }
  976. }
  977. // Produces a resolve result that tries resolving this instruction again. If
  978. // `const_id` is specified, then this is the end of the second phase, and the
  979. // constant value will be passed to the next resolution attempt. Otherwise,
  980. // this is the end of the first phase.
  981. auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  982. -> ResolveResult {
  983. CARBON_CHECK(HasNewWork());
  984. return {.const_id = const_id, .retry = true};
  985. }
  986. // Produces a resolve result that provides the given constant value. Requires
  987. // that there is no new work.
  988. auto ResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  989. CARBON_CHECK(!HasNewWork());
  990. return {.const_id = const_id};
  991. }
  992. // Produces a resolve result that provides the given constant value. Retries
  993. // instead if work has been added.
  994. auto RetryOrResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  995. if (HasNewWork()) {
  996. return Retry();
  997. }
  998. return ResolveAsConstant(const_id);
  999. }
  1000. // Produces a resolve result for the given instruction that describes a
  1001. // constant value. This should only be used for instructions that describe
  1002. // constants, and not for instructions that represent declarations. For a
  1003. // declaration, we need an associated location, so AddInstInNoBlock should be
  1004. // used instead. Requires that there is no new work.
  1005. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  1006. CARBON_CHECK(!HasNewWork());
  1007. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  1008. CARBON_CHECK(result.is_constant(), "{0} is not constant", inst);
  1009. return {.const_id = result};
  1010. }
  1011. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1012. template <typename InstT>
  1013. auto ResolveAs(InstT inst) -> ResolveResult {
  1014. return ResolveAsUntyped(inst);
  1015. }
  1016. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  1017. auto type_const_id = GetLocalConstantId(inst.type_id);
  1018. if (HasNewWork()) {
  1019. return Retry();
  1020. }
  1021. // Add a lazy reference to the target declaration.
  1022. auto decl_id = AddImportRef(
  1023. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  1024. SemIR::EntityNameId::Invalid);
  1025. return ResolveAs<SemIR::AssociatedEntity>(
  1026. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1027. .index = inst.index,
  1028. .decl_id = decl_id});
  1029. }
  1030. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  1031. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1032. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  1033. auto interface_inst_id = GetLocalConstantId(inst.interface_type_id);
  1034. if (HasNewWork()) {
  1035. return Retry();
  1036. }
  1037. return ResolveAs<SemIR::AssociatedEntityType>(
  1038. {.type_id = SemIR::TypeId::TypeType,
  1039. .interface_type_id =
  1040. context_.GetTypeIdForTypeConstant(interface_inst_id),
  1041. .entity_type_id =
  1042. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  1043. }
  1044. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  1045. -> ResolveResult {
  1046. auto type_const_id = GetLocalConstantId(inst.type_id);
  1047. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  1048. if (HasNewWork()) {
  1049. return Retry();
  1050. }
  1051. // Import the instruction in order to update contained base_type_id and
  1052. // track the import location.
  1053. auto inst_id = context_.AddInstInNoBlock(
  1054. context_.MakeImportedLocAndInst<SemIR::BaseDecl>(
  1055. AddImportIRInst(import_inst_id),
  1056. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1057. .base_type_id =
  1058. context_.GetTypeIdForTypeConstant(base_type_const_id),
  1059. .index = inst.index}));
  1060. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  1061. }
  1062. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  1063. auto value_id = GetLocalConstantId(inst.value_id);
  1064. return RetryOrResolveAsConstant(value_id);
  1065. }
  1066. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  1067. auto type_id = GetLocalConstantId(inst.type_id);
  1068. if (HasNewWork()) {
  1069. return Retry();
  1070. }
  1071. const auto& import_entity_name =
  1072. import_ir_.entity_names().Get(inst.entity_name_id);
  1073. auto name_id = GetLocalNameId(import_entity_name.name_id);
  1074. auto entity_name_id = context_.entity_names().Add(
  1075. {.name_id = name_id,
  1076. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1077. .bind_index = import_entity_name.bind_index});
  1078. return ResolveAs<SemIR::BindSymbolicName>(
  1079. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1080. .entity_name_id = entity_name_id,
  1081. .value_id = SemIR::InstId::Invalid});
  1082. }
  1083. // Makes an incomplete class. This is necessary even with classes with a
  1084. // complete declaration, because things such as `Self` may refer back to the
  1085. // type.
  1086. auto MakeIncompleteClass(const SemIR::Class& import_class)
  1087. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1088. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  1089. .class_id = SemIR::ClassId::Invalid,
  1090. .decl_block_id = SemIR::InstBlockId::Empty};
  1091. auto class_decl_id =
  1092. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1093. AddImportIRInst(import_class.latest_decl_id()), class_decl));
  1094. // Regardless of whether ClassDecl is a complete type, we first need an
  1095. // incomplete type so that any references have something to point at.
  1096. class_decl.class_id = context_.classes().Add(
  1097. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  1098. {.self_type_id = SemIR::TypeId::Invalid,
  1099. .inheritance_kind = import_class.inheritance_kind}});
  1100. if (import_class.has_parameters()) {
  1101. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  1102. }
  1103. // Write the class ID into the ClassDecl.
  1104. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  1105. auto self_const_id = context_.constant_values().Get(class_decl_id);
  1106. return {class_decl.class_id, self_const_id};
  1107. }
  1108. // Fills out the class definition for an incomplete class.
  1109. auto AddClassDefinition(const SemIR::Class& import_class,
  1110. SemIR::Class& new_class,
  1111. SemIR::ConstantId object_repr_const_id,
  1112. SemIR::InstId base_id) -> void {
  1113. new_class.definition_id = new_class.first_owning_decl_id;
  1114. new_class.object_repr_id =
  1115. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  1116. new_class.scope_id = context_.name_scopes().Add(
  1117. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1118. new_class.parent_scope_id);
  1119. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  1120. const auto& import_scope =
  1121. import_ir_.name_scopes().Get(import_class.scope_id);
  1122. // Push a block so that we can add scoped instructions to it.
  1123. context_.inst_block_stack().Push();
  1124. AddNameScopeImportRefs(import_scope, new_scope);
  1125. new_class.body_block_id = context_.inst_block_stack().Pop();
  1126. if (import_class.base_id.is_valid()) {
  1127. new_class.base_id = base_id;
  1128. // Add the base scope to extended scopes.
  1129. auto base_inst_id = context_.types().GetInstId(
  1130. context_.insts()
  1131. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  1132. .base_type_id);
  1133. const auto& base_class = context_.classes().Get(
  1134. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  1135. new_scope.extended_scopes.push_back(base_class.scope_id);
  1136. }
  1137. CARBON_CHECK(new_scope.extended_scopes.size() ==
  1138. import_scope.extended_scopes.size());
  1139. }
  1140. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  1141. SemIR::ConstantId class_const_id) -> ResolveResult {
  1142. // TODO: The handling of interfaces repeats a lot with the handling of
  1143. // classes, and will likely also be repeated for named constraints and
  1144. // choice types. Factor out some of this functionality.
  1145. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  1146. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1147. if (!class_const_id.is_valid()) {
  1148. if (HasNewWork()) {
  1149. // This is the end of the first phase. Don't make a new class yet if we
  1150. // already have new work.
  1151. return Retry();
  1152. }
  1153. // On the second phase, create a forward declaration of the class for any
  1154. // recursive references.
  1155. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  1156. } else {
  1157. // On the third phase, compute the class ID from the constant
  1158. // value of the declaration.
  1159. auto class_const_inst = context_.insts().Get(
  1160. context_.constant_values().GetInstId(class_const_id));
  1161. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1162. class_id = class_type->class_id;
  1163. } else {
  1164. auto generic_class_type =
  1165. context_.types().GetAs<SemIR::GenericClassType>(
  1166. class_const_inst.type_id());
  1167. class_id = generic_class_type.class_id;
  1168. }
  1169. }
  1170. // Load constants for the definition.
  1171. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  1172. auto implicit_param_const_ids =
  1173. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  1174. auto param_const_ids = GetLocalParamConstantIds(import_class.param_refs_id);
  1175. auto generic_data = GetLocalGenericData(import_class.generic_id);
  1176. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  1177. auto object_repr_const_id =
  1178. import_class.object_repr_id.is_valid()
  1179. ? GetLocalConstantId(import_class.object_repr_id)
  1180. : SemIR::ConstantId::Invalid;
  1181. auto base_id = import_class.base_id.is_valid()
  1182. ? GetLocalConstantInstId(import_class.base_id)
  1183. : SemIR::InstId::Invalid;
  1184. if (HasNewWork()) {
  1185. return Retry(class_const_id);
  1186. }
  1187. auto& new_class = context_.classes().Get(class_id);
  1188. new_class.parent_scope_id = parent_scope_id;
  1189. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  1190. import_class.implicit_param_refs_id, implicit_param_const_ids);
  1191. new_class.param_refs_id =
  1192. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  1193. SetGenericData(import_class.generic_id, new_class.generic_id, generic_data);
  1194. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1195. if (import_class.is_defined()) {
  1196. AddClassDefinition(import_class, new_class, object_repr_const_id,
  1197. base_id);
  1198. }
  1199. return ResolveAsConstant(class_const_id);
  1200. }
  1201. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  1202. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1203. auto class_const_id = GetLocalConstantId(
  1204. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1205. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1206. if (HasNewWork()) {
  1207. return Retry();
  1208. }
  1209. // Find the corresponding class type. For a non-generic class, this is the
  1210. // type of the class declaration. For a generic class, build a class type
  1211. // referencing this specialization of the generic class.
  1212. auto class_const_inst = context_.insts().Get(
  1213. context_.constant_values().GetInstId(class_const_id));
  1214. if (class_const_inst.Is<SemIR::ClassType>()) {
  1215. return ResolveAsConstant(class_const_id);
  1216. } else {
  1217. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  1218. class_const_inst.type_id());
  1219. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1220. return ResolveAs<SemIR::ClassType>(
  1221. {.type_id = SemIR::TypeId::TypeType,
  1222. .class_id = generic_class_type.class_id,
  1223. .specific_id = specific_id});
  1224. }
  1225. }
  1226. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  1227. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1228. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  1229. if (HasNewWork()) {
  1230. return Retry();
  1231. }
  1232. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  1233. return ResolveAs<SemIR::ConstType>(
  1234. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  1235. }
  1236. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  1237. auto value_id = GetLocalConstantId(inst.value_id);
  1238. return RetryOrResolveAsConstant(value_id);
  1239. }
  1240. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  1241. -> ResolveResult {
  1242. auto const_id = GetLocalConstantId(inst.type_id);
  1243. if (HasNewWork()) {
  1244. return Retry();
  1245. }
  1246. auto inst_id = context_.AddInstInNoBlock(
  1247. context_.MakeImportedLocAndInst<SemIR::FieldDecl>(
  1248. AddImportIRInst(import_inst_id),
  1249. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1250. .name_id = GetLocalNameId(inst.name_id),
  1251. .index = inst.index}));
  1252. return {.const_id = context_.constant_values().Get(inst_id)};
  1253. }
  1254. // Make a declaration of a function. This is done as a separate step from
  1255. // importing the function declaration in order to resolve cycles.
  1256. auto MakeFunctionDecl(const SemIR::Function& import_function,
  1257. SemIR::SpecificId specific_id)
  1258. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1259. SemIR::FunctionDecl function_decl = {
  1260. .type_id = SemIR::TypeId::Invalid,
  1261. .function_id = SemIR::FunctionId::Invalid,
  1262. .decl_block_id = SemIR::InstBlockId::Empty};
  1263. auto function_decl_id =
  1264. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1265. AddImportIRInst(import_function.first_decl_id()), function_decl));
  1266. // Start with an incomplete function.
  1267. function_decl.function_id = context_.functions().Add(
  1268. {GetIncompleteLocalEntityBase(function_decl_id, import_function),
  1269. {.return_storage_id = SemIR::InstId::Invalid,
  1270. .builtin_function_kind = import_function.builtin_function_kind}});
  1271. function_decl.type_id =
  1272. context_.GetFunctionType(function_decl.function_id, specific_id);
  1273. // Write the function ID and type into the FunctionDecl.
  1274. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1275. return {function_decl.function_id,
  1276. context_.constant_values().Get(function_decl_id)};
  1277. }
  1278. auto TryResolveTypedInst(SemIR::FunctionDecl inst,
  1279. SemIR::ConstantId function_const_id)
  1280. -> ResolveResult {
  1281. const auto& import_function = import_ir_.functions().Get(inst.function_id);
  1282. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1283. if (!function_const_id.is_valid()) {
  1284. auto import_specific_id = import_ir_.types()
  1285. .GetAs<SemIR::FunctionType>(inst.type_id)
  1286. .specific_id;
  1287. auto specific_data = GetLocalSpecificData(import_specific_id);
  1288. if (HasNewWork()) {
  1289. // This is the end of the first phase. Don't make a new function yet if
  1290. // we already have new work.
  1291. return Retry();
  1292. }
  1293. auto specific_id =
  1294. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1295. // On the second phase, create a forward declaration of the interface.
  1296. std::tie(function_id, function_const_id) =
  1297. MakeFunctionDecl(import_function, specific_id);
  1298. } else {
  1299. // On the third phase, compute the function ID from the constant value of
  1300. // the declaration.
  1301. auto function_const_inst = context_.insts().Get(
  1302. context_.constant_values().GetInstId(function_const_id));
  1303. auto function_type = context_.types().GetAs<SemIR::FunctionType>(
  1304. function_const_inst.type_id());
  1305. function_id = function_type.function_id;
  1306. }
  1307. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1308. if (import_function.return_storage_id.is_valid()) {
  1309. return_type_const_id = GetLocalConstantId(
  1310. import_ir_.insts().Get(import_function.return_storage_id).type_id());
  1311. }
  1312. auto parent_scope_id = GetLocalNameScopeId(import_function.parent_scope_id);
  1313. auto implicit_param_const_ids =
  1314. GetLocalParamConstantIds(import_function.implicit_param_refs_id);
  1315. auto param_const_ids =
  1316. GetLocalParamConstantIds(import_function.param_refs_id);
  1317. auto generic_data = GetLocalGenericData(import_function.generic_id);
  1318. if (HasNewWork()) {
  1319. return Retry(function_const_id);
  1320. }
  1321. // Add the function declaration.
  1322. auto& new_function = context_.functions().Get(function_id);
  1323. new_function.parent_scope_id = parent_scope_id;
  1324. new_function.implicit_param_refs_id = GetLocalParamRefsId(
  1325. import_function.implicit_param_refs_id, implicit_param_const_ids);
  1326. new_function.param_refs_id =
  1327. GetLocalParamRefsId(import_function.param_refs_id, param_const_ids);
  1328. SetGenericData(import_function.generic_id, new_function.generic_id,
  1329. generic_data);
  1330. if (import_function.return_storage_id.is_valid()) {
  1331. // Recreate the return slot from scratch.
  1332. // TODO: Once we import function definitions, we'll need to make sure we
  1333. // use the same return storage variable in the declaration and definition.
  1334. new_function.return_storage_id =
  1335. context_.AddInstInNoBlock<SemIR::VarStorage>(
  1336. AddImportIRInst(import_function.return_storage_id),
  1337. {.type_id =
  1338. context_.GetTypeIdForTypeConstant(return_type_const_id),
  1339. .name_id = SemIR::NameId::ReturnSlot});
  1340. }
  1341. if (import_function.definition_id.is_valid()) {
  1342. new_function.definition_id = new_function.first_owning_decl_id;
  1343. }
  1344. return ResolveAsConstant(function_const_id);
  1345. }
  1346. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1347. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1348. auto fn_val_id = GetLocalConstantInstId(
  1349. import_ir_.functions().Get(inst.function_id).first_decl_id());
  1350. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1351. if (HasNewWork()) {
  1352. return Retry();
  1353. }
  1354. auto fn_type_id = context_.insts().Get(fn_val_id).type_id();
  1355. return ResolveAs<SemIR::FunctionType>(
  1356. {.type_id = SemIR::TypeId::TypeType,
  1357. .function_id = context_.types()
  1358. .GetAs<SemIR::FunctionType>(fn_type_id)
  1359. .function_id,
  1360. .specific_id =
  1361. GetOrAddLocalSpecific(inst.specific_id, specific_data)});
  1362. }
  1363. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1364. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1365. auto class_val_id = GetLocalConstantInstId(
  1366. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1367. if (HasNewWork()) {
  1368. return Retry();
  1369. }
  1370. auto class_val = context_.insts().Get(class_val_id);
  1371. CARBON_CHECK(
  1372. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1373. return ResolveAsConstant(
  1374. context_.types().GetConstantId(class_val.type_id()));
  1375. }
  1376. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1377. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1378. auto interface_val_id = GetLocalConstantInstId(
  1379. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1380. if (HasNewWork()) {
  1381. return Retry();
  1382. }
  1383. auto interface_val = context_.insts().Get(interface_val_id);
  1384. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1385. interface_val.type_id()));
  1386. return ResolveAsConstant(
  1387. context_.types().GetConstantId(interface_val.type_id()));
  1388. }
  1389. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1390. SemIR::InstId inst_id) -> ResolveResult {
  1391. // Return the constant for the instruction of the imported constant.
  1392. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1393. if (!constant_id.is_valid()) {
  1394. return ResolveAsConstant(SemIR::ConstantId::Error);
  1395. }
  1396. if (!constant_id.is_constant()) {
  1397. context_.TODO(inst_id,
  1398. "Non-constant ImportRefLoaded (comes up with var)");
  1399. return ResolveAsConstant(SemIR::ConstantId::Error);
  1400. }
  1401. auto new_constant_id =
  1402. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1403. return RetryOrResolveAsConstant(new_constant_id);
  1404. }
  1405. // Make a declaration of an interface. This is done as a separate step from
  1406. // importing the interface definition in order to resolve cycles.
  1407. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1408. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1409. SemIR::InterfaceDecl interface_decl = {
  1410. .type_id = SemIR::TypeId::TypeType,
  1411. .interface_id = SemIR::InterfaceId::Invalid,
  1412. .decl_block_id = SemIR::InstBlockId::Empty};
  1413. auto interface_decl_id =
  1414. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1415. AddImportIRInst(import_interface.first_owning_decl_id),
  1416. interface_decl));
  1417. // Start with an incomplete interface.
  1418. interface_decl.interface_id = context_.interfaces().Add(
  1419. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1420. {}});
  1421. if (import_interface.has_parameters()) {
  1422. interface_decl.type_id =
  1423. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1424. }
  1425. // Write the interface ID into the InterfaceDecl.
  1426. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1427. return {interface_decl.interface_id,
  1428. context_.constant_values().Get(interface_decl_id)};
  1429. }
  1430. // Imports the definition for an interface that has been imported as a forward
  1431. // declaration.
  1432. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1433. SemIR::Interface& new_interface,
  1434. SemIR::InstId self_param_id) -> void {
  1435. new_interface.scope_id = context_.name_scopes().Add(
  1436. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1437. new_interface.parent_scope_id);
  1438. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1439. const auto& import_scope =
  1440. import_ir_.name_scopes().Get(import_interface.scope_id);
  1441. // Push a block so that we can add scoped instructions to it.
  1442. context_.inst_block_stack().Push();
  1443. AddNameScopeImportRefs(import_scope, new_scope);
  1444. new_interface.associated_entities_id =
  1445. AddAssociatedEntities(import_interface.associated_entities_id);
  1446. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1447. new_interface.self_param_id = self_param_id;
  1448. CARBON_CHECK(import_scope.extended_scopes.empty(),
  1449. "Interfaces don't currently have extended scopes to support.");
  1450. }
  1451. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1452. SemIR::ConstantId interface_const_id)
  1453. -> ResolveResult {
  1454. const auto& import_interface =
  1455. import_ir_.interfaces().Get(inst.interface_id);
  1456. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1457. if (!interface_const_id.is_valid()) {
  1458. if (HasNewWork()) {
  1459. // This is the end of the first phase. Don't make a new interface yet if
  1460. // we already have new work.
  1461. return Retry();
  1462. }
  1463. // On the second phase, create a forward declaration of the interface.
  1464. std::tie(interface_id, interface_const_id) =
  1465. MakeInterfaceDecl(import_interface);
  1466. } else {
  1467. // On the third phase, compute the interface ID from the constant value of
  1468. // the declaration.
  1469. auto interface_const_inst = context_.insts().Get(
  1470. context_.constant_values().GetInstId(interface_const_id));
  1471. if (auto interface_type =
  1472. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1473. interface_id = interface_type->interface_id;
  1474. } else {
  1475. auto generic_interface_type =
  1476. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1477. interface_const_inst.type_id());
  1478. interface_id = generic_interface_type.interface_id;
  1479. }
  1480. }
  1481. auto parent_scope_id =
  1482. GetLocalNameScopeId(import_interface.parent_scope_id);
  1483. auto implicit_param_const_ids =
  1484. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1485. auto param_const_ids =
  1486. GetLocalParamConstantIds(import_interface.param_refs_id);
  1487. auto generic_data = GetLocalGenericData(import_interface.generic_id);
  1488. std::optional<SemIR::InstId> self_param_id;
  1489. if (import_interface.is_defined()) {
  1490. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1491. }
  1492. if (HasNewWork()) {
  1493. return Retry(interface_const_id);
  1494. }
  1495. auto& new_interface = context_.interfaces().Get(interface_id);
  1496. new_interface.parent_scope_id = parent_scope_id;
  1497. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1498. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1499. new_interface.param_refs_id =
  1500. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1501. SetGenericData(import_interface.generic_id, new_interface.generic_id,
  1502. generic_data);
  1503. if (import_interface.is_defined()) {
  1504. CARBON_CHECK(self_param_id);
  1505. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1506. }
  1507. return ResolveAsConstant(interface_const_id);
  1508. }
  1509. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1510. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1511. auto interface_const_id = GetLocalConstantId(
  1512. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1513. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1514. if (HasNewWork()) {
  1515. return Retry();
  1516. }
  1517. // Find the corresponding interface type. For a non-generic interface, this
  1518. // is the type of the interface declaration. For a generic interface, build
  1519. // a interface type referencing this specialization of the generic
  1520. // interface.
  1521. auto interface_const_inst = context_.insts().Get(
  1522. context_.constant_values().GetInstId(interface_const_id));
  1523. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1524. return ResolveAsConstant(interface_const_id);
  1525. } else {
  1526. auto generic_interface_type =
  1527. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1528. interface_const_inst.type_id());
  1529. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1530. return ResolveAs<SemIR::InterfaceType>(
  1531. {.type_id = SemIR::TypeId::TypeType,
  1532. .interface_id = generic_interface_type.interface_id,
  1533. .specific_id = specific_id});
  1534. }
  1535. }
  1536. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1537. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1538. if (HasNewWork()) {
  1539. return Retry();
  1540. }
  1541. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1542. return ResolveAs<SemIR::InterfaceWitness>(
  1543. {.type_id =
  1544. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1545. .elements_id = elements_id});
  1546. }
  1547. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1548. auto type_id = GetLocalConstantId(inst.type_id);
  1549. if (HasNewWork()) {
  1550. return Retry();
  1551. }
  1552. return ResolveAs<SemIR::IntLiteral>(
  1553. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1554. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1555. }
  1556. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1557. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1558. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1559. if (HasNewWork()) {
  1560. return Retry();
  1561. }
  1562. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1563. return ResolveAs<SemIR::PointerType>(
  1564. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1565. }
  1566. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1567. -> ResolveResult {
  1568. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1569. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1570. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1571. field_const_ids.reserve(orig_fields.size());
  1572. for (auto field_id : orig_fields) {
  1573. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1574. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1575. }
  1576. if (HasNewWork()) {
  1577. return Retry();
  1578. }
  1579. // Prepare a vector of fields for GetStructType.
  1580. // TODO: Should we have field constants so that we can deduplicate fields
  1581. // without creating instructions here?
  1582. llvm::SmallVector<SemIR::InstId> fields;
  1583. fields.reserve(orig_fields.size());
  1584. for (auto [field_id, field_const_id] :
  1585. llvm::zip(orig_fields, field_const_ids)) {
  1586. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1587. auto name_id = GetLocalNameId(field.name_id);
  1588. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1589. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1590. AddImportIRInst(import_inst_id),
  1591. {.name_id = name_id, .field_type_id = field_type_id}));
  1592. }
  1593. return ResolveAs<SemIR::StructType>(
  1594. {.type_id = SemIR::TypeId::TypeType,
  1595. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1596. }
  1597. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1598. auto type_id = GetLocalConstantId(inst.type_id);
  1599. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1600. if (HasNewWork()) {
  1601. return Retry();
  1602. }
  1603. return ResolveAs<SemIR::StructValue>(
  1604. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1605. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1606. }
  1607. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1608. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1609. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1610. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1611. elem_const_ids.reserve(orig_elem_type_ids.size());
  1612. for (auto elem_type_id : orig_elem_type_ids) {
  1613. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1614. }
  1615. if (HasNewWork()) {
  1616. return Retry();
  1617. }
  1618. // Prepare a vector of the tuple types for GetTupleType.
  1619. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1620. elem_type_ids.reserve(orig_elem_type_ids.size());
  1621. for (auto elem_const_id : elem_const_ids) {
  1622. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1623. }
  1624. return ResolveAsConstant(
  1625. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids)));
  1626. }
  1627. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1628. auto type_id = GetLocalConstantId(inst.type_id);
  1629. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1630. if (HasNewWork()) {
  1631. return Retry();
  1632. }
  1633. return ResolveAs<SemIR::TupleValue>(
  1634. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1635. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1636. }
  1637. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1638. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1639. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1640. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1641. if (HasNewWork()) {
  1642. return Retry();
  1643. }
  1644. return ResolveAs<SemIR::UnboundElementType>(
  1645. {.type_id = SemIR::TypeId::TypeType,
  1646. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1647. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1648. }
  1649. // Perform any work that we deferred until the end of the main Resolve loop.
  1650. auto PerformPendingWork() -> void {
  1651. // Note that the individual Finish steps can add new pending work, so keep
  1652. // going until we have no more work to do.
  1653. while (!pending_generics_.empty() || !pending_specifics_.empty()) {
  1654. while (!pending_generics_.empty()) {
  1655. FinishPendingGeneric(pending_generics_.pop_back_val());
  1656. }
  1657. while (!pending_specifics_.empty()) {
  1658. FinishPendingSpecific(pending_specifics_.pop_back_val());
  1659. }
  1660. }
  1661. }
  1662. // Resolves and returns the local contents for an imported instruction block
  1663. // of constant instructions.
  1664. auto ResolveLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  1665. -> llvm::SmallVector<SemIR::InstId> {
  1666. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  1667. llvm::SmallVector<SemIR::InstId> inst_ids;
  1668. inst_ids.reserve(import_block.size());
  1669. for (auto import_inst_id : import_block) {
  1670. inst_ids.push_back(
  1671. context_.constant_values().GetInstId(ResolveOneInst(import_inst_id)));
  1672. }
  1673. return inst_ids;
  1674. }
  1675. // Resolves and returns a local eval block for a region of an imported
  1676. // generic.
  1677. auto ResolveLocalEvalBlock(const SemIR::Generic& import_generic,
  1678. SemIR::GenericId generic_id,
  1679. SemIR::GenericInstIndex::Region region)
  1680. -> SemIR::InstBlockId {
  1681. auto import_block_id = import_generic.GetEvalBlock(region);
  1682. if (!import_block_id.is_valid()) {
  1683. return SemIR::InstBlockId::Invalid;
  1684. }
  1685. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1686. return RebuildGenericEvalBlock(context_, generic_id, region, inst_ids);
  1687. }
  1688. // Fills in the remaining information in a partially-imported generic.
  1689. auto FinishPendingGeneric(PendingGeneric pending) -> void {
  1690. const auto& import_generic = import_ir_.generics().Get(pending.import_id);
  1691. // Don't store the local generic between calls: the generics list can be
  1692. // reallocated by ResolveLocalEvalBlock importing more specifics.
  1693. auto decl_block_id =
  1694. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1695. SemIR::GenericInstIndex::Region::Declaration);
  1696. context_.generics().Get(pending.local_id).decl_block_id = decl_block_id;
  1697. auto self_specific_id = MakeSelfSpecific(context_, pending.local_id);
  1698. context_.generics().Get(pending.local_id).self_specific_id =
  1699. self_specific_id;
  1700. pending_specifics_.push_back({.import_id = import_generic.self_specific_id,
  1701. .local_id = self_specific_id});
  1702. auto definition_block_id =
  1703. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1704. SemIR::GenericInstIndex::Region::Definition);
  1705. context_.generics().Get(pending.local_id).definition_block_id =
  1706. definition_block_id;
  1707. }
  1708. // Resolves and returns a local inst block of constant instructions
  1709. // corresponding to an imported inst block.
  1710. auto ResolveLocalInstBlock(SemIR::InstBlockId import_block_id)
  1711. -> SemIR::InstBlockId {
  1712. if (!import_block_id.is_valid()) {
  1713. return SemIR::InstBlockId::Invalid;
  1714. }
  1715. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1716. return context_.inst_blocks().Add(inst_ids);
  1717. }
  1718. // Fills in the remaining information in a partially-imported specific.
  1719. auto FinishPendingSpecific(PendingSpecific pending) -> void {
  1720. const auto& import_specific = import_ir_.specifics().Get(pending.import_id);
  1721. // Don't store the local specific between calls: the specifics list can be
  1722. // reallocated by ResolveLocalInstBlock importing more specifics.
  1723. if (!context_.specifics().Get(pending.local_id).decl_block_id.is_valid()) {
  1724. auto decl_block_id = ResolveLocalInstBlock(import_specific.decl_block_id);
  1725. context_.specifics().Get(pending.local_id).decl_block_id = decl_block_id;
  1726. }
  1727. if (!context_.specifics()
  1728. .Get(pending.local_id)
  1729. .definition_block_id.is_valid() &&
  1730. import_specific.definition_block_id.is_valid()) {
  1731. auto definition_block_id =
  1732. ResolveLocalInstBlock(import_specific.definition_block_id);
  1733. context_.specifics().Get(pending.local_id).definition_block_id =
  1734. definition_block_id;
  1735. }
  1736. }
  1737. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1738. return context_.import_ir_constant_values()[import_ir_id_.index];
  1739. }
  1740. Context& context_;
  1741. SemIR::ImportIRId import_ir_id_;
  1742. const SemIR::File& import_ir_;
  1743. llvm::SmallVector<Work> work_stack_;
  1744. // The size of work_stack_ at the start of resolving the current instruction.
  1745. size_t initial_work_ = 0;
  1746. // Generics that we have partially imported but not yet finished importing.
  1747. llvm::SmallVector<PendingGeneric> pending_generics_;
  1748. // Specifics that we have partially imported but not yet finished importing.
  1749. llvm::SmallVector<PendingSpecific> pending_specifics_;
  1750. };
  1751. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1752. // loaded (including the one pointed at directly by the ImportRef), and the
  1753. // final instruction's type ID.
  1754. //
  1755. // This addresses cases where an ImportRefUnloaded may point at another
  1756. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1757. // constant-evaluated version of the instruction to work with.
  1758. static auto GetInstForLoad(Context& context,
  1759. SemIR::ImportIRInstId import_ir_inst_id)
  1760. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1761. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1762. {}, SemIR::TypeId::Invalid};
  1763. auto& [import_ir_insts, type_id] = result;
  1764. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1765. // The first ImportIRInst is added directly because the IR doesn't need to be
  1766. // localized.
  1767. import_ir_insts.push_back(import_ir_inst);
  1768. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1769. while (true) {
  1770. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1771. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1772. if (!import_ref) {
  1773. type_id = cursor_inst.type_id();
  1774. return result;
  1775. }
  1776. import_ir_inst =
  1777. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1778. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1779. import_ir_insts.push_back(
  1780. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1781. .is_export = false,
  1782. .sem_ir = cursor_ir}),
  1783. .inst_id = import_ir_inst.inst_id});
  1784. }
  1785. }
  1786. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1787. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1788. if (!inst) {
  1789. return;
  1790. }
  1791. auto [indirect_insts, load_type_id] =
  1792. GetInstForLoad(context, inst->import_ir_inst_id);
  1793. // The last indirect instruction is the one to resolve. Pop it here because
  1794. // Resolve will assign the constant.
  1795. auto load_ir_inst = indirect_insts.pop_back_val();
  1796. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1797. // The resolver calls into Context to create instructions. Don't register
  1798. // those instructions as part of the enclosing generic scope if they're
  1799. // dependent on a generic parameter.
  1800. context.generic_region_stack().Push();
  1801. auto type_id = resolver.ResolveType(load_type_id);
  1802. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1803. context.generic_region_stack().Pop();
  1804. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1805. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1806. // TryEvalInst, which we want to avoid with ImportRefs.
  1807. context.sem_ir().insts().Set(
  1808. inst_id,
  1809. SemIR::ImportRefLoaded{.type_id = type_id,
  1810. .import_ir_inst_id = inst->import_ir_inst_id,
  1811. .entity_name_id = inst->entity_name_id});
  1812. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1813. context.constant_values().Set(inst_id, constant_id);
  1814. for (const auto& import_ir_inst : indirect_insts) {
  1815. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1816. import_ir_inst.inst_id, constant_id);
  1817. }
  1818. }
  1819. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1820. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1821. const SemIR::File& import_ir,
  1822. SemIR::ImplId import_impl_id) -> void {
  1823. // Resolve the imported impl to a local impl ID.
  1824. ImportRefResolver resolver(context, import_ir_id);
  1825. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1826. auto self_id = resolver.ResolveType(import_impl.self_id);
  1827. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1828. // Import the definition if the impl is defined.
  1829. // TODO: Do we need to check for multiple definitions?
  1830. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1831. if (import_impl.is_defined()) {
  1832. // TODO: Create a scope for the `impl` if necessary.
  1833. // TODO: Consider importing the definition_id.
  1834. auto& impl = context.impls().Get(impl_id);
  1835. impl.witness_id = AddImportRef(
  1836. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1837. SemIR::EntityNameId::Invalid);
  1838. }
  1839. }
  1840. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1841. // and this file elsewhere.
  1842. auto ImportImpls(Context& context) -> void {
  1843. for (auto [import_index, import_ir] :
  1844. llvm::enumerate(context.import_irs().array_ref())) {
  1845. if (!import_ir.sem_ir) {
  1846. continue;
  1847. }
  1848. SemIR::ImportIRId import_ir_id(import_index);
  1849. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1850. SemIR::ImplId impl_id(impl_index);
  1851. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1852. }
  1853. }
  1854. }
  1855. } // namespace Carbon::Check