import_ref.cpp 103 KB

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