import_ref.cpp 77 KB

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