import_ref.cpp 141 KB

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