import_ref.cpp 118 KB

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