import_ref.cpp 132 KB

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