import_ref.cpp 92 KB

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