import_ref.cpp 112 KB

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