import_ref.cpp 101 KB

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