import_ref.cpp 143 KB

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