import_ref.cpp 139 KB

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