import_ref.cpp 90 KB

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