import_ref.cpp 142 KB

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