import_ref.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Adds the ImportIR, excluding the update to the check_ir_map.
  20. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  21. -> SemIR::ImportIRId {
  22. context.import_ir_constant_values().push_back(
  23. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  24. return context.import_irs().Add(import_ir);
  25. }
  26. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  27. auto ir_id = SemIR::ImportIRId::Invalid;
  28. if (import_ir.sem_ir != nullptr) {
  29. ir_id = AddImportIR(context, import_ir);
  30. } else {
  31. // We don't have a check_ir_id, so add without touching check_ir_map.
  32. ir_id = InternalAddImportIR(context, import_ir);
  33. }
  34. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl)
  35. << "ApiForImpl must be the first IR";
  36. }
  37. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  38. -> SemIR::ImportIRId {
  39. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  40. if (!ir_id.is_valid()) {
  41. // Note this updates check_ir_map.
  42. ir_id = InternalAddImportIR(context, import_ir);
  43. } else if (import_ir.is_export) {
  44. // We're processing an `export import`. In case the IR was indirectly added
  45. // as a non-export, mark it as an export.
  46. context.import_irs().Get(ir_id).is_export = true;
  47. }
  48. return ir_id;
  49. }
  50. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  51. SemIR::EntityNameId entity_name_id) -> SemIR::InstId {
  52. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  53. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  54. .entity_name_id = entity_name_id};
  55. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  56. SemIR::LocIdAndInst(import_ir_inst_id, inst));
  57. // ImportRefs have a dedicated block because this may be called during
  58. // processing where the instruction shouldn't be inserted in the current inst
  59. // block.
  60. context.import_ref_ids().push_back(import_ref_id);
  61. return import_ref_id;
  62. }
  63. auto GetCanonicalImportIRInst(Context& context, const SemIR::File* cursor_ir,
  64. SemIR::InstId cursor_inst_id)
  65. -> SemIR::ImportIRInst {
  66. while (true) {
  67. auto inst = cursor_ir->insts().Get(cursor_inst_id);
  68. CARBON_KIND_SWITCH(inst) {
  69. case CARBON_KIND(SemIR::ExportDecl bind_export): {
  70. cursor_inst_id = bind_export.value_id;
  71. continue;
  72. }
  73. case SemIR::ImportRefLoaded::Kind:
  74. case SemIR::ImportRefUnloaded::Kind: {
  75. auto import_ref = inst.As<SemIR::AnyImportRef>();
  76. auto import_ir_inst =
  77. cursor_ir->import_ir_insts().Get(import_ref.import_ir_inst_id);
  78. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  79. cursor_inst_id = import_ir_inst.inst_id;
  80. continue;
  81. }
  82. default: {
  83. auto ir_id = SemIR::ImportIRId::Invalid;
  84. if (cursor_ir != &context.sem_ir()) {
  85. // This uses AddImportIR in case it was indirectly found, which can
  86. // happen with two or more steps of exports.
  87. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  88. .is_export = false,
  89. .sem_ir = cursor_ir});
  90. }
  91. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  92. }
  93. }
  94. }
  95. }
  96. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  97. SemIR::ImportIRInst prev_import_ir_inst,
  98. SemIR::ImportIRId new_ir_id,
  99. const SemIR::File* new_import_ir,
  100. SemIR::InstId new_inst_id) -> void {
  101. auto new_import_ir_inst =
  102. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  103. if (new_import_ir_inst == prev_import_ir_inst) {
  104. return;
  105. }
  106. auto conflict_id =
  107. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id},
  108. SemIR::EntityNameId::Invalid);
  109. context.DiagnoseDuplicateName(conflict_id, prev_id);
  110. }
  111. // Resolves an instruction from an imported IR into a constant referring to the
  112. // current IR.
  113. //
  114. // Calling Resolve on an instruction operates in an iterative manner, tracking
  115. // Work items on work_stack_. At a high level, the loop is:
  116. //
  117. // 1. If a constant value is already known for the work item, and we're
  118. // processing it for the first time, it's considered resolved.
  119. // - The constant check avoids performance costs of deduplication on add.
  120. // - If `retry` is set, we process it again, because it didn't complete last
  121. // time, even though we have a constant value already.
  122. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  123. // - For instructions that can be forward declared, if we don't already have
  124. // a constant value from a previous attempt at resolution, start by making
  125. // a forward declared constant value to address circular references.
  126. // - Gather all input constants.
  127. // - Gathering constants directly adds unresolved values to work_stack_.
  128. // - If any need to be resolved (HasNewWork), return Retry(): this
  129. // instruction needs two calls to complete.
  130. // - If the constant value is already known because we have made a forward
  131. // declaration, pass it to Retry(). It will be passed to future attempts
  132. // to resolve this instruction so the earlier work can be found, and will
  133. // be made available for other instructions to use.
  134. // - The second attempt to resolve this instruction must produce the same
  135. // constant, because the value may have already been used by resolved
  136. // instructions.
  137. // - Build any necessary IR structures, and return the output constant.
  138. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  139. // remain, and may no longer be at the top of the stack; set `retry` on it so
  140. // we'll make sure to run it again later.
  141. //
  142. // TryResolveInst/TryResolveTypedInst can complete in one call for a given
  143. // instruction, but should always complete within two calls. However, due to the
  144. // chance of a second call, it's important to reserve all expensive logic until
  145. // it's been established that input constants are available; this in particular
  146. // includes GetTypeIdForTypeConstant calls which do a hash table lookup.
  147. //
  148. // TODO: Fix class `extern` handling and merging, rewrite tests.
  149. // - check/testdata/class/cross_package_import.carbon
  150. // - check/testdata/class/extern.carbon
  151. // TODO: Fix function `extern` handling and merging, rewrite tests.
  152. // - check/testdata/function/declaration/import.carbon
  153. // - check/testdata/packages/cross_package_import.carbon
  154. class ImportRefResolver {
  155. public:
  156. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  157. : context_(context),
  158. import_ir_id_(import_ir_id),
  159. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  160. // Iteratively resolves an imported instruction's inner references until a
  161. // constant ID referencing the current IR is produced. See the class comment
  162. // for more details.
  163. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  164. work_stack_.push_back({.inst_id = inst_id});
  165. while (!work_stack_.empty()) {
  166. auto work = work_stack_.back();
  167. CARBON_CHECK(work.inst_id.is_valid());
  168. // Step 1: check for a constant value.
  169. auto existing = FindResolvedConstId(work.inst_id);
  170. if (existing.const_id.is_valid() && !work.retry) {
  171. work_stack_.pop_back();
  172. continue;
  173. }
  174. // Step 2: resolve the instruction.
  175. auto initial_work = work_stack_.size();
  176. auto [new_const_id, finished] =
  177. TryResolveInst(work.inst_id, existing.const_id);
  178. CARBON_CHECK(finished == !HasNewWork(initial_work));
  179. CARBON_CHECK(!existing.const_id.is_valid() ||
  180. existing.const_id == new_const_id)
  181. << "Constant value changed in second pass.";
  182. if (!existing.const_id.is_valid()) {
  183. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  184. }
  185. // Step 3: pop or retry.
  186. if (finished) {
  187. work_stack_.pop_back();
  188. } else {
  189. work_stack_[initial_work - 1].retry = true;
  190. }
  191. }
  192. auto constant_id = import_ir_constant_values().Get(inst_id);
  193. CARBON_CHECK(constant_id.is_valid());
  194. return constant_id;
  195. }
  196. // Wraps constant evaluation with logic to handle types.
  197. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  198. if (!import_type_id.is_valid()) {
  199. return import_type_id;
  200. }
  201. auto import_type_inst_id = import_ir_.types().GetInstId(import_type_id);
  202. CARBON_CHECK(import_type_inst_id.is_valid());
  203. if (import_type_inst_id.is_builtin()) {
  204. // Builtins don't require constant resolution; we can use them directly.
  205. return context_.GetBuiltinType(import_type_inst_id.builtin_inst_kind());
  206. } else {
  207. return context_.GetTypeIdForTypeConstant(Resolve(import_type_inst_id));
  208. }
  209. }
  210. private:
  211. // A step in work_stack_.
  212. struct Work {
  213. // The instruction to work on.
  214. SemIR::InstId inst_id;
  215. // True if another pass was requested last time this was run.
  216. bool retry = false;
  217. };
  218. // The result of attempting to resolve an imported instruction to a constant.
  219. struct ResolveResult {
  220. // Try resolving this function again. If `const_id` is specified, it will be
  221. // passed to the next resolution attempt.
  222. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  223. -> ResolveResult {
  224. return {.const_id = const_id, .finished = false};
  225. }
  226. // The new constant value, if known.
  227. SemIR::ConstantId const_id;
  228. // Whether resolution has finished. If false, `TryResolveInst` will be
  229. // called again. Note that this is not strictly necessary, and we can get
  230. // the same information by checking whether new work was added to the stack.
  231. // However, we use this for consistency checks between resolve actions and
  232. // the work stack.
  233. bool finished = true;
  234. };
  235. // The constant found by FindResolvedConstId.
  236. struct ResolvedConstId {
  237. // The constant for the instruction. Invalid if not yet resolved.
  238. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  239. // Instructions which are indirect but equivalent to the current instruction
  240. // being resolved, and should have their constant set to the same. Empty
  241. // when const_id is valid.
  242. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  243. };
  244. // Local information associated with an imported generic.
  245. struct GenericData {
  246. llvm::SmallVector<SemIR::InstId> bindings;
  247. // TODO: Add data for the self specific.
  248. llvm::SmallVector<SemIR::InstId> decl_block;
  249. llvm::SmallVector<SemIR::InstId> definition_block;
  250. };
  251. // Local information associated with an imported specific.
  252. struct SpecificData {
  253. SemIR::ConstantId generic_const_id;
  254. llvm::SmallVector<SemIR::InstId> args;
  255. llvm::SmallVector<SemIR::InstId> decl_block;
  256. llvm::SmallVector<SemIR::InstId> definition_block;
  257. };
  258. // Looks to see if an instruction has been resolved. If a constant is only
  259. // found indirectly, sets the constant for any indirect steps that don't
  260. // already have the constant. If a constant isn't found, returns the indirect
  261. // instructions so that they can have the resolved constant assigned later.
  262. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  263. ResolvedConstId result;
  264. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  265. existing_const_id.is_valid()) {
  266. result.const_id = existing_const_id;
  267. return result;
  268. }
  269. const auto* cursor_ir = &import_ir_;
  270. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  271. auto cursor_inst_id = inst_id;
  272. while (true) {
  273. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  274. if (!loc_id.is_import_ir_inst_id()) {
  275. return result;
  276. }
  277. auto ir_inst =
  278. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  279. const auto* prev_ir = cursor_ir;
  280. auto prev_inst_id = cursor_inst_id;
  281. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  282. cursor_ir_id = context_.GetImportIRId(*cursor_ir);
  283. if (!cursor_ir_id.is_valid()) {
  284. // TODO: Should we figure out a location to assign here?
  285. cursor_ir_id = AddImportIR(context_, {.decl_id = SemIR::InstId::Invalid,
  286. .is_export = false,
  287. .sem_ir = cursor_ir});
  288. }
  289. cursor_inst_id = ir_inst.inst_id;
  290. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id)
  291. << cursor_ir->insts().Get(cursor_inst_id);
  292. if (auto const_id =
  293. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  294. cursor_inst_id);
  295. const_id.is_valid()) {
  296. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  297. result.const_id = const_id;
  298. result.indirect_insts.clear();
  299. return result;
  300. } else {
  301. result.indirect_insts.push_back(
  302. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  303. }
  304. }
  305. }
  306. // Sets a resolved constant into the current and indirect instructions.
  307. auto SetResolvedConstId(SemIR::InstId inst_id,
  308. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  309. SemIR::ConstantId const_id) -> void {
  310. import_ir_constant_values().Set(inst_id, const_id);
  311. for (auto indirect_inst : indirect_insts) {
  312. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  313. indirect_inst.inst_id, const_id);
  314. }
  315. }
  316. // Returns true if new unresolved constants were found.
  317. //
  318. // At the start of a function, do:
  319. // auto initial_work = work_stack_.size();
  320. // Then when determining:
  321. // if (HasNewWork(initial_work)) { ... }
  322. auto HasNewWork(size_t initial_work) -> bool {
  323. CARBON_CHECK(initial_work <= work_stack_.size())
  324. << "Work shouldn't decrease";
  325. return initial_work < work_stack_.size();
  326. }
  327. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  328. return context_.import_ir_insts().Add(
  329. {.ir_id = import_ir_id_, .inst_id = inst_id});
  330. }
  331. // Returns the ConstantId for an InstId. Adds unresolved constants to
  332. // work_stack_.
  333. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  334. auto const_id = import_ir_constant_values().Get(inst_id);
  335. if (!const_id.is_valid()) {
  336. work_stack_.push_back({.inst_id = inst_id});
  337. }
  338. return const_id;
  339. }
  340. // Returns the local constant InstId for an imported InstId.
  341. auto GetLocalConstantInstId(SemIR::InstId inst_id) -> SemIR::InstId {
  342. auto const_id = import_ir_constant_values().Get(inst_id);
  343. if (!const_id.is_valid()) {
  344. work_stack_.push_back({.inst_id = inst_id});
  345. return SemIR::InstId::Invalid;
  346. }
  347. return context_.constant_values().GetInstId(const_id);
  348. }
  349. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  350. // work_stack_.
  351. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  352. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  353. }
  354. // Gets the local constant values corresponding to an imported inst block.
  355. auto GetLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  356. -> llvm::SmallVector<SemIR::InstId> {
  357. llvm::SmallVector<SemIR::InstId> inst_ids;
  358. if (!import_block_id.is_valid() ||
  359. import_block_id == SemIR::InstBlockId::Empty) {
  360. return inst_ids;
  361. }
  362. // Import all the values in the block.
  363. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  364. inst_ids.reserve(import_block.size());
  365. for (auto import_inst_id : import_block) {
  366. auto const_id = GetLocalConstantId(import_inst_id);
  367. inst_ids.push_back(context_.constant_values().GetInstIdIfValid(const_id));
  368. }
  369. return inst_ids;
  370. }
  371. // Gets a local instruction block ID corresponding to an imported inst block
  372. // whose contents were already imported, for example by
  373. // GetLocalInstBlockContents.
  374. auto GetLocalInstBlockId(SemIR::InstBlockId import_block_id,
  375. llvm::ArrayRef<SemIR::InstId> contents)
  376. -> SemIR::InstBlockId {
  377. if (!import_block_id.is_valid()) {
  378. return SemIR::InstBlockId::Invalid;
  379. }
  380. return context_.inst_blocks().Add(contents);
  381. }
  382. // Gets a local canonical instruction block ID corresponding to an imported
  383. // inst block whose contents were already imported, for example by
  384. // GetLocalInstBlockContents.
  385. auto GetLocalCanonicalInstBlockId(SemIR::InstBlockId import_block_id,
  386. llvm::ArrayRef<SemIR::InstId> contents)
  387. -> SemIR::InstBlockId {
  388. if (!import_block_id.is_valid()) {
  389. return SemIR::InstBlockId::Invalid;
  390. }
  391. return context_.inst_blocks().AddCanonical(contents);
  392. }
  393. // Gets an incomplete local version of an imported generic. Most fields are
  394. // set in the second pass.
  395. auto MakeIncompleteGeneric(SemIR::InstId decl_id, SemIR::GenericId generic_id)
  396. -> SemIR::GenericId {
  397. if (!generic_id.is_valid()) {
  398. return SemIR::GenericId::Invalid;
  399. }
  400. return context_.generics().Add(
  401. {.decl_id = decl_id,
  402. .bindings_id = SemIR::InstBlockId::Invalid,
  403. .self_specific_id = SemIR::SpecificId::Invalid});
  404. }
  405. // Gets a local version of the data associated with a generic.
  406. auto GetLocalGenericData(SemIR::GenericId generic_id) -> GenericData {
  407. if (!generic_id.is_valid()) {
  408. return GenericData();
  409. }
  410. const auto& generic = import_ir_.generics().Get(generic_id);
  411. return {
  412. .bindings = GetLocalInstBlockContents(generic.bindings_id),
  413. .decl_block = GetLocalInstBlockContents(generic.decl_block_id),
  414. .definition_block =
  415. GetLocalInstBlockContents(generic.definition_block_id),
  416. };
  417. }
  418. // Given the local constant values for the elements of the eval block, builds
  419. // and returns the eval block for a region of a generic.
  420. auto GetLocalEvalBlock(const SemIR::Generic& import_generic,
  421. SemIR::GenericId generic_id,
  422. SemIR::GenericInstIndex::Region region,
  423. llvm::ArrayRef<SemIR::InstId> inst_ids)
  424. -> SemIR::InstBlockId {
  425. auto import_block_id = import_generic.GetEvalBlock(region);
  426. if (!import_block_id.is_valid()) {
  427. return SemIR::InstBlockId::Invalid;
  428. }
  429. return RebuildGenericEvalBlock(context_, generic_id, region, inst_ids);
  430. }
  431. // Adds the given local generic data to the given generic.
  432. auto SetGenericData(SemIR::GenericId import_generic_id,
  433. SemIR::GenericId new_generic_id,
  434. const GenericData& generic_data) -> void {
  435. if (!import_generic_id.is_valid()) {
  436. return;
  437. }
  438. const auto& import_generic = import_ir_.generics().Get(import_generic_id);
  439. auto& new_generic = context_.generics().Get(new_generic_id);
  440. new_generic.bindings_id = GetLocalCanonicalInstBlockId(
  441. import_generic.bindings_id, generic_data.bindings);
  442. // TODO: Import or rebuild the self specific.
  443. new_generic.decl_block_id = GetLocalEvalBlock(
  444. import_generic, new_generic_id,
  445. SemIR::GenericInstIndex::Region::Declaration, generic_data.decl_block);
  446. new_generic.definition_block_id =
  447. GetLocalEvalBlock(import_generic, new_generic_id,
  448. SemIR::GenericInstIndex::Region::Definition,
  449. generic_data.definition_block);
  450. }
  451. // Gets a local constant value corresponding to an imported generic ID. May
  452. // add work to the work stack and return `Invalid`.
  453. auto GetLocalConstantId(SemIR::GenericId generic_id) -> SemIR::ConstantId {
  454. if (!generic_id.is_valid()) {
  455. return SemIR::ConstantId::Invalid;
  456. }
  457. return GetLocalConstantId(
  458. import_ir_.insts()
  459. .Get(import_ir_.generics().Get(generic_id).decl_id)
  460. .type_id());
  461. }
  462. // Gets a local generic ID given the corresponding local constant ID returned
  463. // by GetLocalConstantId for the imported generic. Does not add any new work.
  464. auto GetLocalGenericId(SemIR::ConstantId local_const_id) -> SemIR::GenericId {
  465. if (!local_const_id.is_valid()) {
  466. return SemIR::GenericId::Invalid;
  467. }
  468. auto type = context_.insts().Get(
  469. context_.constant_values().GetInstId(local_const_id));
  470. CARBON_KIND_SWITCH(type) {
  471. case CARBON_KIND(SemIR::FunctionType fn_type): {
  472. return context_.functions().Get(fn_type.function_id).generic_id;
  473. }
  474. case CARBON_KIND(SemIR::GenericClassType class_type): {
  475. return context_.classes().Get(class_type.class_id).generic_id;
  476. }
  477. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  478. return context_.interfaces()
  479. .Get(interface_type.interface_id)
  480. .generic_id;
  481. }
  482. default: {
  483. CARBON_FATAL() << "Unexpected type for generic declaration: " << type;
  484. }
  485. }
  486. }
  487. // Gets local information about an imported specific.
  488. auto GetLocalSpecificData(SemIR::SpecificId specific_id) -> SpecificData {
  489. if (!specific_id.is_valid()) {
  490. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  491. }
  492. const auto& specific = import_ir_.specifics().Get(specific_id);
  493. return {
  494. .generic_const_id = GetLocalConstantId(specific.generic_id),
  495. .args = GetLocalInstBlockContents(specific.args_id),
  496. .decl_block = GetLocalInstBlockContents(specific.decl_block_id),
  497. .definition_block =
  498. GetLocalInstBlockContents(specific.definition_block_id),
  499. };
  500. }
  501. // Gets a local specific whose data was already imported by
  502. // GetLocalSpecificData. Does not add any new work.
  503. auto GetOrAddLocalSpecific(SemIR::SpecificId import_specific_id,
  504. const SpecificData& data) -> SemIR::SpecificId {
  505. if (!import_specific_id.is_valid()) {
  506. return SemIR::SpecificId::Invalid;
  507. }
  508. // Form a corresponding local specific ID.
  509. const auto& import_specific =
  510. import_ir_.specifics().Get(import_specific_id);
  511. auto generic_id = GetLocalGenericId(data.generic_const_id);
  512. auto args_id =
  513. GetLocalCanonicalInstBlockId(import_specific.args_id, data.args);
  514. // Populate the specific. Note that we might get data from multiple
  515. // different import IRs, so only import data we don't already have.
  516. auto specific_id = context_.specifics().GetOrAdd(generic_id, args_id);
  517. auto& specific = context_.specifics().Get(specific_id);
  518. if (!specific.decl_block_id.is_valid()) {
  519. specific.decl_block_id =
  520. GetLocalInstBlockId(import_specific.decl_block_id, data.decl_block);
  521. }
  522. if (!specific.definition_block_id.is_valid()) {
  523. specific.definition_block_id = GetLocalInstBlockId(
  524. import_specific.definition_block_id, data.definition_block);
  525. }
  526. return specific_id;
  527. }
  528. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  529. // to work_stack_.
  530. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  531. -> llvm::SmallVector<SemIR::ConstantId> {
  532. llvm::SmallVector<SemIR::ConstantId> const_ids;
  533. if (!param_refs_id.is_valid() ||
  534. param_refs_id == SemIR::InstBlockId::Empty) {
  535. return const_ids;
  536. }
  537. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  538. const_ids.reserve(param_refs.size());
  539. for (auto inst_id : param_refs) {
  540. const_ids.push_back(
  541. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  542. // If the parameter is a symbolic binding, build the BindSymbolicName
  543. // constant.
  544. auto bind_id = inst_id;
  545. if (auto addr =
  546. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  547. bind_id = addr->inner_id;
  548. }
  549. GetLocalConstantId(bind_id);
  550. }
  551. return const_ids;
  552. }
  553. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  554. // a version of param_refs_id localized to the current IR.
  555. auto GetLocalParamRefsId(
  556. SemIR::InstBlockId param_refs_id,
  557. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  558. -> SemIR::InstBlockId {
  559. if (!param_refs_id.is_valid() ||
  560. param_refs_id == SemIR::InstBlockId::Empty) {
  561. return param_refs_id;
  562. }
  563. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  564. llvm::SmallVector<SemIR::InstId> new_param_refs;
  565. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  566. // Figure out the param structure. This echoes
  567. // Function::GetParamFromParamRefId.
  568. // TODO: Consider a different parameter handling to simplify import logic.
  569. auto inst = import_ir_.insts().Get(ref_id);
  570. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  571. auto bind_id = ref_id;
  572. auto param_id = ref_id;
  573. if (addr_inst) {
  574. bind_id = addr_inst->inner_id;
  575. param_id = bind_id;
  576. inst = import_ir_.insts().Get(bind_id);
  577. }
  578. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  579. if (bind_inst) {
  580. param_id = bind_inst->value_id;
  581. inst = import_ir_.insts().Get(param_id);
  582. }
  583. auto param_inst = inst.As<SemIR::Param>();
  584. // Rebuild the param instruction.
  585. auto name_id = GetLocalNameId(param_inst.name_id);
  586. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  587. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  588. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  589. if (bind_inst) {
  590. switch (bind_inst->kind) {
  591. case SemIR::BindName::Kind: {
  592. auto entity_name_id = context_.entity_names().Add(
  593. {.name_id = name_id,
  594. .parent_scope_id = SemIR::NameScopeId::Invalid,
  595. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  596. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  597. AddImportIRInst(bind_id), {.type_id = type_id,
  598. .entity_name_id = entity_name_id,
  599. .value_id = new_param_id});
  600. break;
  601. }
  602. case SemIR::BindSymbolicName::Kind: {
  603. // We already imported a constant value for this symbolic binding.
  604. // We can reuse most of it.
  605. auto new_bind_inst_id = GetLocalConstantInstId(bind_id);
  606. auto new_bind_inst =
  607. context_.insts().GetAs<SemIR::BindSymbolicName>(
  608. new_bind_inst_id);
  609. new_bind_inst.value_id = new_param_id;
  610. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  611. new_bind_inst);
  612. break;
  613. }
  614. default: {
  615. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  616. }
  617. }
  618. }
  619. if (addr_inst) {
  620. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  621. AddImportIRInst(ref_id),
  622. {.type_id = type_id, .inner_id = new_param_id});
  623. }
  624. new_param_refs.push_back(new_param_id);
  625. }
  626. return context_.inst_blocks().Add(new_param_refs);
  627. }
  628. // Translates a NameId from the import IR to a local NameId.
  629. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  630. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  631. return SemIR::NameId::ForIdentifier(
  632. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  633. }
  634. return import_name_id;
  635. }
  636. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  637. // unresolved constants to the work stack.
  638. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  639. -> SemIR::NameScopeId {
  640. // Get the instruction that created the scope.
  641. auto [inst_id, inst] =
  642. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  643. if (!inst) {
  644. // Map scopes that aren't associated with an instruction to invalid
  645. // scopes. For now, such scopes aren't used, and we don't have a good way
  646. // to remap them.
  647. return SemIR::NameScopeId::Invalid;
  648. }
  649. // Get the constant value for the scope.
  650. auto const_id = SemIR::ConstantId::Invalid;
  651. CARBON_KIND_SWITCH(*inst) {
  652. case SemIR::ImplDecl::Kind:
  653. // TODO: Import the scope for an `impl` definition.
  654. return SemIR::NameScopeId::Invalid;
  655. case SemIR::Namespace::Kind:
  656. // If the namespace has already been imported, we can use its constant.
  657. // However, if it hasn't, we use Invalid instead of adding it to the
  658. // work stack. That's expected to be okay when resolving references.
  659. const_id = import_ir_constant_values().Get(inst_id);
  660. break;
  661. default:
  662. const_id = GetLocalConstantId(inst_id);
  663. }
  664. if (!const_id.is_valid()) {
  665. return SemIR::NameScopeId::Invalid;
  666. }
  667. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  668. auto name_scope_inst = context_.insts().Get(const_inst_id);
  669. CARBON_KIND_SWITCH(name_scope_inst) {
  670. case CARBON_KIND(SemIR::Namespace inst): {
  671. return inst.name_scope_id;
  672. }
  673. case CARBON_KIND(SemIR::ClassType inst): {
  674. return context_.classes().Get(inst.class_id).scope_id;
  675. }
  676. case CARBON_KIND(SemIR::InterfaceType inst): {
  677. return context_.interfaces().Get(inst.interface_id).scope_id;
  678. }
  679. case SemIR::StructValue::Kind: {
  680. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  681. CARBON_KIND_SWITCH(type_inst) {
  682. case CARBON_KIND(SemIR::GenericClassType inst): {
  683. return context_.classes().Get(inst.class_id).scope_id;
  684. }
  685. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  686. return context_.interfaces().Get(inst.interface_id).scope_id;
  687. }
  688. default: {
  689. break;
  690. }
  691. }
  692. break;
  693. }
  694. default: {
  695. if (const_inst_id == SemIR::InstId::BuiltinError) {
  696. return SemIR::NameScopeId::Invalid;
  697. }
  698. break;
  699. }
  700. }
  701. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  702. << name_scope_inst;
  703. }
  704. // Given an imported entity base, returns an incomplete, local version of it.
  705. //
  706. // Most fields are set in the second pass once they're imported. Import enough
  707. // of the parameter lists that we know whether this interface is a generic
  708. // interface and can build the right constant value for it.
  709. //
  710. // TODO: Add a better way to represent a generic prior to importing the
  711. // parameters.
  712. auto GetIncompleteLocalEntityBase(
  713. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  714. -> SemIR::EntityWithParamsBase {
  715. return {
  716. .name_id = GetLocalNameId(import_base.name_id),
  717. .parent_scope_id = SemIR::NameScopeId::Invalid,
  718. .generic_id = MakeIncompleteGeneric(decl_id, import_base.generic_id),
  719. .first_param_node_id = Parse::NodeId::Invalid,
  720. .last_param_node_id = Parse::NodeId::Invalid,
  721. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  722. ? SemIR::InstBlockId::Empty
  723. : SemIR::InstBlockId::Invalid,
  724. .param_refs_id = import_base.param_refs_id.is_valid()
  725. ? SemIR::InstBlockId::Empty
  726. : SemIR::InstBlockId::Invalid,
  727. .decl_id = decl_id,
  728. };
  729. }
  730. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  731. // lookup.
  732. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  733. SemIR::NameScope& new_scope) -> void {
  734. for (auto entry : import_scope.names) {
  735. auto ref_id = AddImportRef(
  736. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  737. SemIR::EntityNameId::Invalid);
  738. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  739. .inst_id = ref_id,
  740. .access_kind = entry.access_kind});
  741. }
  742. }
  743. // Given a block ID for a list of associated entities of a witness, returns a
  744. // version localized to the current IR.
  745. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  746. -> SemIR::InstBlockId {
  747. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  748. return SemIR::InstBlockId::Empty;
  749. }
  750. auto associated_entities =
  751. import_ir_.inst_blocks().Get(associated_entities_id);
  752. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  753. new_associated_entities.reserve(associated_entities.size());
  754. for (auto inst_id : associated_entities) {
  755. new_associated_entities.push_back(
  756. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  757. SemIR::EntityNameId::Invalid));
  758. }
  759. return context_.inst_blocks().Add(new_associated_entities);
  760. }
  761. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  762. // more has been added to the stack. A similar API is followed for all
  763. // following TryResolveTypedInst helper functions.
  764. //
  765. // `const_id` is Invalid unless we've tried to resolve this instruction
  766. // before, in which case it's the previous result.
  767. //
  768. // TODO: Error is returned when support is missing, but that should go away.
  769. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  770. -> ResolveResult {
  771. if (inst_id.is_builtin()) {
  772. CARBON_CHECK(!const_id.is_valid());
  773. // Constants for builtins can be directly copied.
  774. return {.const_id = context_.constant_values().Get(inst_id)};
  775. }
  776. auto untyped_inst = import_ir_.insts().Get(inst_id);
  777. CARBON_KIND_SWITCH(untyped_inst) {
  778. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  779. return TryResolveTypedInst(inst);
  780. }
  781. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  782. return TryResolveTypedInst(inst);
  783. }
  784. case CARBON_KIND(SemIR::BaseDecl inst): {
  785. return TryResolveTypedInst(inst, inst_id);
  786. }
  787. case CARBON_KIND(SemIR::BindAlias inst): {
  788. return TryResolveTypedInst(inst);
  789. }
  790. case CARBON_KIND(SemIR::BindName inst): {
  791. // TODO: This always returns `ConstantId::NotConstant`.
  792. return {.const_id = TryEvalInst(context_, inst_id, inst)};
  793. }
  794. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  795. return TryResolveTypedInst(inst);
  796. }
  797. case CARBON_KIND(SemIR::ClassDecl inst): {
  798. return TryResolveTypedInst(inst, const_id);
  799. }
  800. case CARBON_KIND(SemIR::ClassType inst): {
  801. return TryResolveTypedInst(inst);
  802. }
  803. case CARBON_KIND(SemIR::ConstType inst): {
  804. return TryResolveTypedInst(inst);
  805. }
  806. case CARBON_KIND(SemIR::ExportDecl inst): {
  807. return TryResolveTypedInst(inst);
  808. }
  809. case CARBON_KIND(SemIR::FieldDecl inst): {
  810. return TryResolveTypedInst(inst, inst_id);
  811. }
  812. case CARBON_KIND(SemIR::FunctionDecl inst): {
  813. return TryResolveTypedInst(inst);
  814. }
  815. case CARBON_KIND(SemIR::FunctionType inst): {
  816. return TryResolveTypedInst(inst);
  817. }
  818. case CARBON_KIND(SemIR::GenericClassType inst): {
  819. return TryResolveTypedInst(inst);
  820. }
  821. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  822. return TryResolveTypedInst(inst);
  823. }
  824. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  825. return TryResolveTypedInst(inst, inst_id);
  826. }
  827. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  828. return TryResolveTypedInst(inst, const_id);
  829. }
  830. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  831. return TryResolveTypedInst(inst);
  832. }
  833. case CARBON_KIND(SemIR::InterfaceType inst): {
  834. return TryResolveTypedInst(inst);
  835. }
  836. case CARBON_KIND(SemIR::IntLiteral inst): {
  837. return TryResolveTypedInst(inst);
  838. }
  839. case CARBON_KIND(SemIR::Namespace inst): {
  840. CARBON_FATAL() << "Namespaces shouldn't need resolution this way: "
  841. << inst;
  842. }
  843. case CARBON_KIND(SemIR::PointerType inst): {
  844. return TryResolveTypedInst(inst);
  845. }
  846. case CARBON_KIND(SemIR::StructType inst): {
  847. return TryResolveTypedInst(inst, inst_id);
  848. }
  849. case CARBON_KIND(SemIR::StructValue inst): {
  850. return TryResolveTypedInst(inst);
  851. }
  852. case CARBON_KIND(SemIR::TupleType inst): {
  853. return TryResolveTypedInst(inst);
  854. }
  855. case CARBON_KIND(SemIR::TupleValue inst): {
  856. return TryResolveTypedInst(inst);
  857. }
  858. case CARBON_KIND(SemIR::UnboundElementType inst): {
  859. return TryResolveTypedInst(inst);
  860. }
  861. default:
  862. context_.TODO(
  863. SemIR::LocId(AddImportIRInst(inst_id)),
  864. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  865. return {.const_id = SemIR::ConstantId::Error};
  866. }
  867. }
  868. // Produce a resolve result for the given instruction that describes a
  869. // constant value. This should only be used for instructions that describe
  870. // constants, and not for instructions that represent declarations. For a
  871. // declaration, we need an associated location, so AddInstInNoBlock should be
  872. // used instead.
  873. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  874. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  875. CARBON_CHECK(result.is_constant()) << inst << " is not constant";
  876. return {.const_id = result};
  877. }
  878. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  879. template <typename InstT>
  880. auto ResolveAs(InstT inst) -> ResolveResult {
  881. return ResolveAsUntyped(inst);
  882. }
  883. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  884. auto initial_work = work_stack_.size();
  885. auto type_const_id = GetLocalConstantId(inst.type_id);
  886. if (HasNewWork(initial_work)) {
  887. return ResolveResult::Retry();
  888. }
  889. // Add a lazy reference to the target declaration.
  890. auto decl_id = AddImportRef(
  891. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  892. SemIR::EntityNameId::Invalid);
  893. return ResolveAs<SemIR::AssociatedEntity>(
  894. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  895. .index = inst.index,
  896. .decl_id = decl_id});
  897. }
  898. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  899. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  900. auto initial_work = work_stack_.size();
  901. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  902. auto interface_inst_id = GetLocalConstantInstId(
  903. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  904. if (HasNewWork(initial_work)) {
  905. return ResolveResult::Retry();
  906. }
  907. // TODO: Track an interface type, not an interface ID, on
  908. // AssociatedEntityType.
  909. auto interface_inst = context_.insts().Get(interface_inst_id);
  910. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  911. if (interface_inst.Is<SemIR::InterfaceType>()) {
  912. interface_id = interface_inst.As<SemIR::InterfaceType>().interface_id;
  913. } else {
  914. interface_id =
  915. context_.types()
  916. .GetAs<SemIR::GenericInterfaceType>(interface_inst.type_id())
  917. .interface_id;
  918. }
  919. return ResolveAs<SemIR::AssociatedEntityType>(
  920. {.type_id = SemIR::TypeId::TypeType,
  921. .interface_id = interface_id,
  922. .entity_type_id =
  923. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  924. }
  925. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  926. -> ResolveResult {
  927. auto initial_work = work_stack_.size();
  928. auto type_const_id = GetLocalConstantId(inst.type_id);
  929. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  930. if (HasNewWork(initial_work)) {
  931. return ResolveResult::Retry();
  932. }
  933. // Import the instruction in order to update contained base_type_id and
  934. // track the import location.
  935. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  936. AddImportIRInst(import_inst_id),
  937. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  938. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  939. .index = inst.index});
  940. return {.const_id = context_.constant_values().Get(inst_id)};
  941. }
  942. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  943. auto initial_work = work_stack_.size();
  944. auto value_id = GetLocalConstantId(inst.value_id);
  945. if (HasNewWork(initial_work)) {
  946. return ResolveResult::Retry();
  947. }
  948. return {.const_id = value_id};
  949. }
  950. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  951. auto initial_work = work_stack_.size();
  952. auto type_id = GetLocalConstantId(inst.type_id);
  953. if (HasNewWork(initial_work)) {
  954. return ResolveResult::Retry();
  955. }
  956. const auto& import_entity_name =
  957. import_ir_.entity_names().Get(inst.entity_name_id);
  958. auto name_id = GetLocalNameId(import_entity_name.name_id);
  959. auto entity_name_id = context_.entity_names().Add(
  960. {.name_id = name_id,
  961. .parent_scope_id = SemIR::NameScopeId::Invalid,
  962. .bind_index = import_entity_name.bind_index});
  963. return ResolveAs<SemIR::BindSymbolicName>(
  964. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  965. .entity_name_id = entity_name_id,
  966. .value_id = SemIR::InstId::Invalid});
  967. }
  968. // Makes an incomplete class. This is necessary even with classes with a
  969. // complete declaration, because things such as `Self` may refer back to the
  970. // type.
  971. auto MakeIncompleteClass(const SemIR::Class& import_class)
  972. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  973. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  974. .class_id = SemIR::ClassId::Invalid,
  975. .decl_block_id = SemIR::InstBlockId::Empty};
  976. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  977. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  978. // Regardless of whether ClassDecl is a complete type, we first need an
  979. // incomplete type so that any references have something to point at.
  980. class_decl.class_id = context_.classes().Add(
  981. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  982. {.self_type_id = SemIR::TypeId::Invalid,
  983. .inheritance_kind = import_class.inheritance_kind}});
  984. if (import_class.is_generic()) {
  985. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  986. }
  987. // Write the class ID into the ClassDecl.
  988. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  989. auto self_const_id = context_.constant_values().Get(class_decl_id);
  990. return {class_decl.class_id, self_const_id};
  991. }
  992. // Fills out the class definition for an incomplete class.
  993. auto AddClassDefinition(const SemIR::Class& import_class,
  994. SemIR::Class& new_class,
  995. SemIR::ConstantId object_repr_const_id,
  996. SemIR::InstId base_id) -> void {
  997. new_class.definition_id = new_class.decl_id;
  998. new_class.object_repr_id =
  999. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  1000. new_class.scope_id = context_.name_scopes().Add(
  1001. new_class.decl_id, SemIR::NameId::Invalid, new_class.parent_scope_id);
  1002. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  1003. const auto& import_scope =
  1004. import_ir_.name_scopes().Get(import_class.scope_id);
  1005. // Push a block so that we can add scoped instructions to it.
  1006. context_.inst_block_stack().Push();
  1007. AddNameScopeImportRefs(import_scope, new_scope);
  1008. new_class.body_block_id = context_.inst_block_stack().Pop();
  1009. if (import_class.base_id.is_valid()) {
  1010. new_class.base_id = base_id;
  1011. // Add the base scope to extended scopes.
  1012. auto base_inst_id = context_.types().GetInstId(
  1013. context_.insts()
  1014. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  1015. .base_type_id);
  1016. const auto& base_class = context_.classes().Get(
  1017. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  1018. new_scope.extended_scopes.push_back(base_class.scope_id);
  1019. }
  1020. CARBON_CHECK(new_scope.extended_scopes.size() ==
  1021. import_scope.extended_scopes.size());
  1022. }
  1023. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  1024. SemIR::ConstantId class_const_id) -> ResolveResult {
  1025. // TODO: The handling of interfaces repeats a lot with the handling of
  1026. // classes, and will likely also be repeated for named constraints and
  1027. // choice types. Factor out some of this functionality.
  1028. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  1029. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1030. if (!class_const_id.is_valid()) {
  1031. // On the first pass, create a forward declaration of the class for any
  1032. // recursive references.
  1033. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  1034. } else {
  1035. // On the second pass, compute the class ID from the constant value of the
  1036. // declaration.
  1037. auto class_const_inst = context_.insts().Get(
  1038. context_.constant_values().GetInstId(class_const_id));
  1039. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1040. class_id = class_type->class_id;
  1041. } else {
  1042. auto generic_class_type =
  1043. context_.types().GetAs<SemIR::GenericClassType>(
  1044. class_const_inst.type_id());
  1045. class_id = generic_class_type.class_id;
  1046. }
  1047. }
  1048. // Load constants for the definition.
  1049. auto initial_work = work_stack_.size();
  1050. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  1051. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1052. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  1053. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1054. GetLocalParamConstantIds(import_class.param_refs_id);
  1055. auto generic_data = GetLocalGenericData(import_class.generic_id);
  1056. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  1057. auto object_repr_const_id =
  1058. import_class.object_repr_id.is_valid()
  1059. ? GetLocalConstantId(import_class.object_repr_id)
  1060. : SemIR::ConstantId::Invalid;
  1061. auto base_id = import_class.base_id.is_valid()
  1062. ? GetLocalConstantInstId(import_class.base_id)
  1063. : SemIR::InstId::Invalid;
  1064. if (HasNewWork(initial_work)) {
  1065. return ResolveResult::Retry(class_const_id);
  1066. }
  1067. auto& new_class = context_.classes().Get(class_id);
  1068. new_class.parent_scope_id = parent_scope_id;
  1069. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  1070. import_class.implicit_param_refs_id, implicit_param_const_ids);
  1071. new_class.param_refs_id =
  1072. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  1073. SetGenericData(import_class.generic_id, new_class.generic_id, generic_data);
  1074. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1075. if (import_class.is_defined()) {
  1076. AddClassDefinition(import_class, new_class, object_repr_const_id,
  1077. base_id);
  1078. }
  1079. return {.const_id = class_const_id};
  1080. }
  1081. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  1082. auto initial_work = work_stack_.size();
  1083. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1084. auto class_const_id =
  1085. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  1086. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1087. if (HasNewWork(initial_work)) {
  1088. return ResolveResult::Retry();
  1089. }
  1090. // Find the corresponding class type. For a non-generic class, this is the
  1091. // type of the class declaration. For a generic class, build a class type
  1092. // referencing this specialization of the generic class.
  1093. auto class_const_inst = context_.insts().Get(
  1094. context_.constant_values().GetInstId(class_const_id));
  1095. if (class_const_inst.Is<SemIR::ClassType>()) {
  1096. return {.const_id = class_const_id};
  1097. } else {
  1098. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  1099. class_const_inst.type_id());
  1100. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1101. return ResolveAs<SemIR::ClassType>(
  1102. {.type_id = SemIR::TypeId::TypeType,
  1103. .class_id = generic_class_type.class_id,
  1104. .specific_id = specific_id});
  1105. }
  1106. }
  1107. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  1108. auto initial_work = work_stack_.size();
  1109. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1110. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  1111. if (HasNewWork(initial_work)) {
  1112. return ResolveResult::Retry();
  1113. }
  1114. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  1115. return ResolveAs<SemIR::ConstType>(
  1116. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  1117. }
  1118. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  1119. auto initial_work = work_stack_.size();
  1120. auto value_id = GetLocalConstantId(inst.value_id);
  1121. if (HasNewWork(initial_work)) {
  1122. return ResolveResult::Retry();
  1123. }
  1124. return {.const_id = value_id};
  1125. }
  1126. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  1127. -> ResolveResult {
  1128. auto initial_work = work_stack_.size();
  1129. auto const_id = GetLocalConstantId(inst.type_id);
  1130. if (HasNewWork(initial_work)) {
  1131. return ResolveResult::Retry();
  1132. }
  1133. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  1134. AddImportIRInst(import_inst_id),
  1135. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1136. .name_id = GetLocalNameId(inst.name_id),
  1137. .index = inst.index});
  1138. return {.const_id = context_.constant_values().Get(inst_id)};
  1139. }
  1140. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  1141. auto initial_work = work_stack_.size();
  1142. const auto& function = import_ir_.functions().Get(inst.function_id);
  1143. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1144. if (function.return_storage_id.is_valid()) {
  1145. return_type_const_id =
  1146. GetLocalConstantId(function.GetDeclaredReturnType(import_ir_));
  1147. }
  1148. auto parent_scope_id = GetLocalNameScopeId(function.parent_scope_id);
  1149. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1150. GetLocalParamConstantIds(function.implicit_param_refs_id);
  1151. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1152. GetLocalParamConstantIds(function.param_refs_id);
  1153. auto generic_data = GetLocalGenericData(function.generic_id);
  1154. if (HasNewWork(initial_work)) {
  1155. return ResolveResult::Retry();
  1156. }
  1157. // Add the function declaration.
  1158. SemIR::FunctionDecl function_decl = {
  1159. .type_id = SemIR::TypeId::Invalid,
  1160. .function_id = SemIR::FunctionId::Invalid,
  1161. .decl_block_id = SemIR::InstBlockId::Empty};
  1162. auto import_ir_inst_id = AddImportIRInst(function.latest_decl_id());
  1163. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  1164. SemIR::LocIdAndInst(import_ir_inst_id, function_decl));
  1165. // TODO: Implement import for generics.
  1166. auto generic_id =
  1167. MakeIncompleteGeneric(function_decl_id, function.generic_id);
  1168. SetGenericData(function.generic_id, generic_id, generic_data);
  1169. auto new_return_storage = SemIR::InstId::Invalid;
  1170. if (function.return_storage_id.is_valid()) {
  1171. // Recreate the return slot from scratch.
  1172. // TODO: Once we import function definitions, we'll need to make sure we
  1173. // use the same return storage variable in the declaration and definition.
  1174. new_return_storage = context_.AddInstInNoBlock<SemIR::VarStorage>(
  1175. AddImportIRInst(function.return_storage_id),
  1176. {.type_id = context_.GetTypeIdForTypeConstant(return_type_const_id),
  1177. .name_id = SemIR::NameId::ReturnSlot});
  1178. }
  1179. function_decl.function_id = context_.functions().Add(
  1180. {{.name_id = GetLocalNameId(function.name_id),
  1181. .parent_scope_id = parent_scope_id,
  1182. .generic_id = generic_id,
  1183. .first_param_node_id = Parse::NodeId::Invalid,
  1184. .last_param_node_id = Parse::NodeId::Invalid,
  1185. .implicit_param_refs_id = GetLocalParamRefsId(
  1186. function.implicit_param_refs_id, implicit_param_const_ids),
  1187. .param_refs_id =
  1188. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  1189. .decl_id = function_decl_id,
  1190. .definition_id = function.definition_id.is_valid()
  1191. ? function_decl_id
  1192. : SemIR::InstId::Invalid},
  1193. {.return_storage_id = new_return_storage,
  1194. .is_extern = function.is_extern,
  1195. .builtin_function_kind = function.builtin_function_kind}});
  1196. // TODO: Import this or recompute it.
  1197. auto specific_id = SemIR::SpecificId::Invalid;
  1198. function_decl.type_id =
  1199. context_.GetFunctionType(function_decl.function_id, specific_id);
  1200. // Write the function ID into the FunctionDecl.
  1201. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1202. return {.const_id = context_.constant_values().Get(function_decl_id)};
  1203. }
  1204. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1205. auto initial_work = work_stack_.size();
  1206. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1207. auto fn_val_id = GetLocalConstantInstId(
  1208. import_ir_.functions().Get(inst.function_id).decl_id);
  1209. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1210. if (HasNewWork(initial_work)) {
  1211. return ResolveResult::Retry();
  1212. }
  1213. auto fn_type_id = context_.insts().Get(fn_val_id).type_id();
  1214. return ResolveAs<SemIR::FunctionType>(
  1215. {.type_id = SemIR::TypeId::TypeType,
  1216. .function_id = context_.types()
  1217. .GetAs<SemIR::FunctionType>(fn_type_id)
  1218. .function_id,
  1219. .specific_id =
  1220. GetOrAddLocalSpecific(inst.specific_id, specific_data)});
  1221. }
  1222. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1223. auto initial_work = work_stack_.size();
  1224. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1225. auto class_val_id =
  1226. GetLocalConstantInstId(import_ir_.classes().Get(inst.class_id).decl_id);
  1227. if (HasNewWork(initial_work)) {
  1228. return ResolveResult::Retry();
  1229. }
  1230. auto class_val = context_.insts().Get(class_val_id);
  1231. CARBON_CHECK(
  1232. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1233. return {.const_id = context_.types().GetConstantId(class_val.type_id())};
  1234. }
  1235. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1236. auto initial_work = work_stack_.size();
  1237. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1238. auto interface_val_id = GetLocalConstantInstId(
  1239. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1240. if (HasNewWork(initial_work)) {
  1241. return ResolveResult::Retry();
  1242. }
  1243. auto interface_val = context_.insts().Get(interface_val_id);
  1244. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1245. interface_val.type_id()));
  1246. return {.const_id =
  1247. context_.types().GetConstantId(interface_val.type_id())};
  1248. }
  1249. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1250. SemIR::InstId inst_id) -> ResolveResult {
  1251. auto initial_work = work_stack_.size();
  1252. // Return the constant for the instruction of the imported constant.
  1253. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1254. if (!constant_id.is_valid()) {
  1255. return {.const_id = SemIR::ConstantId::Error};
  1256. }
  1257. if (!constant_id.is_constant()) {
  1258. context_.TODO(inst_id,
  1259. "Non-constant ImportRefLoaded (comes up with var)");
  1260. return {.const_id = SemIR::ConstantId::Error};
  1261. }
  1262. auto new_constant_id =
  1263. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1264. if (HasNewWork(initial_work)) {
  1265. return ResolveResult::Retry();
  1266. }
  1267. return {.const_id = new_constant_id};
  1268. }
  1269. // Make a declaration of an interface. This is done as a separate step from
  1270. // importing the interface definition in order to resolve cycles.
  1271. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1272. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1273. SemIR::InterfaceDecl interface_decl = {
  1274. .type_id = SemIR::TypeId::TypeType,
  1275. .interface_id = SemIR::InterfaceId::Invalid,
  1276. .decl_block_id = SemIR::InstBlockId::Empty};
  1277. auto interface_decl_id =
  1278. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1279. AddImportIRInst(import_interface.decl_id), interface_decl));
  1280. // Start with an incomplete interface.
  1281. interface_decl.interface_id = context_.interfaces().Add(
  1282. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1283. {}});
  1284. if (import_interface.is_generic()) {
  1285. interface_decl.type_id =
  1286. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1287. }
  1288. // Write the interface ID into the InterfaceDecl.
  1289. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1290. return {interface_decl.interface_id,
  1291. context_.constant_values().Get(interface_decl_id)};
  1292. }
  1293. // Imports the definition for an interface that has been imported as a forward
  1294. // declaration.
  1295. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1296. SemIR::Interface& new_interface,
  1297. SemIR::InstId self_param_id) -> void {
  1298. new_interface.scope_id = context_.name_scopes().Add(
  1299. new_interface.decl_id, SemIR::NameId::Invalid,
  1300. new_interface.parent_scope_id);
  1301. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1302. const auto& import_scope =
  1303. import_ir_.name_scopes().Get(import_interface.scope_id);
  1304. // Push a block so that we can add scoped instructions to it.
  1305. context_.inst_block_stack().Push();
  1306. AddNameScopeImportRefs(import_scope, new_scope);
  1307. new_interface.associated_entities_id =
  1308. AddAssociatedEntities(import_interface.associated_entities_id);
  1309. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1310. new_interface.self_param_id = self_param_id;
  1311. CARBON_CHECK(import_scope.extended_scopes.empty())
  1312. << "Interfaces don't currently have extended scopes to support.";
  1313. }
  1314. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1315. SemIR::ConstantId interface_const_id)
  1316. -> ResolveResult {
  1317. const auto& import_interface =
  1318. import_ir_.interfaces().Get(inst.interface_id);
  1319. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1320. if (!interface_const_id.is_valid()) {
  1321. // On the first pass, create a forward declaration of the interface.
  1322. std::tie(interface_id, interface_const_id) =
  1323. MakeInterfaceDecl(import_interface);
  1324. } else {
  1325. // On the second pass, compute the interface ID from the constant value of
  1326. // the declaration.
  1327. auto interface_const_inst = context_.insts().Get(
  1328. context_.constant_values().GetInstId(interface_const_id));
  1329. if (auto interface_type =
  1330. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1331. interface_id = interface_type->interface_id;
  1332. } else {
  1333. auto generic_interface_type =
  1334. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1335. interface_const_inst.type_id());
  1336. interface_id = generic_interface_type.interface_id;
  1337. }
  1338. }
  1339. auto initial_work = work_stack_.size();
  1340. auto parent_scope_id =
  1341. GetLocalNameScopeId(import_interface.parent_scope_id);
  1342. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1343. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1344. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1345. GetLocalParamConstantIds(import_interface.param_refs_id);
  1346. auto generic_data = GetLocalGenericData(import_interface.generic_id);
  1347. std::optional<SemIR::InstId> self_param_id;
  1348. if (import_interface.is_defined()) {
  1349. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1350. }
  1351. if (HasNewWork(initial_work)) {
  1352. return ResolveResult::Retry(interface_const_id);
  1353. }
  1354. auto& new_interface = context_.interfaces().Get(interface_id);
  1355. new_interface.parent_scope_id = parent_scope_id;
  1356. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1357. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1358. new_interface.param_refs_id =
  1359. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1360. SetGenericData(import_interface.generic_id, new_interface.generic_id,
  1361. generic_data);
  1362. if (import_interface.is_defined()) {
  1363. CARBON_CHECK(self_param_id);
  1364. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1365. }
  1366. return {.const_id = interface_const_id};
  1367. }
  1368. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1369. auto initial_work = work_stack_.size();
  1370. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1371. auto interface_const_id = GetLocalConstantId(
  1372. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1373. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1374. if (HasNewWork(initial_work)) {
  1375. return ResolveResult::Retry();
  1376. }
  1377. // Find the corresponding interface type. For a non-generic interface, this
  1378. // is the type of the interface declaration. For a generic interface, build
  1379. // a interface type referencing this specialization of the generic
  1380. // interface.
  1381. auto interface_const_inst = context_.insts().Get(
  1382. context_.constant_values().GetInstId(interface_const_id));
  1383. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1384. return {.const_id = interface_const_id};
  1385. } else {
  1386. auto generic_interface_type =
  1387. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1388. interface_const_inst.type_id());
  1389. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1390. return ResolveAs<SemIR::InterfaceType>(
  1391. {.type_id = SemIR::TypeId::TypeType,
  1392. .interface_id = generic_interface_type.interface_id,
  1393. .specific_id = specific_id});
  1394. }
  1395. }
  1396. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1397. auto initial_work = work_stack_.size();
  1398. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1399. if (HasNewWork(initial_work)) {
  1400. return ResolveResult::Retry();
  1401. }
  1402. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1403. return ResolveAs<SemIR::InterfaceWitness>(
  1404. {.type_id =
  1405. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1406. .elements_id = elements_id});
  1407. }
  1408. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1409. auto initial_work = work_stack_.size();
  1410. auto type_id = GetLocalConstantId(inst.type_id);
  1411. if (HasNewWork(initial_work)) {
  1412. return ResolveResult::Retry();
  1413. }
  1414. return ResolveAs<SemIR::IntLiteral>(
  1415. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1416. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1417. }
  1418. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1419. auto initial_work = work_stack_.size();
  1420. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1421. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1422. if (HasNewWork(initial_work)) {
  1423. return ResolveResult::Retry();
  1424. }
  1425. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1426. return ResolveAs<SemIR::PointerType>(
  1427. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1428. }
  1429. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1430. -> ResolveResult {
  1431. // Collect all constants first, locating unresolved ones in a single pass.
  1432. auto initial_work = work_stack_.size();
  1433. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1434. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1435. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1436. field_const_ids.reserve(orig_fields.size());
  1437. for (auto field_id : orig_fields) {
  1438. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1439. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1440. }
  1441. if (HasNewWork(initial_work)) {
  1442. return ResolveResult::Retry();
  1443. }
  1444. // Prepare a vector of fields for GetStructType.
  1445. // TODO: Should we have field constants so that we can deduplicate fields
  1446. // without creating instructions here?
  1447. llvm::SmallVector<SemIR::InstId> fields;
  1448. fields.reserve(orig_fields.size());
  1449. for (auto [field_id, field_const_id] :
  1450. llvm::zip(orig_fields, field_const_ids)) {
  1451. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1452. auto name_id = GetLocalNameId(field.name_id);
  1453. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1454. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1455. AddImportIRInst(import_inst_id),
  1456. {.name_id = name_id, .field_type_id = field_type_id}));
  1457. }
  1458. return ResolveAs<SemIR::StructType>(
  1459. {.type_id = SemIR::TypeId::TypeType,
  1460. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1461. }
  1462. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1463. auto initial_work = work_stack_.size();
  1464. auto type_id = GetLocalConstantId(inst.type_id);
  1465. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1466. if (HasNewWork(initial_work)) {
  1467. return ResolveResult::Retry();
  1468. }
  1469. return ResolveAs<SemIR::StructValue>(
  1470. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1471. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1472. }
  1473. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1474. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1475. // Collect all constants first, locating unresolved ones in a single pass.
  1476. auto initial_work = work_stack_.size();
  1477. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1478. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1479. elem_const_ids.reserve(orig_elem_type_ids.size());
  1480. for (auto elem_type_id : orig_elem_type_ids) {
  1481. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1482. }
  1483. if (HasNewWork(initial_work)) {
  1484. return ResolveResult::Retry();
  1485. }
  1486. // Prepare a vector of the tuple types for GetTupleType.
  1487. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1488. elem_type_ids.reserve(orig_elem_type_ids.size());
  1489. for (auto elem_const_id : elem_const_ids) {
  1490. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1491. }
  1492. return {.const_id = context_.types().GetConstantId(
  1493. context_.GetTupleType(elem_type_ids))};
  1494. }
  1495. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1496. auto initial_work = work_stack_.size();
  1497. auto type_id = GetLocalConstantId(inst.type_id);
  1498. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1499. if (HasNewWork(initial_work)) {
  1500. return ResolveResult::Retry();
  1501. }
  1502. return ResolveAs<SemIR::TupleValue>(
  1503. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1504. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1505. }
  1506. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1507. auto initial_work = work_stack_.size();
  1508. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1509. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1510. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1511. if (HasNewWork(initial_work)) {
  1512. return ResolveResult::Retry();
  1513. }
  1514. return ResolveAs<SemIR::UnboundElementType>(
  1515. {.type_id = SemIR::TypeId::TypeType,
  1516. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1517. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1518. }
  1519. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1520. return context_.import_ir_constant_values()[import_ir_id_.index];
  1521. }
  1522. Context& context_;
  1523. SemIR::ImportIRId import_ir_id_;
  1524. const SemIR::File& import_ir_;
  1525. llvm::SmallVector<Work> work_stack_;
  1526. };
  1527. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1528. // loaded (including the one pointed at directly by the ImportRef), and the
  1529. // final instruction's type ID.
  1530. //
  1531. // This addresses cases where an ImportRefUnloaded may point at another
  1532. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1533. // constant-evaluated version of the instruction to work with.
  1534. static auto GetInstForLoad(Context& context,
  1535. SemIR::ImportIRInstId import_ir_inst_id)
  1536. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1537. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1538. {}, SemIR::TypeId::Invalid};
  1539. auto& [import_ir_insts, type_id] = result;
  1540. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1541. // The first ImportIRInst is added directly because the IR doesn't need to be
  1542. // localized.
  1543. import_ir_insts.push_back(import_ir_inst);
  1544. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1545. while (true) {
  1546. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1547. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1548. if (!import_ref) {
  1549. type_id = cursor_inst.type_id();
  1550. return result;
  1551. }
  1552. import_ir_inst =
  1553. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1554. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1555. import_ir_insts.push_back(
  1556. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1557. .is_export = false,
  1558. .sem_ir = cursor_ir}),
  1559. .inst_id = import_ir_inst.inst_id});
  1560. }
  1561. }
  1562. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1563. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1564. if (!inst) {
  1565. return;
  1566. }
  1567. auto [indirect_insts, load_type_id] =
  1568. GetInstForLoad(context, inst->import_ir_inst_id);
  1569. // The last indirect instruction is the one to resolve. Pop it here because
  1570. // Resolve will assign the constant.
  1571. auto load_ir_inst = indirect_insts.pop_back_val();
  1572. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1573. // The resolver calls into Context to create instructions. Don't register
  1574. // those instructions as part of the enclosing generic scope if they're
  1575. // dependent on a generic parameter.
  1576. context.generic_region_stack().Push();
  1577. auto type_id = resolver.ResolveType(load_type_id);
  1578. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1579. context.generic_region_stack().Pop();
  1580. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1581. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1582. // TryEvalInst, which we want to avoid with ImportRefs.
  1583. context.sem_ir().insts().Set(
  1584. inst_id,
  1585. SemIR::ImportRefLoaded{.type_id = type_id,
  1586. .import_ir_inst_id = inst->import_ir_inst_id,
  1587. .entity_name_id = inst->entity_name_id});
  1588. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1589. context.constant_values().Set(inst_id, constant_id);
  1590. for (const auto& import_ir_inst : indirect_insts) {
  1591. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1592. import_ir_inst.inst_id, constant_id);
  1593. }
  1594. }
  1595. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1596. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1597. const SemIR::File& import_ir,
  1598. SemIR::ImplId import_impl_id) -> void {
  1599. // Resolve the imported impl to a local impl ID.
  1600. ImportRefResolver resolver(context, import_ir_id);
  1601. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1602. auto self_id = resolver.ResolveType(import_impl.self_id);
  1603. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1604. // Import the definition if the impl is defined.
  1605. // TODO: Do we need to check for multiple definitions?
  1606. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1607. if (import_impl.is_defined()) {
  1608. // TODO: Create a scope for the `impl` if necessary.
  1609. // TODO: Consider importing the definition_id.
  1610. auto& impl = context.impls().Get(impl_id);
  1611. impl.witness_id = AddImportRef(
  1612. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1613. SemIR::EntityNameId::Invalid);
  1614. }
  1615. }
  1616. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1617. // and this file elsewhere.
  1618. auto ImportImpls(Context& context) -> void {
  1619. for (auto [import_index, import_ir] :
  1620. llvm::enumerate(context.import_irs().array_ref())) {
  1621. if (!import_ir.sem_ir) {
  1622. continue;
  1623. }
  1624. auto import_ir_id = SemIR::ImportIRId(import_index);
  1625. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1626. auto impl_id = SemIR::ImplId(impl_index);
  1627. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1628. }
  1629. }
  1630. }
  1631. } // namespace Carbon::Check