import_ref.cpp 139 KB

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