import_ref.cpp 85 KB

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