import_ref.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251
  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. auto import_decl_inst_id = import_ir_.generics().Get(generic_id).decl_id;
  503. auto import_decl_inst = import_ir_.insts().Get(import_decl_inst_id);
  504. if (import_decl_inst.Is<SemIR::ImplDecl>()) {
  505. // For an impl declaration, the imported entity can be found via the
  506. // declaration.
  507. return GetLocalConstantId(import_decl_inst_id);
  508. }
  509. // For all other kinds of declaration, the imported entity can be found via
  510. // the type of the declaration.
  511. return GetLocalConstantId(import_decl_inst.type_id());
  512. }
  513. // Gets a local generic ID given the corresponding local constant ID returned
  514. // by GetLocalConstantId for the imported generic. Does not add any new work.
  515. auto GetLocalGenericId(SemIR::ConstantId local_const_id) -> SemIR::GenericId {
  516. if (!local_const_id.is_valid()) {
  517. return SemIR::GenericId::Invalid;
  518. }
  519. auto inst = context_.insts().Get(
  520. context_.constant_values().GetInstId(local_const_id));
  521. CARBON_KIND_SWITCH(inst) {
  522. case CARBON_KIND(SemIR::FunctionType fn_type): {
  523. return context_.functions().Get(fn_type.function_id).generic_id;
  524. }
  525. case CARBON_KIND(SemIR::GenericClassType class_type): {
  526. return context_.classes().Get(class_type.class_id).generic_id;
  527. }
  528. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  529. return context_.interfaces()
  530. .Get(interface_type.interface_id)
  531. .generic_id;
  532. }
  533. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  534. return context_.impls().Get(impl_decl.impl_id).generic_id;
  535. }
  536. default: {
  537. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  538. }
  539. }
  540. }
  541. // Gets local information about an imported specific.
  542. auto GetLocalSpecificData(SemIR::SpecificId specific_id) -> SpecificData {
  543. if (!specific_id.is_valid()) {
  544. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  545. }
  546. const auto& specific = import_ir_.specifics().Get(specific_id);
  547. return {
  548. .generic_const_id = GetLocalConstantId(specific.generic_id),
  549. .args = GetLocalInstBlockContents(specific.args_id),
  550. };
  551. }
  552. // Gets a local specific whose data was already imported by
  553. // GetLocalSpecificData. Does not add any new work.
  554. auto GetOrAddLocalSpecific(SemIR::SpecificId import_specific_id,
  555. const SpecificData& data) -> SemIR::SpecificId {
  556. if (!import_specific_id.is_valid()) {
  557. return SemIR::SpecificId::Invalid;
  558. }
  559. // Form a corresponding local specific ID.
  560. const auto& import_specific =
  561. import_ir_.specifics().Get(import_specific_id);
  562. auto generic_id = GetLocalGenericId(data.generic_const_id);
  563. auto args_id =
  564. GetLocalCanonicalInstBlockId(import_specific.args_id, data.args);
  565. // Get the specific.
  566. auto specific_id = context_.specifics().GetOrAdd(generic_id, args_id);
  567. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  568. auto& specific = context_.specifics().Get(specific_id);
  569. if (!specific.decl_block_id.is_valid() ||
  570. (import_specific.definition_block_id.is_valid() &&
  571. !specific.definition_block_id.is_valid())) {
  572. pending_specifics_.push_back(
  573. {.import_id = import_specific_id, .local_id = specific_id});
  574. }
  575. return specific_id;
  576. }
  577. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  578. // to work_stack_.
  579. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  580. -> llvm::SmallVector<ParamData> {
  581. llvm::SmallVector<ParamData> param_data;
  582. if (!param_refs_id.is_valid() ||
  583. param_refs_id == SemIR::InstBlockId::Empty) {
  584. return param_data;
  585. }
  586. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  587. param_data.reserve(param_refs.size());
  588. for (auto inst_id : param_refs) {
  589. auto type_const_id =
  590. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id());
  591. // If the parameter is a symbolic binding, build the BindSymbolicName
  592. // constant.
  593. auto bind_id = inst_id;
  594. auto bind_inst = import_ir_.insts().Get(bind_id);
  595. if (auto addr = bind_inst.TryAs<SemIR::AddrPattern>()) {
  596. bind_id = addr->inner_id;
  597. bind_inst = import_ir_.insts().Get(bind_id);
  598. }
  599. auto bind_const_id = bind_inst.Is<SemIR::BindSymbolicName>()
  600. ? GetLocalConstantId(bind_id)
  601. : SemIR::ConstantId::Invalid;
  602. param_data.push_back(
  603. {.type_const_id = type_const_id, .bind_const_id = bind_const_id});
  604. }
  605. return param_data;
  606. }
  607. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  608. // a version of param_refs_id localized to the current IR.
  609. auto GetLocalParamRefsId(SemIR::InstBlockId param_refs_id,
  610. const llvm::SmallVector<ParamData>& params_data)
  611. -> SemIR::InstBlockId {
  612. if (!param_refs_id.is_valid() ||
  613. param_refs_id == SemIR::InstBlockId::Empty) {
  614. return param_refs_id;
  615. }
  616. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  617. llvm::SmallVector<SemIR::InstId> new_param_refs;
  618. for (auto [ref_id, param_data] : llvm::zip(param_refs, params_data)) {
  619. // Figure out the param structure. This echoes
  620. // Function::GetParamFromParamRefId.
  621. // TODO: Consider a different parameter handling to simplify import logic.
  622. auto inst = import_ir_.insts().Get(ref_id);
  623. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  624. auto bind_id = ref_id;
  625. auto param_id = ref_id;
  626. if (addr_inst) {
  627. bind_id = addr_inst->inner_id;
  628. param_id = bind_id;
  629. inst = import_ir_.insts().Get(bind_id);
  630. }
  631. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  632. if (bind_inst) {
  633. param_id = bind_inst->value_id;
  634. inst = import_ir_.insts().Get(param_id);
  635. }
  636. auto param_inst = inst.As<SemIR::Param>();
  637. // Rebuild the param instruction.
  638. auto name_id = GetLocalNameId(param_inst.name_id);
  639. auto type_id =
  640. context_.GetTypeIdForTypeConstant(param_data.type_const_id);
  641. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  642. AddImportIRInst(param_id),
  643. {.type_id = type_id,
  644. .name_id = name_id,
  645. .runtime_index = param_inst.runtime_index});
  646. if (bind_inst) {
  647. switch (bind_inst->kind) {
  648. case SemIR::BindName::Kind: {
  649. auto entity_name_id = context_.entity_names().Add(
  650. {.name_id = name_id,
  651. .parent_scope_id = SemIR::NameScopeId::Invalid,
  652. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  653. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  654. AddImportIRInst(bind_id), {.type_id = type_id,
  655. .entity_name_id = entity_name_id,
  656. .value_id = new_param_id});
  657. break;
  658. }
  659. case SemIR::BindSymbolicName::Kind: {
  660. // We already imported a constant value for this symbolic binding.
  661. // We can reuse most of it, but update the value to point to our
  662. // specific parameter, and preserve the constant value.
  663. auto new_bind_inst =
  664. context_.insts().GetAs<SemIR::BindSymbolicName>(
  665. context_.constant_values().GetInstId(
  666. param_data.bind_const_id));
  667. new_bind_inst.value_id = new_param_id;
  668. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  669. new_bind_inst);
  670. context_.constant_values().Set(new_param_id,
  671. param_data.bind_const_id);
  672. break;
  673. }
  674. default: {
  675. CARBON_FATAL("Unexpected kind: {0}", bind_inst->kind);
  676. }
  677. }
  678. }
  679. if (addr_inst) {
  680. new_param_id = context_.AddInstInNoBlock(
  681. context_.MakeImportedLocAndInst<SemIR::AddrPattern>(
  682. AddImportIRInst(ref_id),
  683. {.type_id = type_id, .inner_id = new_param_id}));
  684. }
  685. new_param_refs.push_back(new_param_id);
  686. }
  687. return context_.inst_blocks().Add(new_param_refs);
  688. }
  689. // Translates a NameId from the import IR to a local NameId.
  690. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  691. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  692. return SemIR::NameId::ForIdentifier(
  693. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  694. }
  695. return import_name_id;
  696. }
  697. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  698. // unresolved constants to the work stack.
  699. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  700. -> SemIR::NameScopeId {
  701. // Get the instruction that created the scope.
  702. auto [inst_id, inst] =
  703. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  704. if (!inst) {
  705. // Map scopes that aren't associated with an instruction to invalid
  706. // scopes. For now, such scopes aren't used, and we don't have a good way
  707. // to remap them.
  708. return SemIR::NameScopeId::Invalid;
  709. }
  710. // Get the constant value for the scope.
  711. auto const_id = SemIR::ConstantId::Invalid;
  712. CARBON_KIND_SWITCH(*inst) {
  713. case SemIR::Namespace::Kind:
  714. // If the namespace has already been imported, we can use its constant.
  715. // However, if it hasn't, we use Invalid instead of adding it to the
  716. // work stack. That's expected to be okay when resolving references.
  717. const_id = import_ir_constant_values().Get(inst_id);
  718. break;
  719. default:
  720. const_id = GetLocalConstantId(inst_id);
  721. }
  722. if (!const_id.is_valid()) {
  723. return SemIR::NameScopeId::Invalid;
  724. }
  725. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  726. auto name_scope_inst = context_.insts().Get(const_inst_id);
  727. CARBON_KIND_SWITCH(name_scope_inst) {
  728. case CARBON_KIND(SemIR::Namespace inst): {
  729. return inst.name_scope_id;
  730. }
  731. case CARBON_KIND(SemIR::ClassType inst): {
  732. return context_.classes().Get(inst.class_id).scope_id;
  733. }
  734. case CARBON_KIND(SemIR::ImplDecl inst): {
  735. return context_.impls().Get(inst.impl_id).scope_id;
  736. }
  737. case CARBON_KIND(SemIR::InterfaceType inst): {
  738. return context_.interfaces().Get(inst.interface_id).scope_id;
  739. }
  740. case SemIR::StructValue::Kind: {
  741. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  742. CARBON_KIND_SWITCH(type_inst) {
  743. case CARBON_KIND(SemIR::GenericClassType inst): {
  744. return context_.classes().Get(inst.class_id).scope_id;
  745. }
  746. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  747. return context_.interfaces().Get(inst.interface_id).scope_id;
  748. }
  749. default: {
  750. break;
  751. }
  752. }
  753. break;
  754. }
  755. default: {
  756. if (const_inst_id == SemIR::InstId::BuiltinError) {
  757. return SemIR::NameScopeId::Invalid;
  758. }
  759. break;
  760. }
  761. }
  762. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  763. name_scope_inst);
  764. }
  765. // Given an imported entity base, returns an incomplete, local version of it.
  766. //
  767. // Most fields are set in the third phase once they're imported. Import enough
  768. // of the parameter lists that we know whether this interface is a generic
  769. // interface and can build the right constant value for it.
  770. //
  771. // TODO: Support extern.
  772. // TODO: Add a better way to represent a generic prior to importing the
  773. // parameters.
  774. auto GetIncompleteLocalEntityBase(
  775. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  776. -> SemIR::EntityWithParamsBase {
  777. // Translate the extern_library_id if present.
  778. auto extern_library_id = SemIR::LibraryNameId::Invalid;
  779. if (import_base.extern_library_id.is_valid()) {
  780. if (import_base.extern_library_id.index >= 0) {
  781. auto val = import_ir_.string_literal_values().Get(
  782. import_base.extern_library_id.AsStringLiteralValueId());
  783. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  784. context_.string_literal_values().Add(val));
  785. } else {
  786. extern_library_id = import_base.extern_library_id;
  787. }
  788. }
  789. return {
  790. .name_id = GetLocalNameId(import_base.name_id),
  791. .parent_scope_id = SemIR::NameScopeId::Invalid,
  792. .generic_id = MakeIncompleteGeneric(decl_id, import_base.generic_id),
  793. .first_param_node_id = Parse::NodeId::Invalid,
  794. .last_param_node_id = Parse::NodeId::Invalid,
  795. .pattern_block_id = SemIR::InstBlockId::Invalid,
  796. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  797. ? SemIR::InstBlockId::Empty
  798. : SemIR::InstBlockId::Invalid,
  799. .param_refs_id = import_base.param_refs_id.is_valid()
  800. ? SemIR::InstBlockId::Empty
  801. : SemIR::InstBlockId::Invalid,
  802. .is_extern = import_base.is_extern,
  803. .extern_library_id = extern_library_id,
  804. .non_owning_decl_id = import_base.non_owning_decl_id.is_valid()
  805. ? decl_id
  806. : SemIR::InstId::Invalid,
  807. .first_owning_decl_id = import_base.first_owning_decl_id.is_valid()
  808. ? decl_id
  809. : SemIR::InstId::Invalid,
  810. };
  811. }
  812. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  813. // lookup.
  814. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  815. SemIR::NameScope& new_scope) -> void {
  816. for (auto entry : import_scope.names) {
  817. auto ref_id = AddImportRef(
  818. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  819. SemIR::EntityNameId::Invalid);
  820. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  821. .inst_id = ref_id,
  822. .access_kind = entry.access_kind});
  823. }
  824. }
  825. // Given a block ID for a list of associated entities of a witness, returns a
  826. // version localized to the current IR.
  827. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  828. -> SemIR::InstBlockId {
  829. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  830. return SemIR::InstBlockId::Empty;
  831. }
  832. auto associated_entities =
  833. import_ir_.inst_blocks().Get(associated_entities_id);
  834. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  835. new_associated_entities.reserve(associated_entities.size());
  836. for (auto inst_id : associated_entities) {
  837. new_associated_entities.push_back(
  838. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  839. SemIR::EntityNameId::Invalid));
  840. }
  841. return context_.inst_blocks().Add(new_associated_entities);
  842. }
  843. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  844. // more has been added to the stack. A similar API is followed for all
  845. // following TryResolveTypedInst helper functions.
  846. //
  847. // `const_id` is Invalid unless we've tried to resolve this instruction
  848. // before, in which case it's the previous result.
  849. //
  850. // TODO: Error is returned when support is missing, but that should go away.
  851. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  852. -> ResolveResult {
  853. auto inst_const_id = import_ir_.constant_values().Get(inst_id);
  854. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  855. return TryResolveInstCanonical(inst_id, const_id);
  856. }
  857. // Try to import the generic. This might add new work.
  858. const auto& symbolic_const =
  859. import_ir_.constant_values().GetSymbolicConstant(inst_const_id);
  860. auto generic_const_id = GetLocalConstantId(symbolic_const.generic_id);
  861. auto inner_const_id = SemIR::ConstantId::Invalid;
  862. if (const_id.is_valid()) {
  863. // For the third phase, extract the constant value that
  864. // TryResolveInstCanonical produced previously.
  865. inner_const_id = context_.constant_values().Get(
  866. context_.constant_values().GetSymbolicConstant(const_id).inst_id);
  867. }
  868. // Import the constant and rebuild the symbolic constant data.
  869. auto result = TryResolveInstCanonical(inst_id, inner_const_id);
  870. if (!result.const_id.is_valid()) {
  871. // First phase: TryResolveInstCanoncial needs a retry.
  872. return result;
  873. }
  874. if (!const_id.is_valid()) {
  875. // Second phase: we have created an abstract constant. Create a
  876. // corresponding generic constant.
  877. if (symbolic_const.generic_id.is_valid()) {
  878. result.const_id = context_.constant_values().AddSymbolicConstant(
  879. {.inst_id = context_.constant_values().GetInstId(result.const_id),
  880. .generic_id = GetLocalGenericId(generic_const_id),
  881. .index = symbolic_const.index});
  882. }
  883. } else {
  884. // Third phase: perform a consistency check and produce the constant we
  885. // created in the second phase.
  886. CARBON_CHECK(result.const_id == inner_const_id,
  887. "Constant value changed in third phase.");
  888. result.const_id = const_id;
  889. }
  890. return result;
  891. }
  892. // Tries to resolve the InstId, returning a canonical constant when ready, or
  893. // Invalid if more has been added to the stack. This is the same as
  894. // TryResolveInst, except that it may resolve symbolic constants as canonical
  895. // constants instead of as constants associated with a particular generic.
  896. auto TryResolveInstCanonical(SemIR::InstId inst_id,
  897. SemIR::ConstantId const_id) -> ResolveResult {
  898. if (inst_id.is_builtin()) {
  899. CARBON_CHECK(!const_id.is_valid());
  900. // Constants for builtins can be directly copied.
  901. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  902. }
  903. auto untyped_inst = import_ir_.insts().Get(inst_id);
  904. CARBON_KIND_SWITCH(untyped_inst) {
  905. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  906. return TryResolveTypedInst(inst);
  907. }
  908. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  909. return TryResolveTypedInst(inst);
  910. }
  911. case CARBON_KIND(SemIR::BaseDecl inst): {
  912. return TryResolveTypedInst(inst, inst_id);
  913. }
  914. case CARBON_KIND(SemIR::BindAlias inst): {
  915. return TryResolveTypedInst(inst);
  916. }
  917. case SemIR::BindName::Kind: {
  918. // TODO: Should we be resolving BindNames at all?
  919. return ResolveAsConstant(SemIR::ConstantId::NotConstant);
  920. }
  921. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  922. return TryResolveTypedInst(inst);
  923. }
  924. case CARBON_KIND(SemIR::ClassDecl inst): {
  925. return TryResolveTypedInst(inst, const_id);
  926. }
  927. case CARBON_KIND(SemIR::ClassType inst): {
  928. return TryResolveTypedInst(inst);
  929. }
  930. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  931. return TryResolveTypedInst(inst);
  932. }
  933. case CARBON_KIND(SemIR::ConstType inst): {
  934. return TryResolveTypedInst(inst);
  935. }
  936. case CARBON_KIND(SemIR::ExportDecl inst): {
  937. return TryResolveTypedInst(inst);
  938. }
  939. case CARBON_KIND(SemIR::FieldDecl inst): {
  940. return TryResolveTypedInst(inst, inst_id);
  941. }
  942. case CARBON_KIND(SemIR::FunctionDecl inst): {
  943. return TryResolveTypedInst(inst, const_id);
  944. }
  945. case CARBON_KIND(SemIR::FunctionType inst): {
  946. return TryResolveTypedInst(inst);
  947. }
  948. case CARBON_KIND(SemIR::GenericClassType inst): {
  949. return TryResolveTypedInst(inst);
  950. }
  951. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  952. return TryResolveTypedInst(inst);
  953. }
  954. case CARBON_KIND(SemIR::ImplDecl inst): {
  955. return TryResolveTypedInst(inst, const_id);
  956. }
  957. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  958. return TryResolveTypedInst(inst, inst_id);
  959. }
  960. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  961. return TryResolveTypedInst(inst, const_id);
  962. }
  963. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  964. return TryResolveTypedInst(inst);
  965. }
  966. case CARBON_KIND(SemIR::InterfaceType inst): {
  967. return TryResolveTypedInst(inst);
  968. }
  969. case CARBON_KIND(SemIR::IntLiteral inst): {
  970. return TryResolveTypedInst(inst);
  971. }
  972. case CARBON_KIND(SemIR::PointerType inst): {
  973. return TryResolveTypedInst(inst);
  974. }
  975. case CARBON_KIND(SemIR::StructType inst): {
  976. return TryResolveTypedInst(inst, inst_id);
  977. }
  978. case CARBON_KIND(SemIR::StructValue inst): {
  979. return TryResolveTypedInst(inst);
  980. }
  981. case CARBON_KIND(SemIR::TupleType inst): {
  982. return TryResolveTypedInst(inst);
  983. }
  984. case CARBON_KIND(SemIR::TupleValue inst): {
  985. return TryResolveTypedInst(inst);
  986. }
  987. case CARBON_KIND(SemIR::UnboundElementType inst): {
  988. return TryResolveTypedInst(inst);
  989. }
  990. default:
  991. context_.TODO(
  992. SemIR::LocId(AddImportIRInst(inst_id)),
  993. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  994. return {.const_id = SemIR::ConstantId::Error};
  995. }
  996. }
  997. // Produces a resolve result that tries resolving this instruction again. If
  998. // `const_id` is specified, then this is the end of the second phase, and the
  999. // constant value will be passed to the next resolution attempt. Otherwise,
  1000. // this is the end of the first phase.
  1001. auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  1002. -> ResolveResult {
  1003. CARBON_CHECK(HasNewWork());
  1004. return {.const_id = const_id, .retry = true};
  1005. }
  1006. // Produces a resolve result that provides the given constant value. Requires
  1007. // that there is no new work.
  1008. auto ResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  1009. CARBON_CHECK(!HasNewWork());
  1010. return {.const_id = const_id};
  1011. }
  1012. // Produces a resolve result that provides the given constant value. Retries
  1013. // instead if work has been added.
  1014. auto RetryOrResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  1015. if (HasNewWork()) {
  1016. return Retry();
  1017. }
  1018. return ResolveAsConstant(const_id);
  1019. }
  1020. // Produces a resolve result for the given instruction that describes a
  1021. // constant value. This should only be used for instructions that describe
  1022. // constants, and not for instructions that represent declarations. For a
  1023. // declaration, we need an associated location, so AddInstInNoBlock should be
  1024. // used instead. Requires that there is no new work.
  1025. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  1026. CARBON_CHECK(!HasNewWork());
  1027. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  1028. CARBON_CHECK(result.is_constant(), "{0} is not constant", inst);
  1029. return {.const_id = result};
  1030. }
  1031. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1032. template <typename InstT>
  1033. auto ResolveAs(InstT inst) -> ResolveResult {
  1034. return ResolveAsUntyped(inst);
  1035. }
  1036. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  1037. auto type_const_id = GetLocalConstantId(inst.type_id);
  1038. if (HasNewWork()) {
  1039. return Retry();
  1040. }
  1041. // Add a lazy reference to the target declaration.
  1042. auto decl_id = AddImportRef(
  1043. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  1044. SemIR::EntityNameId::Invalid);
  1045. return ResolveAs<SemIR::AssociatedEntity>(
  1046. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1047. .index = inst.index,
  1048. .decl_id = decl_id});
  1049. }
  1050. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  1051. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1052. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  1053. auto interface_inst_id = GetLocalConstantId(inst.interface_type_id);
  1054. if (HasNewWork()) {
  1055. return Retry();
  1056. }
  1057. return ResolveAs<SemIR::AssociatedEntityType>(
  1058. {.type_id = SemIR::TypeId::TypeType,
  1059. .interface_type_id =
  1060. context_.GetTypeIdForTypeConstant(interface_inst_id),
  1061. .entity_type_id =
  1062. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  1063. }
  1064. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  1065. -> ResolveResult {
  1066. auto type_const_id = GetLocalConstantId(inst.type_id);
  1067. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  1068. if (HasNewWork()) {
  1069. return Retry();
  1070. }
  1071. // Import the instruction in order to update contained base_type_id and
  1072. // track the import location.
  1073. auto inst_id = context_.AddInstInNoBlock(
  1074. context_.MakeImportedLocAndInst<SemIR::BaseDecl>(
  1075. AddImportIRInst(import_inst_id),
  1076. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1077. .base_type_id =
  1078. context_.GetTypeIdForTypeConstant(base_type_const_id),
  1079. .index = inst.index}));
  1080. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  1081. }
  1082. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  1083. auto value_id = GetLocalConstantId(inst.value_id);
  1084. return RetryOrResolveAsConstant(value_id);
  1085. }
  1086. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  1087. auto type_id = GetLocalConstantId(inst.type_id);
  1088. if (HasNewWork()) {
  1089. return Retry();
  1090. }
  1091. const auto& import_entity_name =
  1092. import_ir_.entity_names().Get(inst.entity_name_id);
  1093. auto name_id = GetLocalNameId(import_entity_name.name_id);
  1094. auto entity_name_id = context_.entity_names().Add(
  1095. {.name_id = name_id,
  1096. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1097. .bind_index = import_entity_name.bind_index});
  1098. return ResolveAs<SemIR::BindSymbolicName>(
  1099. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1100. .entity_name_id = entity_name_id,
  1101. .value_id = SemIR::InstId::Invalid});
  1102. }
  1103. // Makes an incomplete class. This is necessary even with classes with a
  1104. // complete declaration, because things such as `Self` may refer back to the
  1105. // type.
  1106. auto MakeIncompleteClass(const SemIR::Class& import_class,
  1107. SemIR::SpecificId enclosing_specific_id)
  1108. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1109. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  1110. .class_id = SemIR::ClassId::Invalid,
  1111. .decl_block_id = SemIR::InstBlockId::Empty};
  1112. auto class_decl_id =
  1113. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1114. AddImportIRInst(import_class.latest_decl_id()), class_decl));
  1115. // Regardless of whether ClassDecl is a complete type, we first need an
  1116. // incomplete type so that any references have something to point at.
  1117. class_decl.class_id = context_.classes().Add(
  1118. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  1119. {.self_type_id = SemIR::TypeId::Invalid,
  1120. .inheritance_kind = import_class.inheritance_kind}});
  1121. if (import_class.has_parameters()) {
  1122. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id,
  1123. enclosing_specific_id);
  1124. }
  1125. // Write the class ID into the ClassDecl.
  1126. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  1127. auto self_const_id = context_.constant_values().Get(class_decl_id);
  1128. return {class_decl.class_id, self_const_id};
  1129. }
  1130. // Fills out the class definition for an incomplete class.
  1131. auto AddClassDefinition(const SemIR::Class& import_class,
  1132. SemIR::Class& new_class,
  1133. SemIR::InstId complete_type_witness_id,
  1134. SemIR::InstId base_id) -> void {
  1135. new_class.definition_id = new_class.first_owning_decl_id;
  1136. new_class.complete_type_witness_id = complete_type_witness_id;
  1137. new_class.scope_id = context_.name_scopes().Add(
  1138. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1139. new_class.parent_scope_id);
  1140. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  1141. const auto& import_scope =
  1142. import_ir_.name_scopes().Get(import_class.scope_id);
  1143. // Push a block so that we can add scoped instructions to it.
  1144. context_.inst_block_stack().Push();
  1145. AddNameScopeImportRefs(import_scope, new_scope);
  1146. new_class.body_block_id = context_.inst_block_stack().Pop();
  1147. if (import_class.base_id.is_valid()) {
  1148. new_class.base_id = base_id;
  1149. // Add the base scope to extended scopes.
  1150. auto base_inst_id = context_.types().GetInstId(
  1151. context_.insts()
  1152. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  1153. .base_type_id);
  1154. const auto& base_class = context_.classes().Get(
  1155. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  1156. new_scope.extended_scopes.push_back(base_class.scope_id);
  1157. }
  1158. CARBON_CHECK(new_scope.extended_scopes.size() ==
  1159. import_scope.extended_scopes.size());
  1160. }
  1161. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  1162. SemIR::ConstantId class_const_id) -> ResolveResult {
  1163. // TODO: The handling of interfaces repeats a lot with the handling of
  1164. // classes, and will likely also be repeated for named constraints and
  1165. // choice types. Factor out some of this functionality.
  1166. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  1167. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1168. if (!class_const_id.is_valid()) {
  1169. auto import_specific_id = SemIR::SpecificId::Invalid;
  1170. if (auto import_generic_class_type =
  1171. import_ir_.types().TryGetAs<SemIR::GenericClassType>(
  1172. inst.type_id)) {
  1173. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1174. }
  1175. auto specific_data = GetLocalSpecificData(import_specific_id);
  1176. if (HasNewWork()) {
  1177. // This is the end of the first phase. Don't make a new class yet if
  1178. // we already have new work.
  1179. return Retry();
  1180. }
  1181. // On the second phase, create a forward declaration of the class for any
  1182. // recursive references.
  1183. auto enclosing_specific_id =
  1184. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1185. std::tie(class_id, class_const_id) =
  1186. MakeIncompleteClass(import_class, enclosing_specific_id);
  1187. } else {
  1188. // On the third phase, compute the class ID from the constant
  1189. // value of the declaration.
  1190. auto class_const_inst = context_.insts().Get(
  1191. context_.constant_values().GetInstId(class_const_id));
  1192. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1193. class_id = class_type->class_id;
  1194. } else {
  1195. auto generic_class_type =
  1196. context_.types().GetAs<SemIR::GenericClassType>(
  1197. class_const_inst.type_id());
  1198. class_id = generic_class_type.class_id;
  1199. }
  1200. }
  1201. // Load constants for the definition.
  1202. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  1203. auto implicit_param_const_ids =
  1204. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  1205. auto param_const_ids = GetLocalParamConstantIds(import_class.param_refs_id);
  1206. auto generic_data = GetLocalGenericData(import_class.generic_id);
  1207. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  1208. auto complete_type_witness_id =
  1209. import_class.complete_type_witness_id.is_valid()
  1210. ? GetLocalConstantInstId(import_class.complete_type_witness_id)
  1211. : SemIR::InstId::Invalid;
  1212. auto base_id = import_class.base_id.is_valid()
  1213. ? GetLocalConstantInstId(import_class.base_id)
  1214. : SemIR::InstId::Invalid;
  1215. if (HasNewWork()) {
  1216. return Retry(class_const_id);
  1217. }
  1218. auto& new_class = context_.classes().Get(class_id);
  1219. new_class.parent_scope_id = parent_scope_id;
  1220. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  1221. import_class.implicit_param_refs_id, implicit_param_const_ids);
  1222. new_class.param_refs_id =
  1223. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  1224. SetGenericData(import_class.generic_id, new_class.generic_id, generic_data);
  1225. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1226. if (import_class.is_defined()) {
  1227. AddClassDefinition(import_class, new_class, complete_type_witness_id,
  1228. base_id);
  1229. }
  1230. return ResolveAsConstant(class_const_id);
  1231. }
  1232. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  1233. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1234. auto class_const_id = GetLocalConstantId(
  1235. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1236. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1237. if (HasNewWork()) {
  1238. return Retry();
  1239. }
  1240. // Find the corresponding class type. For a non-generic class, this is the
  1241. // type of the class declaration. For a generic class, build a class type
  1242. // referencing this specialization of the generic class.
  1243. auto class_const_inst = context_.insts().Get(
  1244. context_.constant_values().GetInstId(class_const_id));
  1245. if (class_const_inst.Is<SemIR::ClassType>()) {
  1246. return ResolveAsConstant(class_const_id);
  1247. } else {
  1248. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  1249. class_const_inst.type_id());
  1250. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1251. return ResolveAs<SemIR::ClassType>(
  1252. {.type_id = SemIR::TypeId::TypeType,
  1253. .class_id = generic_class_type.class_id,
  1254. .specific_id = specific_id});
  1255. }
  1256. }
  1257. auto TryResolveTypedInst(SemIR::CompleteTypeWitness inst) -> ResolveResult {
  1258. CARBON_CHECK(import_ir_.types().GetInstId(inst.type_id) ==
  1259. SemIR::InstId::BuiltinWitnessType);
  1260. auto object_repr_const_id = GetLocalConstantId(inst.object_repr_id);
  1261. if (HasNewWork()) {
  1262. return Retry();
  1263. }
  1264. auto object_repr_id =
  1265. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  1266. return ResolveAs<SemIR::CompleteTypeWitness>(
  1267. {.type_id =
  1268. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1269. .object_repr_id = object_repr_id});
  1270. }
  1271. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  1272. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1273. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  1274. if (HasNewWork()) {
  1275. return Retry();
  1276. }
  1277. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  1278. return ResolveAs<SemIR::ConstType>(
  1279. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  1280. }
  1281. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  1282. auto value_id = GetLocalConstantId(inst.value_id);
  1283. return RetryOrResolveAsConstant(value_id);
  1284. }
  1285. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  1286. -> ResolveResult {
  1287. auto const_id = GetLocalConstantId(inst.type_id);
  1288. if (HasNewWork()) {
  1289. return Retry();
  1290. }
  1291. auto inst_id = context_.AddInstInNoBlock(
  1292. context_.MakeImportedLocAndInst<SemIR::FieldDecl>(
  1293. AddImportIRInst(import_inst_id),
  1294. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1295. .name_id = GetLocalNameId(inst.name_id),
  1296. .index = inst.index}));
  1297. return {.const_id = context_.constant_values().Get(inst_id)};
  1298. }
  1299. // Make a declaration of a function. This is done as a separate step from
  1300. // importing the function declaration in order to resolve cycles.
  1301. auto MakeFunctionDecl(const SemIR::Function& import_function,
  1302. SemIR::SpecificId specific_id)
  1303. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1304. SemIR::FunctionDecl function_decl = {
  1305. .type_id = SemIR::TypeId::Invalid,
  1306. .function_id = SemIR::FunctionId::Invalid,
  1307. .decl_block_id = SemIR::InstBlockId::Empty};
  1308. auto function_decl_id =
  1309. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1310. AddImportIRInst(import_function.first_decl_id()), function_decl));
  1311. // Start with an incomplete function.
  1312. function_decl.function_id = context_.functions().Add(
  1313. {GetIncompleteLocalEntityBase(function_decl_id, import_function),
  1314. {.return_storage_id = SemIR::InstId::Invalid,
  1315. .builtin_function_kind = import_function.builtin_function_kind}});
  1316. function_decl.type_id =
  1317. context_.GetFunctionType(function_decl.function_id, specific_id);
  1318. // Write the function ID and type into the FunctionDecl.
  1319. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1320. return {function_decl.function_id,
  1321. context_.constant_values().Get(function_decl_id)};
  1322. }
  1323. auto TryResolveTypedInst(SemIR::FunctionDecl inst,
  1324. SemIR::ConstantId function_const_id)
  1325. -> ResolveResult {
  1326. const auto& import_function = import_ir_.functions().Get(inst.function_id);
  1327. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1328. if (!function_const_id.is_valid()) {
  1329. auto import_specific_id = import_ir_.types()
  1330. .GetAs<SemIR::FunctionType>(inst.type_id)
  1331. .specific_id;
  1332. auto specific_data = GetLocalSpecificData(import_specific_id);
  1333. if (HasNewWork()) {
  1334. // This is the end of the first phase. Don't make a new function yet if
  1335. // we already have new work.
  1336. return Retry();
  1337. }
  1338. // On the second phase, create a forward declaration of the interface.
  1339. auto specific_id =
  1340. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1341. std::tie(function_id, function_const_id) =
  1342. MakeFunctionDecl(import_function, specific_id);
  1343. } else {
  1344. // On the third phase, compute the function ID from the constant value of
  1345. // the declaration.
  1346. auto function_const_inst = context_.insts().Get(
  1347. context_.constant_values().GetInstId(function_const_id));
  1348. auto function_type = context_.types().GetAs<SemIR::FunctionType>(
  1349. function_const_inst.type_id());
  1350. function_id = function_type.function_id;
  1351. }
  1352. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1353. if (import_function.return_storage_id.is_valid()) {
  1354. return_type_const_id = GetLocalConstantId(
  1355. import_ir_.insts().Get(import_function.return_storage_id).type_id());
  1356. }
  1357. auto parent_scope_id = GetLocalNameScopeId(import_function.parent_scope_id);
  1358. auto implicit_param_const_ids =
  1359. GetLocalParamConstantIds(import_function.implicit_param_refs_id);
  1360. auto param_const_ids =
  1361. GetLocalParamConstantIds(import_function.param_refs_id);
  1362. auto generic_data = GetLocalGenericData(import_function.generic_id);
  1363. if (HasNewWork()) {
  1364. return Retry(function_const_id);
  1365. }
  1366. // Add the function declaration.
  1367. auto& new_function = context_.functions().Get(function_id);
  1368. new_function.parent_scope_id = parent_scope_id;
  1369. new_function.implicit_param_refs_id = GetLocalParamRefsId(
  1370. import_function.implicit_param_refs_id, implicit_param_const_ids);
  1371. new_function.param_refs_id =
  1372. GetLocalParamRefsId(import_function.param_refs_id, param_const_ids);
  1373. SetGenericData(import_function.generic_id, new_function.generic_id,
  1374. generic_data);
  1375. if (import_function.return_storage_id.is_valid()) {
  1376. // Recreate the return slot from scratch.
  1377. // TODO: Once we import function definitions, we'll need to make sure we
  1378. // use the same return storage variable in the declaration and definition.
  1379. new_function.return_storage_id =
  1380. context_.AddInstInNoBlock<SemIR::VarStorage>(
  1381. AddImportIRInst(import_function.return_storage_id),
  1382. {.type_id =
  1383. context_.GetTypeIdForTypeConstant(return_type_const_id),
  1384. .name_id = SemIR::NameId::ReturnSlot});
  1385. }
  1386. if (import_function.definition_id.is_valid()) {
  1387. new_function.definition_id = new_function.first_owning_decl_id;
  1388. }
  1389. return ResolveAsConstant(function_const_id);
  1390. }
  1391. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1392. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1393. auto fn_val_id = GetLocalConstantInstId(
  1394. import_ir_.functions().Get(inst.function_id).first_decl_id());
  1395. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1396. if (HasNewWork()) {
  1397. return Retry();
  1398. }
  1399. auto fn_type_id = context_.insts().Get(fn_val_id).type_id();
  1400. return ResolveAs<SemIR::FunctionType>(
  1401. {.type_id = SemIR::TypeId::TypeType,
  1402. .function_id = context_.types()
  1403. .GetAs<SemIR::FunctionType>(fn_type_id)
  1404. .function_id,
  1405. .specific_id =
  1406. GetOrAddLocalSpecific(inst.specific_id, specific_data)});
  1407. }
  1408. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1409. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1410. auto class_val_id = GetLocalConstantInstId(
  1411. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1412. if (HasNewWork()) {
  1413. return Retry();
  1414. }
  1415. auto class_val = context_.insts().Get(class_val_id);
  1416. CARBON_CHECK(
  1417. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1418. return ResolveAsConstant(
  1419. context_.types().GetConstantId(class_val.type_id()));
  1420. }
  1421. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1422. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1423. auto interface_val_id = GetLocalConstantInstId(
  1424. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1425. if (HasNewWork()) {
  1426. return Retry();
  1427. }
  1428. auto interface_val = context_.insts().Get(interface_val_id);
  1429. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1430. interface_val.type_id()));
  1431. return ResolveAsConstant(
  1432. context_.types().GetConstantId(interface_val.type_id()));
  1433. }
  1434. // Forms a constant ID that represents the given instruction ID that denotes
  1435. // an impl declaration. Impl declarations don't have a constant value, but for
  1436. // the purposes of importing we pretend that they do.
  1437. //
  1438. // TODO: Consider alternative options here. We could make impl declarations
  1439. // actually evaluate to themselves to avoid this hack.
  1440. static auto ImplDeclIdAsConstantId(SemIR::InstId impl_decl_id)
  1441. -> SemIR::ConstantId {
  1442. return SemIR::ConstantId::ForTemplateConstant(impl_decl_id);
  1443. }
  1444. // Gets the instruction ID for an impl declaration represented by the
  1445. // specified constant ID.
  1446. auto ConstantIdAsImplDeclId(SemIR::ConstantId impl_const_id)
  1447. -> SemIR::InstId {
  1448. return context_.constant_values().GetInstId(impl_const_id);
  1449. }
  1450. // Make a declaration of an impl. This is done as a separate step from
  1451. // importing the impl definition in order to resolve cycles.
  1452. auto MakeImplDeclaration(const SemIR::Impl& import_impl)
  1453. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1454. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::Invalid,
  1455. .decl_block_id = SemIR::InstBlockId::Empty};
  1456. auto impl_decl_id =
  1457. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1458. AddImportIRInst(import_impl.latest_decl_id()), impl_decl));
  1459. impl_decl.impl_id = context_.impls().Add(
  1460. {GetIncompleteLocalEntityBase(impl_decl_id, import_impl),
  1461. {.self_id = SemIR::TypeId::Invalid,
  1462. .constraint_id = SemIR::TypeId::Invalid,
  1463. .witness_id = SemIR::InstId::Invalid}});
  1464. // Write the impl ID into the ImplDecl.
  1465. context_.ReplaceInstBeforeConstantUse(impl_decl_id, impl_decl);
  1466. return {impl_decl.impl_id, ImplDeclIdAsConstantId(impl_decl_id)};
  1467. }
  1468. // Imports the definition of an impl.
  1469. auto AddImplDefinition(const SemIR::Impl& import_impl, SemIR::Impl& new_impl,
  1470. SemIR::InstId witness_id) -> void {
  1471. new_impl.definition_id = new_impl.first_owning_decl_id;
  1472. new_impl.witness_id = witness_id;
  1473. // Import the definition scope, if we might need it. Name lookup is never
  1474. // performed into this scope by a user of the impl, so this is only
  1475. // necessary in the same library that defined the impl, in order to support
  1476. // defining members of the impl out of line in the impl file when the impl
  1477. // is defined in the API file.
  1478. if (import_ir_id_ == SemIR::ImportIRId::ApiForImpl) {
  1479. new_impl.scope_id = context_.name_scopes().Add(
  1480. new_impl.first_owning_decl_id, SemIR::NameId::Invalid,
  1481. new_impl.parent_scope_id);
  1482. auto& new_scope = context_.name_scopes().Get(new_impl.scope_id);
  1483. const auto& import_scope =
  1484. import_ir_.name_scopes().Get(import_impl.scope_id);
  1485. // Push a block so that we can add scoped instructions to it.
  1486. context_.inst_block_stack().Push();
  1487. AddNameScopeImportRefs(import_scope, new_scope);
  1488. new_impl.body_block_id = context_.inst_block_stack().Pop();
  1489. }
  1490. }
  1491. auto TryResolveTypedInst(SemIR::ImplDecl inst,
  1492. SemIR::ConstantId impl_const_id) -> ResolveResult {
  1493. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1494. // functions. Factor out the commonality.
  1495. const auto& import_impl = import_ir_.impls().Get(inst.impl_id);
  1496. SemIR::ImplId impl_id = SemIR::ImplId::Invalid;
  1497. if (!impl_const_id.is_valid()) {
  1498. if (HasNewWork()) {
  1499. // This is the end of the first phase. Don't make a new impl yet if we
  1500. // already have new work.
  1501. return Retry();
  1502. }
  1503. // On the second phase, create a forward declaration of the impl for any
  1504. // recursive references.
  1505. std::tie(impl_id, impl_const_id) = MakeImplDeclaration(import_impl);
  1506. } else {
  1507. // On the third phase, compute the impl ID from the "constant value" of
  1508. // the declaration, which is a reference to the created ImplDecl.
  1509. auto impl_const_inst = context_.insts().GetAs<SemIR::ImplDecl>(
  1510. context_.constant_values().GetInstId(impl_const_id));
  1511. impl_id = impl_const_inst.impl_id;
  1512. }
  1513. // Load constants for the definition.
  1514. auto parent_scope_id = GetLocalNameScopeId(import_impl.parent_scope_id);
  1515. auto implicit_param_const_ids =
  1516. GetLocalParamConstantIds(import_impl.implicit_param_refs_id);
  1517. auto generic_data = GetLocalGenericData(import_impl.generic_id);
  1518. auto self_const_id = GetLocalConstantId(import_impl.self_id);
  1519. auto constraint_const_id = GetLocalConstantId(import_impl.constraint_id);
  1520. if (HasNewWork()) {
  1521. return Retry(impl_const_id);
  1522. }
  1523. auto& new_impl = context_.impls().Get(impl_id);
  1524. new_impl.parent_scope_id = parent_scope_id;
  1525. new_impl.implicit_param_refs_id = GetLocalParamRefsId(
  1526. import_impl.implicit_param_refs_id, implicit_param_const_ids);
  1527. CARBON_CHECK(!import_impl.param_refs_id.is_valid() &&
  1528. !new_impl.param_refs_id.is_valid());
  1529. SetGenericData(import_impl.generic_id, new_impl.generic_id, generic_data);
  1530. new_impl.self_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1531. new_impl.constraint_id =
  1532. context_.GetTypeIdForTypeConstant(constraint_const_id);
  1533. if (import_impl.is_defined()) {
  1534. auto witness_id = AddImportRef(
  1535. context_, {.ir_id = import_ir_id_, .inst_id = import_impl.witness_id},
  1536. SemIR::EntityNameId::Invalid);
  1537. AddImplDefinition(import_impl, new_impl, witness_id);
  1538. }
  1539. // If the `impl` is declared in the API file corresponding to the current
  1540. // file, add this to impl lookup so that it can be found by redeclarations
  1541. // in the current file.
  1542. if (import_ir_id_ == SemIR::ImportIRId::ApiForImpl) {
  1543. context_.impls()
  1544. .GetOrAddLookupBucket(new_impl.self_id, new_impl.constraint_id)
  1545. .push_back(impl_id);
  1546. }
  1547. return ResolveAsConstant(impl_const_id);
  1548. }
  1549. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1550. SemIR::InstId inst_id) -> ResolveResult {
  1551. // Return the constant for the instruction of the imported constant.
  1552. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1553. if (!constant_id.is_valid()) {
  1554. return ResolveAsConstant(SemIR::ConstantId::Error);
  1555. }
  1556. if (!constant_id.is_constant()) {
  1557. context_.TODO(inst_id,
  1558. "Non-constant ImportRefLoaded (comes up with var)");
  1559. return ResolveAsConstant(SemIR::ConstantId::Error);
  1560. }
  1561. auto new_constant_id =
  1562. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1563. return RetryOrResolveAsConstant(new_constant_id);
  1564. }
  1565. // Make a declaration of an interface. This is done as a separate step from
  1566. // importing the interface definition in order to resolve cycles.
  1567. auto MakeInterfaceDecl(const SemIR::Interface& import_interface,
  1568. SemIR::SpecificId enclosing_specific_id)
  1569. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1570. SemIR::InterfaceDecl interface_decl = {
  1571. .type_id = SemIR::TypeId::TypeType,
  1572. .interface_id = SemIR::InterfaceId::Invalid,
  1573. .decl_block_id = SemIR::InstBlockId::Empty};
  1574. auto interface_decl_id =
  1575. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1576. AddImportIRInst(import_interface.first_owning_decl_id),
  1577. interface_decl));
  1578. // Start with an incomplete interface.
  1579. interface_decl.interface_id = context_.interfaces().Add(
  1580. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1581. {}});
  1582. if (import_interface.has_parameters()) {
  1583. interface_decl.type_id = context_.GetGenericInterfaceType(
  1584. interface_decl.interface_id, enclosing_specific_id);
  1585. }
  1586. // Write the interface ID into the InterfaceDecl.
  1587. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1588. return {interface_decl.interface_id,
  1589. context_.constant_values().Get(interface_decl_id)};
  1590. }
  1591. // Imports the definition for an interface that has been imported as a forward
  1592. // declaration.
  1593. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1594. SemIR::Interface& new_interface,
  1595. SemIR::InstId self_param_id) -> void {
  1596. new_interface.scope_id = context_.name_scopes().Add(
  1597. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1598. new_interface.parent_scope_id);
  1599. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1600. const auto& import_scope =
  1601. import_ir_.name_scopes().Get(import_interface.scope_id);
  1602. // Push a block so that we can add scoped instructions to it.
  1603. context_.inst_block_stack().Push();
  1604. AddNameScopeImportRefs(import_scope, new_scope);
  1605. new_interface.associated_entities_id =
  1606. AddAssociatedEntities(import_interface.associated_entities_id);
  1607. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1608. new_interface.self_param_id = self_param_id;
  1609. CARBON_CHECK(import_scope.extended_scopes.empty(),
  1610. "Interfaces don't currently have extended scopes to support.");
  1611. }
  1612. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1613. SemIR::ConstantId interface_const_id)
  1614. -> ResolveResult {
  1615. const auto& import_interface =
  1616. import_ir_.interfaces().Get(inst.interface_id);
  1617. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1618. if (!interface_const_id.is_valid()) {
  1619. auto import_specific_id = SemIR::SpecificId::Invalid;
  1620. if (auto import_generic_interface_type =
  1621. import_ir_.types().TryGetAs<SemIR::GenericInterfaceType>(
  1622. inst.type_id)) {
  1623. import_specific_id =
  1624. import_generic_interface_type->enclosing_specific_id;
  1625. }
  1626. auto specific_data = GetLocalSpecificData(import_specific_id);
  1627. if (HasNewWork()) {
  1628. // This is the end of the first phase. Don't make a new interface yet if
  1629. // we already have new work.
  1630. return Retry();
  1631. }
  1632. // On the second phase, create a forward declaration of the interface.
  1633. auto enclosing_specific_id =
  1634. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1635. std::tie(interface_id, interface_const_id) =
  1636. MakeInterfaceDecl(import_interface, enclosing_specific_id);
  1637. } else {
  1638. // On the third phase, compute the interface ID from the constant value of
  1639. // the declaration.
  1640. auto interface_const_inst = context_.insts().Get(
  1641. context_.constant_values().GetInstId(interface_const_id));
  1642. if (auto interface_type =
  1643. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1644. interface_id = interface_type->interface_id;
  1645. } else {
  1646. auto generic_interface_type =
  1647. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1648. interface_const_inst.type_id());
  1649. interface_id = generic_interface_type.interface_id;
  1650. }
  1651. }
  1652. auto parent_scope_id =
  1653. GetLocalNameScopeId(import_interface.parent_scope_id);
  1654. auto implicit_param_const_ids =
  1655. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1656. auto param_const_ids =
  1657. GetLocalParamConstantIds(import_interface.param_refs_id);
  1658. auto generic_data = GetLocalGenericData(import_interface.generic_id);
  1659. std::optional<SemIR::InstId> self_param_id;
  1660. if (import_interface.is_defined()) {
  1661. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1662. }
  1663. if (HasNewWork()) {
  1664. return Retry(interface_const_id);
  1665. }
  1666. auto& new_interface = context_.interfaces().Get(interface_id);
  1667. new_interface.parent_scope_id = parent_scope_id;
  1668. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1669. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1670. new_interface.param_refs_id =
  1671. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1672. SetGenericData(import_interface.generic_id, new_interface.generic_id,
  1673. generic_data);
  1674. if (import_interface.is_defined()) {
  1675. CARBON_CHECK(self_param_id);
  1676. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1677. }
  1678. return ResolveAsConstant(interface_const_id);
  1679. }
  1680. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1681. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1682. auto interface_const_id = GetLocalConstantId(
  1683. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1684. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1685. if (HasNewWork()) {
  1686. return Retry();
  1687. }
  1688. // Find the corresponding interface type. For a non-generic interface, this
  1689. // is the type of the interface declaration. For a generic interface, build
  1690. // a interface type referencing this specialization of the generic
  1691. // interface.
  1692. auto interface_const_inst = context_.insts().Get(
  1693. context_.constant_values().GetInstId(interface_const_id));
  1694. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1695. return ResolveAsConstant(interface_const_id);
  1696. } else {
  1697. auto generic_interface_type =
  1698. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1699. interface_const_inst.type_id());
  1700. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1701. return ResolveAs<SemIR::InterfaceType>(
  1702. {.type_id = SemIR::TypeId::TypeType,
  1703. .interface_id = generic_interface_type.interface_id,
  1704. .specific_id = specific_id});
  1705. }
  1706. }
  1707. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1708. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1709. if (HasNewWork()) {
  1710. return Retry();
  1711. }
  1712. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1713. return ResolveAs<SemIR::InterfaceWitness>(
  1714. {.type_id =
  1715. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1716. .elements_id = elements_id});
  1717. }
  1718. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1719. auto type_id = GetLocalConstantId(inst.type_id);
  1720. if (HasNewWork()) {
  1721. return Retry();
  1722. }
  1723. return ResolveAs<SemIR::IntLiteral>(
  1724. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1725. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1726. }
  1727. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1728. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1729. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1730. if (HasNewWork()) {
  1731. return Retry();
  1732. }
  1733. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1734. return ResolveAs<SemIR::PointerType>(
  1735. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1736. }
  1737. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1738. -> ResolveResult {
  1739. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1740. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1741. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1742. field_const_ids.reserve(orig_fields.size());
  1743. for (auto field_id : orig_fields) {
  1744. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1745. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1746. }
  1747. if (HasNewWork()) {
  1748. return Retry();
  1749. }
  1750. // Prepare a vector of fields for GetStructType.
  1751. // TODO: Should we have field constants so that we can deduplicate fields
  1752. // without creating instructions here?
  1753. llvm::SmallVector<SemIR::InstId> fields;
  1754. fields.reserve(orig_fields.size());
  1755. for (auto [field_id, field_const_id] :
  1756. llvm::zip(orig_fields, field_const_ids)) {
  1757. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1758. auto name_id = GetLocalNameId(field.name_id);
  1759. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1760. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1761. AddImportIRInst(import_inst_id),
  1762. {.name_id = name_id, .field_type_id = field_type_id}));
  1763. }
  1764. return ResolveAs<SemIR::StructType>(
  1765. {.type_id = SemIR::TypeId::TypeType,
  1766. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1767. }
  1768. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1769. auto type_id = GetLocalConstantId(inst.type_id);
  1770. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1771. if (HasNewWork()) {
  1772. return Retry();
  1773. }
  1774. return ResolveAs<SemIR::StructValue>(
  1775. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1776. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1777. }
  1778. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1779. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1780. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1781. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1782. elem_const_ids.reserve(orig_elem_type_ids.size());
  1783. for (auto elem_type_id : orig_elem_type_ids) {
  1784. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1785. }
  1786. if (HasNewWork()) {
  1787. return Retry();
  1788. }
  1789. // Prepare a vector of the tuple types for GetTupleType.
  1790. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1791. elem_type_ids.reserve(orig_elem_type_ids.size());
  1792. for (auto elem_const_id : elem_const_ids) {
  1793. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1794. }
  1795. return ResolveAsConstant(
  1796. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids)));
  1797. }
  1798. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1799. auto type_id = GetLocalConstantId(inst.type_id);
  1800. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1801. if (HasNewWork()) {
  1802. return Retry();
  1803. }
  1804. return ResolveAs<SemIR::TupleValue>(
  1805. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1806. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1807. }
  1808. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1809. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1810. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1811. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1812. if (HasNewWork()) {
  1813. return Retry();
  1814. }
  1815. return ResolveAs<SemIR::UnboundElementType>(
  1816. {.type_id = SemIR::TypeId::TypeType,
  1817. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1818. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1819. }
  1820. // Perform any work that we deferred until the end of the main Resolve loop.
  1821. auto PerformPendingWork() -> void {
  1822. // Note that the individual Finish steps can add new pending work, so keep
  1823. // going until we have no more work to do.
  1824. while (!pending_generics_.empty() || !pending_specifics_.empty()) {
  1825. // Process generics in the order that we added them because a later
  1826. // generic might refer to an earlier one, and the calls to
  1827. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  1828. // state.
  1829. // TODO: Import the generic eval block rather than calling
  1830. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  1831. // NOLINTNEXTLINE(modernize-loop-convert)
  1832. for (size_t i = 0; i != pending_generics_.size(); ++i) {
  1833. FinishPendingGeneric(pending_generics_[i]);
  1834. }
  1835. pending_generics_.clear();
  1836. while (!pending_specifics_.empty()) {
  1837. FinishPendingSpecific(pending_specifics_.pop_back_val());
  1838. }
  1839. }
  1840. }
  1841. // Resolves and returns the local contents for an imported instruction block
  1842. // of constant instructions.
  1843. auto ResolveLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  1844. -> llvm::SmallVector<SemIR::InstId> {
  1845. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  1846. llvm::SmallVector<SemIR::InstId> inst_ids;
  1847. inst_ids.reserve(import_block.size());
  1848. for (auto import_inst_id : import_block) {
  1849. inst_ids.push_back(
  1850. context_.constant_values().GetInstId(ResolveOneInst(import_inst_id)));
  1851. }
  1852. return inst_ids;
  1853. }
  1854. // Resolves and returns a local eval block for a region of an imported
  1855. // generic.
  1856. auto ResolveLocalEvalBlock(const SemIR::Generic& import_generic,
  1857. SemIR::GenericId generic_id,
  1858. SemIR::GenericInstIndex::Region region)
  1859. -> SemIR::InstBlockId {
  1860. auto import_block_id = import_generic.GetEvalBlock(region);
  1861. if (!import_block_id.is_valid()) {
  1862. return SemIR::InstBlockId::Invalid;
  1863. }
  1864. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1865. return RebuildGenericEvalBlock(context_, generic_id, region, inst_ids);
  1866. }
  1867. // Fills in the remaining information in a partially-imported generic.
  1868. auto FinishPendingGeneric(PendingGeneric pending) -> void {
  1869. const auto& import_generic = import_ir_.generics().Get(pending.import_id);
  1870. // Don't store the local generic between calls: the generics list can be
  1871. // reallocated by ResolveLocalEvalBlock importing more specifics.
  1872. auto decl_block_id =
  1873. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1874. SemIR::GenericInstIndex::Region::Declaration);
  1875. context_.generics().Get(pending.local_id).decl_block_id = decl_block_id;
  1876. auto self_specific_id = MakeSelfSpecific(context_, pending.local_id);
  1877. context_.generics().Get(pending.local_id).self_specific_id =
  1878. self_specific_id;
  1879. pending_specifics_.push_back({.import_id = import_generic.self_specific_id,
  1880. .local_id = self_specific_id});
  1881. auto definition_block_id =
  1882. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1883. SemIR::GenericInstIndex::Region::Definition);
  1884. context_.generics().Get(pending.local_id).definition_block_id =
  1885. definition_block_id;
  1886. }
  1887. // Resolves and returns a local inst block of constant instructions
  1888. // corresponding to an imported inst block.
  1889. auto ResolveLocalInstBlock(SemIR::InstBlockId import_block_id)
  1890. -> SemIR::InstBlockId {
  1891. if (!import_block_id.is_valid()) {
  1892. return SemIR::InstBlockId::Invalid;
  1893. }
  1894. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1895. return context_.inst_blocks().Add(inst_ids);
  1896. }
  1897. // Fills in the remaining information in a partially-imported specific.
  1898. auto FinishPendingSpecific(PendingSpecific pending) -> void {
  1899. const auto& import_specific = import_ir_.specifics().Get(pending.import_id);
  1900. // Don't store the local specific between calls: the specifics list can be
  1901. // reallocated by ResolveLocalInstBlock importing more specifics.
  1902. if (!context_.specifics().Get(pending.local_id).decl_block_id.is_valid()) {
  1903. auto decl_block_id = ResolveLocalInstBlock(import_specific.decl_block_id);
  1904. context_.specifics().Get(pending.local_id).decl_block_id = decl_block_id;
  1905. }
  1906. if (!context_.specifics()
  1907. .Get(pending.local_id)
  1908. .definition_block_id.is_valid() &&
  1909. import_specific.definition_block_id.is_valid()) {
  1910. auto definition_block_id =
  1911. ResolveLocalInstBlock(import_specific.definition_block_id);
  1912. context_.specifics().Get(pending.local_id).definition_block_id =
  1913. definition_block_id;
  1914. }
  1915. }
  1916. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1917. return context_.import_ir_constant_values()[import_ir_id_.index];
  1918. }
  1919. Context& context_;
  1920. SemIR::ImportIRId import_ir_id_;
  1921. const SemIR::File& import_ir_;
  1922. llvm::SmallVector<Work> work_stack_;
  1923. // The size of work_stack_ at the start of resolving the current instruction.
  1924. size_t initial_work_ = 0;
  1925. // Generics that we have partially imported but not yet finished importing.
  1926. llvm::SmallVector<PendingGeneric> pending_generics_;
  1927. // Specifics that we have partially imported but not yet finished importing.
  1928. llvm::SmallVector<PendingSpecific> pending_specifics_;
  1929. };
  1930. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1931. // loaded (including the one pointed at directly by the ImportRef), and the
  1932. // final instruction's type ID.
  1933. //
  1934. // This addresses cases where an ImportRefUnloaded may point at another
  1935. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1936. // constant-evaluated version of the instruction to work with.
  1937. static auto GetInstForLoad(Context& context,
  1938. SemIR::ImportIRInstId import_ir_inst_id)
  1939. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1940. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1941. {}, SemIR::TypeId::Invalid};
  1942. auto& [import_ir_insts, type_id] = result;
  1943. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1944. // The first ImportIRInst is added directly because the IR doesn't need to be
  1945. // localized.
  1946. import_ir_insts.push_back(import_ir_inst);
  1947. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1948. while (true) {
  1949. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1950. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1951. if (!import_ref) {
  1952. type_id = cursor_inst.type_id();
  1953. return result;
  1954. }
  1955. import_ir_inst =
  1956. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1957. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1958. import_ir_insts.push_back(
  1959. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1960. .is_export = false,
  1961. .sem_ir = cursor_ir}),
  1962. .inst_id = import_ir_inst.inst_id});
  1963. }
  1964. }
  1965. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1966. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1967. if (!inst) {
  1968. return;
  1969. }
  1970. auto [indirect_insts, load_type_id] =
  1971. GetInstForLoad(context, inst->import_ir_inst_id);
  1972. // The last indirect instruction is the one to resolve. Pop it here because
  1973. // Resolve will assign the constant.
  1974. auto load_ir_inst = indirect_insts.pop_back_val();
  1975. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1976. // The resolver calls into Context to create instructions. Don't register
  1977. // those instructions as part of the enclosing generic scope if they're
  1978. // dependent on a generic parameter.
  1979. context.generic_region_stack().Push();
  1980. auto type_id = resolver.ResolveType(load_type_id);
  1981. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1982. context.generic_region_stack().Pop();
  1983. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1984. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1985. // TryEvalInst, which we want to avoid with ImportRefs.
  1986. context.sem_ir().insts().Set(
  1987. inst_id,
  1988. SemIR::ImportRefLoaded{.type_id = type_id,
  1989. .import_ir_inst_id = inst->import_ir_inst_id,
  1990. .entity_name_id = inst->entity_name_id});
  1991. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1992. context.constant_values().Set(inst_id, constant_id);
  1993. for (const auto& import_ir_inst : indirect_insts) {
  1994. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1995. import_ir_inst.inst_id, constant_id);
  1996. }
  1997. }
  1998. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1999. // and this file elsewhere.
  2000. auto ImportImpls(Context& context) -> void {
  2001. for (auto [import_index, import_ir] :
  2002. llvm::enumerate(context.import_irs().array_ref())) {
  2003. if (!import_ir.sem_ir) {
  2004. continue;
  2005. }
  2006. SemIR::ImportIRId import_ir_id(import_index);
  2007. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  2008. SemIR::ImplId impl_id(impl_index);
  2009. // Resolve the imported impl to a local impl ID.
  2010. ImportRefResolver resolver(context, import_ir_id);
  2011. resolver.Resolve(import_ir.sem_ir->impls().Get(impl_id).first_decl_id());
  2012. }
  2013. }
  2014. }
  2015. } // namespace Carbon::Check