import_ref.cpp 153 KB

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