import_ref.cpp 133 KB

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