import_ref.cpp 85 KB

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