import_ref.cpp 130 KB

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