generic.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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/generic.h"
  5. #include <utility>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/generic_region_stack.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/subst.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/diagnostics/diagnostic.h"
  15. #include "toolchain/sem_ir/constant.h"
  16. #include "toolchain/sem_ir/generic.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. static auto MakeSelfSpecificId(Context& context, SemIR::GenericId generic_id)
  22. -> SemIR::SpecificId;
  23. // Get the current pending generic. If we have not yet allocated a `GenericId`
  24. // for it, do so now.
  25. static auto GetOrCreatePendingGeneric(Context& context)
  26. -> GenericRegionStack::PendingGeneric {
  27. auto pending_generic = context.generic_region_stack().PeekPendingGeneric();
  28. if (!pending_generic.generic_id.has_value()) {
  29. // Allocate a placeholder generic now to form a generic ID. This generic
  30. // will be populated once we reach the end of the generic declaration.
  31. pending_generic.generic_id = context.generics().Add(
  32. SemIR::Generic{.decl_id = SemIR::InstId::None,
  33. .bindings_id = SemIR::InstBlockId::None,
  34. .self_specific_id = SemIR::SpecificId::None});
  35. context.generic_region_stack().SetPendingGenericId(
  36. pending_generic.generic_id);
  37. }
  38. return pending_generic;
  39. }
  40. // Adds an instruction `generic_inst_id` to the eval block for the current
  41. // generic region. The instruction `generic_inst_id` is expected to compute the
  42. // value of the constant described by `const_inst_id` in each specific. Forms
  43. // and returns a corresponding symbolic constant ID that refers to the
  44. // substituted value of that instruction in each specific.
  45. static auto AddGenericConstantInstToEvalBlock(
  46. Context& context, SemIR::InstId const_inst_id,
  47. SemIR::InstId generic_inst_id, SemIR::ConstantDependence dependence)
  48. -> SemIR::ConstantId {
  49. auto [generic_id, region] = GetOrCreatePendingGeneric(context);
  50. auto index = SemIR::GenericInstIndex(
  51. region, context.generic_region_stack().PeekEvalBlock().size());
  52. context.generic_region_stack().AddInstToEvalBlock(generic_inst_id);
  53. return context.constant_values().AddSymbolicConstant(
  54. {.inst_id = const_inst_id,
  55. .generic_id = generic_id,
  56. .index = index,
  57. .dependence = dependence});
  58. }
  59. namespace {
  60. // Substitution callbacks to rebuild a generic constant in the eval block for a
  61. // generic region.
  62. class RebuildGenericConstantInEvalBlockCallbacks : public SubstInstCallbacks {
  63. public:
  64. // `context` must not be null.
  65. RebuildGenericConstantInEvalBlockCallbacks(Context* context,
  66. SemIR::LocId loc_id)
  67. : SubstInstCallbacks(context),
  68. loc_id_(loc_id),
  69. constants_in_generic_(
  70. context->generic_region_stack().PeekConstantsInGenericMap()) {}
  71. auto RebuildType(SemIR::TypeInstId type_inst_id) const
  72. -> SemIR::TypeId override {
  73. // When building instructions in the eval block, form attached types.
  74. return context().types().GetTypeIdForTypeConstantId(
  75. context().constant_values().GetAttached(type_inst_id));
  76. }
  77. // Check for instructions for which we already have a mapping into the eval
  78. // block, and substitute them with the instructions in the eval block.
  79. auto Subst(SemIR::InstId& inst_id) -> SubstResult override {
  80. auto const_id = context().constant_values().Get(inst_id);
  81. if (!const_id.has_value()) {
  82. // An unloaded import ref should never contain anything we need to
  83. // substitute into. Don't trigger loading it here.
  84. CARBON_CHECK(
  85. context().insts().Is<SemIR::ImportRefUnloaded>(inst_id),
  86. "Substituting into instruction with invalid constant ID: {0}",
  87. context().insts().Get(inst_id));
  88. return SubstResult::FullySubstituted;
  89. }
  90. if (!context().constant_values().DependsOnGenericParameter(const_id)) {
  91. // This instruction doesn't have a symbolic constant value, so can't
  92. // contain any bindings that need to be substituted.
  93. return SubstResult::FullySubstituted;
  94. }
  95. // If this constant value has a defining instruction in the eval block,
  96. // replace the instruction in the body of the generic with the one from the
  97. // eval block.
  98. if (auto result = constants_in_generic_.Lookup(
  99. context().constant_values().GetInstId(const_id))) {
  100. inst_id = result.value();
  101. return SubstResult::FullySubstituted;
  102. }
  103. return SubstResult::SubstOperands;
  104. }
  105. // Build a new instruction in the eval block corresponding to the given
  106. // constant.
  107. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst)
  108. -> SemIR::InstId override {
  109. auto& orig_symbolic_const = context().constant_values().GetSymbolicConstant(
  110. context().constant_values().Get(orig_inst_id));
  111. auto const_inst_id = orig_symbolic_const.inst_id;
  112. auto dependence = orig_symbolic_const.dependence;
  113. // We might already have an instruction in the eval block if a transitive
  114. // operand of this instruction has the same constant value.
  115. auto result = constants_in_generic_.Insert(const_inst_id, [&] {
  116. // TODO: Add a function on `Context` to add the instruction without
  117. // inserting it into the dependent instructions list or computing a
  118. // constant value for it.
  119. // TODO: Is the location we pick here always appropriate for the new
  120. // instruction?
  121. auto inst_id = context().sem_ir().insts().AddInNoBlock(
  122. SemIR::LocIdAndInst::UncheckedLoc(loc_id_, new_inst));
  123. auto const_id = AddGenericConstantInstToEvalBlock(
  124. context(), const_inst_id, inst_id, dependence);
  125. context().constant_values().Set(inst_id, const_id);
  126. return inst_id;
  127. });
  128. return result.value();
  129. }
  130. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  131. auto inst = context().insts().Get(orig_inst_id);
  132. CARBON_CHECK(
  133. inst.Is<SemIR::BindSymbolicName>() ||
  134. inst.Is<SemIR::SymbolicBindingPattern>(),
  135. "Instruction {0} has symbolic constant value but no symbolic operands",
  136. inst);
  137. // Rebuild the instruction anyway so that it's included in the eval block.
  138. // TODO: Can we just reuse the instruction in this case?
  139. return Rebuild(orig_inst_id, inst);
  140. }
  141. private:
  142. SemIR::LocId loc_id_;
  143. ConstantsInGenericMap& constants_in_generic_;
  144. };
  145. // Substitution callbacks to rebuild a template action. This rebuilds the action
  146. // instruction in-place if it needs to be modified.
  147. class RebuildTemplateActionInEvalBlockCallbacks final
  148. : public RebuildGenericConstantInEvalBlockCallbacks {
  149. public:
  150. // `context` must not be null.
  151. RebuildTemplateActionInEvalBlockCallbacks(Context* context,
  152. SemIR::LocId loc_id,
  153. SemIR::InstId action_inst_id)
  154. : RebuildGenericConstantInEvalBlockCallbacks(context, loc_id),
  155. action_inst_id_(action_inst_id) {}
  156. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst)
  157. -> SemIR::InstId override {
  158. if (orig_inst_id == action_inst_id_) {
  159. // TODO: We want to ReplaceInstPreservingConstantValue here, but don't
  160. // want to evaluate the action to check the value hasn't changed.
  161. context().sem_ir().insts().Set(orig_inst_id, new_inst);
  162. return orig_inst_id;
  163. }
  164. return RebuildGenericConstantInEvalBlockCallbacks::Rebuild(orig_inst_id,
  165. new_inst);
  166. }
  167. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  168. if (orig_inst_id == action_inst_id_) {
  169. return orig_inst_id;
  170. }
  171. return RebuildGenericConstantInEvalBlockCallbacks::ReuseUnchanged(
  172. orig_inst_id);
  173. }
  174. private:
  175. SemIR::InstId action_inst_id_;
  176. };
  177. } // namespace
  178. // Adds instructions to compute the substituted version of `type_id` in each
  179. // specific into the eval block for the current generic region. Returns a
  180. // symbolic type ID that refers to the substituted type in each specific.
  181. static auto AddGenericTypeToEvalBlock(Context& context, SemIR::LocId loc_id,
  182. SemIR::TypeId type_id) -> SemIR::TypeId {
  183. // Substitute into the type's constant instruction and rebuild it in the eval
  184. // block.
  185. auto rebuild_generic_constant_callbacks =
  186. RebuildGenericConstantInEvalBlockCallbacks(&context, loc_id);
  187. auto type_inst_id = SubstInst(context, context.types().GetInstId(type_id),
  188. rebuild_generic_constant_callbacks);
  189. return context.types().GetTypeIdForTypeConstantId(
  190. context.constant_values().GetAttached(type_inst_id));
  191. }
  192. // Adds instructions to compute the substituted value of `inst_id` in each
  193. // specific into the eval block for the current generic region. Returns a
  194. // symbolic constant instruction ID that refers to the substituted constant
  195. // value in each specific.
  196. static auto AddGenericConstantToEvalBlock(Context& context,
  197. SemIR::InstId inst_id)
  198. -> SemIR::ConstantId {
  199. CARBON_CHECK(context.constant_values().Get(inst_id).is_symbolic(),
  200. "Adding generic constant {0} with non-symbolic value {1}",
  201. context.insts().Get(inst_id),
  202. context.constant_values().Get(inst_id));
  203. // Substitute into the constant value and rebuild it in the eval block if
  204. // we've not encountered it before.
  205. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  206. auto callbacks = RebuildGenericConstantInEvalBlockCallbacks(
  207. &context, SemIR::LocId(inst_id));
  208. auto new_inst_id = SubstInst(context, const_inst_id, callbacks);
  209. CARBON_CHECK(new_inst_id != const_inst_id,
  210. "No substitutions performed for generic constant {0}",
  211. context.insts().Get(inst_id));
  212. return context.constant_values().GetAttached(new_inst_id);
  213. }
  214. // Adds an instruction that performs a template action to the eval block for the
  215. // generic. The instruction should not yet have been added to any block. The
  216. // instruction might refer to types and constants that need to be rewritten, so
  217. // substitute into it first.
  218. static auto AddTemplateActionToEvalBlock(Context& context,
  219. SemIR::InstId inst_id) -> void {
  220. // Substitute into the constant value and rebuild it in the eval block.
  221. auto rebuild_template_action_callbacks =
  222. RebuildTemplateActionInEvalBlockCallbacks(&context, SemIR::LocId(inst_id),
  223. inst_id);
  224. auto new_inst_id =
  225. SubstInst(context, inst_id, rebuild_template_action_callbacks);
  226. CARBON_CHECK(new_inst_id == inst_id,
  227. "Substitution changed InstId of template action");
  228. context.generic_region_stack().PeekConstantsInGenericMap().Insert(inst_id,
  229. inst_id);
  230. // Add the action to the eval block and point its constant value back to its
  231. // index within the block.
  232. auto [generic_id, region] = GetOrCreatePendingGeneric(context);
  233. auto& symbolic_constant = context.constant_values().GetSymbolicConstant(
  234. context.constant_values().GetAttached(inst_id));
  235. symbolic_constant.generic_id = generic_id;
  236. symbolic_constant.index = SemIR::GenericInstIndex(
  237. region, context.generic_region_stack().PeekEvalBlock().size());
  238. context.generic_region_stack().AddInstToEvalBlock(inst_id);
  239. }
  240. // Populates a map of constants in a generic from the constants in the
  241. // declaration region, in preparation for building the definition region.
  242. static auto PopulateConstantsFromDeclaration(
  243. Context& context, SemIR::GenericId generic_id,
  244. ConstantsInGenericMap& constants_in_generic) {
  245. // For the definition region, populate constants from the declaration.
  246. auto decl_eval_block = context.inst_blocks().Get(
  247. context.generics().Get(generic_id).decl_block_id);
  248. constants_in_generic.GrowForInsertCount(decl_eval_block.size());
  249. for (auto inst_id : decl_eval_block) {
  250. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  251. auto result = constants_in_generic.Insert(const_inst_id, inst_id);
  252. CARBON_CHECK(result.is_inserted(),
  253. "Duplicate constant in generic decl eval block: {0}",
  254. context.insts().Get(const_inst_id));
  255. }
  256. }
  257. auto AttachDependentInstToCurrentGeneric(Context& context,
  258. DependentInst dependent_inst) -> void {
  259. auto [inst_id, dep_kind] = dependent_inst;
  260. // If we don't have a generic region here, leave the dependent instruction
  261. // unattached. This happens for out-of-line redeclarations of members of
  262. // dependent scopes:
  263. //
  264. // class A(T:! type) {
  265. // fn F();
  266. // }
  267. // // Has generic type and constant value, but no generic region.
  268. // fn A(T:! type).F() {}
  269. //
  270. // TODO: Copy the attached type and constant value from the previous
  271. // declaration in this case instead of attempting to attach the new
  272. // declaration to a generic region that we're no longer within.
  273. if (context.generic_region_stack().Empty()) {
  274. // This should only happen for `*Decl` instructions, never for template
  275. // actions.
  276. CARBON_CHECK((dep_kind & DependentInst::Template) == DependentInst::None);
  277. return;
  278. }
  279. context.generic_region_stack().AddDependentInst(dependent_inst.inst_id);
  280. // If the type is symbolic, replace it with a type specific to this generic.
  281. if ((dep_kind & DependentInst::SymbolicType) != DependentInst::None) {
  282. auto inst = context.insts().Get(inst_id);
  283. auto type_id = AddGenericTypeToEvalBlock(context, SemIR::LocId(inst_id),
  284. inst.type_id());
  285. // TODO: Eventually, completeness requirements should be modeled as
  286. // constraints on the generic rather than properties of the type. For now,
  287. // require the transformed type to be complete if the original was.
  288. if (context.types().IsComplete(inst.type_id())) {
  289. CompleteTypeOrCheckFail(context, type_id);
  290. }
  291. inst.SetType(type_id);
  292. context.sem_ir().insts().Set(inst_id, inst);
  293. }
  294. // If the instruction has a symbolic constant value, then make a note that
  295. // we'll need to evaluate this instruction when forming the specific. Update
  296. // the constant value of the instruction to refer to the result of that
  297. // eventual evaluation.
  298. if ((dep_kind & DependentInst::SymbolicConstant) != DependentInst::None) {
  299. // Update the constant value to refer to this generic.
  300. context.constant_values().Set(
  301. inst_id, AddGenericConstantToEvalBlock(context, inst_id));
  302. }
  303. // If the instruction is a template action, add it directly to this position
  304. // in the eval block.
  305. if ((dep_kind & DependentInst::Template) != DependentInst::None) {
  306. AddTemplateActionToEvalBlock(context, inst_id);
  307. }
  308. }
  309. // Builds and returns a block of instructions whose constant values need to be
  310. // evaluated in order to resolve a generic to a specific.
  311. static auto MakeGenericEvalBlock(Context& context) -> SemIR::InstBlockId {
  312. return context.inst_blocks().Add(
  313. context.generic_region_stack().PeekEvalBlock());
  314. }
  315. // Builds and returns an eval block, given the list of canonical symbolic
  316. // constants that the instructions in the eval block should produce. This is
  317. // used when importing a generic.
  318. auto RebuildGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  319. SemIR::GenericInstIndex::Region region,
  320. llvm::ArrayRef<SemIR::InstId> const_ids)
  321. -> SemIR::InstBlockId {
  322. context.generic_region_stack().Push(
  323. {.generic_id = generic_id, .region = region});
  324. auto& constants_in_generic =
  325. context.generic_region_stack().PeekConstantsInGenericMap();
  326. // For the definition region, populate constants from the declaration.
  327. if (region == SemIR::GenericInstIndex::Definition) {
  328. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  329. }
  330. constants_in_generic.GrowForInsertCount(const_ids.size());
  331. for (auto [i, inst_id] : llvm::enumerate(const_ids)) {
  332. // Build a constant in the inst block.
  333. AddGenericConstantToEvalBlock(context, inst_id);
  334. CARBON_CHECK(context.generic_region_stack().PeekEvalBlock().size() == i + 1,
  335. "Produced {0} instructions when importing {1}",
  336. (context.generic_region_stack().PeekEvalBlock().size() - i),
  337. context.insts().Get(inst_id));
  338. }
  339. auto eval_block_id = MakeGenericEvalBlock(context);
  340. context.generic_region_stack().Pop();
  341. return eval_block_id;
  342. }
  343. auto StartGenericDecl(Context& context) -> void {
  344. context.generic_region_stack().Push(
  345. {.generic_id = SemIR::GenericId::None,
  346. .region = SemIR::GenericInstIndex::Declaration});
  347. }
  348. auto StartGenericDefinition(Context& context, SemIR::GenericId generic_id)
  349. -> void {
  350. // Push a generic region even if we don't have a generic_id. We might still
  351. // have locally-introduced generic parameters to track:
  352. //
  353. // fn F() {
  354. // let T:! type = i32;
  355. // var x: T;
  356. // }
  357. context.generic_region_stack().Push(
  358. {.generic_id = generic_id,
  359. .region = SemIR::GenericInstIndex::Definition});
  360. if (generic_id.has_value()) {
  361. PopulateConstantsFromDeclaration(
  362. context, generic_id,
  363. context.generic_region_stack().PeekConstantsInGenericMap());
  364. }
  365. }
  366. auto DiscardGenericDecl(Context& context) -> void {
  367. // Unattach any types and constant values we might have created in the
  368. // generic.
  369. // TODO: We should re-evaluate the contents of the eval block in a synthesized
  370. // specific to form these values, in order to propagate the values of local
  371. // `let :!` bindings.
  372. for (auto inst_id : context.generic_region_stack().PeekDependentInsts()) {
  373. // Note that `Get` returns an instruction with an unattached type.
  374. context.sem_ir().insts().Set(inst_id, context.insts().Get(inst_id));
  375. // Note that `Get` returns an unattached constant.
  376. context.constant_values().Set(inst_id,
  377. context.constant_values().Get(inst_id));
  378. }
  379. // Note that we may leak a GenericId here, if one was allocated.
  380. context.generic_region_stack().Pop();
  381. }
  382. auto BuildGeneric(Context& context, SemIR::InstId decl_id) -> SemIR::GenericId {
  383. auto all_bindings =
  384. context.scope_stack().compile_time_bindings_stack().PeekAllValues();
  385. if (all_bindings.empty()) {
  386. CARBON_CHECK(context.generic_region_stack().PeekEvalBlock().empty(),
  387. "Have non-empty eval block {0} in declaration {1} but no "
  388. "compile time bindings are in scope.",
  389. context.insts().Get(
  390. context.generic_region_stack().PeekEvalBlock().front()),
  391. context.insts().Get(decl_id));
  392. DiscardGenericDecl(context);
  393. return SemIR::GenericId::None;
  394. }
  395. // Build the new Generic object. Note that we intentionally do not hold a
  396. // persistent reference to it throughout this function, because the `generics`
  397. // collection can have items added to it by import resolution while we are
  398. // building this generic.
  399. auto bindings_id = context.inst_blocks().Add(all_bindings);
  400. SemIR::Generic generic = {.decl_id = decl_id,
  401. .bindings_id = bindings_id,
  402. .self_specific_id = SemIR::SpecificId::None};
  403. // Get the generic ID, or allocate one now if we don't have one yet. That
  404. // could happen if the eval block is empty.
  405. auto generic_id =
  406. context.generic_region_stack().PeekPendingGeneric().generic_id;
  407. if (!generic_id.has_value()) {
  408. CARBON_CHECK(context.generic_region_stack().PeekEvalBlock().empty(),
  409. "Non-empty eval block but didn't yet allocate a GenericId");
  410. generic_id = context.generics().Add(generic);
  411. context.generic_region_stack().SetPendingGenericId(generic_id);
  412. } else {
  413. CARBON_CHECK(!context.generics().Get(generic_id).decl_id.has_value(),
  414. "Built generic {0} twice", generic_id);
  415. context.generics().Get(generic_id) = generic;
  416. }
  417. // MakeSelfSpecificId could cause something to be imported, which would
  418. // invalidate the return value of `context.generics().Get(generic_id)`.
  419. auto self_specific_id = MakeSelfSpecificId(context, generic_id);
  420. context.generics().Get(generic_id).self_specific_id = self_specific_id;
  421. return generic_id;
  422. }
  423. auto FinishGenericDecl(Context& context, SemIR::LocId loc_id,
  424. SemIR::GenericId generic_id) -> void {
  425. if (!generic_id.has_value()) {
  426. return;
  427. }
  428. auto decl_block_id = MakeGenericEvalBlock(context);
  429. context.generic_region_stack().Pop();
  430. context.generics().Get(generic_id).decl_block_id = decl_block_id;
  431. ResolveSpecificDecl(context, loc_id,
  432. context.generics().GetSelfSpecific(generic_id));
  433. }
  434. auto BuildGenericDecl(Context& context, SemIR::InstId decl_id)
  435. -> SemIR::GenericId {
  436. SemIR::GenericId generic_id = BuildGeneric(context, decl_id);
  437. if (generic_id.has_value()) {
  438. FinishGenericDecl(context, SemIR::LocId(decl_id), generic_id);
  439. }
  440. return generic_id;
  441. }
  442. // Returns the first difference between the two given eval blocks.
  443. static auto FirstDifferenceBetweenEvalBlocks(
  444. Context& context, llvm::ArrayRef<SemIR::InstId> old_eval_block,
  445. llvm::ArrayRef<SemIR::InstId> new_eval_block)
  446. -> std::pair<SemIR::InstId, SemIR::InstId> {
  447. // Check each element of the eval block computes the same unattached constant.
  448. for (auto [old_inst_id, new_inst_id] :
  449. llvm::zip(old_eval_block, new_eval_block)) {
  450. auto old_const_id = context.constant_values().Get(old_inst_id);
  451. auto new_const_id = context.constant_values().Get(new_inst_id);
  452. if (old_const_id != new_const_id) {
  453. if (old_const_id.is_symbolic() && new_const_id.is_symbolic() &&
  454. context.constant_values().GetDependence(old_const_id) ==
  455. SemIR::ConstantDependence::Template &&
  456. context.constant_values().GetDependence(new_const_id) ==
  457. SemIR::ConstantDependence::Template &&
  458. context.insts().Get(old_inst_id).kind() ==
  459. context.insts().Get(new_inst_id).kind()) {
  460. // TODO: We don't have a good mechanism to compare template constants
  461. // because they canonicalize to themselves, so just assume this is OK.
  462. continue;
  463. }
  464. // These constant values differ unexpectedly.
  465. return {old_inst_id, new_inst_id};
  466. }
  467. }
  468. if (old_eval_block.size() < new_eval_block.size()) {
  469. return {SemIR::InstId::None, new_eval_block[old_eval_block.size()]};
  470. }
  471. if (old_eval_block.size() > new_eval_block.size()) {
  472. return {old_eval_block[new_eval_block.size()], SemIR::InstId::None};
  473. }
  474. return {SemIR::InstId::None, SemIR::InstId::None};
  475. }
  476. // If `constant_id` refers to a symbolic constant within the declaration region
  477. // of `generic_id`, remap it to refer to the constant value of the corresponding
  478. // element in the given eval block. Otherwise returns the ID unchanged.
  479. static auto ReattachConstant(Context& context, SemIR::GenericId generic_id,
  480. llvm::ArrayRef<SemIR::InstId> eval_block,
  481. SemIR::ConstantId constant_id)
  482. -> SemIR::ConstantId {
  483. if (!constant_id.has_value() || !constant_id.is_symbolic()) {
  484. return constant_id;
  485. }
  486. auto& symbolic_const =
  487. context.constant_values().GetSymbolicConstant(constant_id);
  488. if (symbolic_const.generic_id != generic_id) {
  489. // Constant doesn't refer into this generic.
  490. return constant_id;
  491. }
  492. CARBON_CHECK(
  493. symbolic_const.index.region() == SemIR::GenericInstIndex::Declaration,
  494. "Definition region of redeclaration should not be referenced");
  495. return context.constant_values().GetAttached(
  496. eval_block[symbolic_const.index.index()]);
  497. }
  498. // Same as `ReattachConstant` but for a type.
  499. static auto ReattachType(Context& context, SemIR::GenericId generic_id,
  500. llvm::ArrayRef<SemIR::InstId> eval_block,
  501. SemIR::TypeId type_id) -> SemIR::TypeId {
  502. return context.types().GetTypeIdForTypeConstantId(ReattachConstant(
  503. context, generic_id, eval_block, context.types().GetConstantId(type_id)));
  504. }
  505. auto FinishGenericRedecl(Context& context, SemIR::GenericId generic_id)
  506. -> void {
  507. if (!generic_id.has_value()) {
  508. DiscardGenericDecl(context);
  509. return;
  510. }
  511. // Find the old and new eval blocks.
  512. auto old_eval_block_id =
  513. context.generics()
  514. .Get(generic_id)
  515. .GetEvalBlock(SemIR::GenericInstIndex::Declaration);
  516. CARBON_CHECK(old_eval_block_id.has_value(),
  517. "Old generic is not fully declared");
  518. auto old_eval_block = context.inst_blocks().Get(old_eval_block_id);
  519. auto new_eval_block = context.generic_region_stack().PeekEvalBlock();
  520. // Check the eval blocks are computing the same constants in the same order.
  521. // This should always be the case because we have already verified they have
  522. // the same parse tree, and the poisoning rules mean that all entities they
  523. // refer to are also the same.
  524. //
  525. // Note that it's OK if the first difference is that an old instruction has no
  526. // corresponding new instruction; we wouldn't have used that anyway. This
  527. // happens for `ImplDecl`, for which the witness is included in the eval block
  528. // of the first declaration.
  529. if (auto [old_inst_id, new_inst_id] = FirstDifferenceBetweenEvalBlocks(
  530. context, old_eval_block, new_eval_block);
  531. new_inst_id.has_value()) {
  532. // This shouldn't be possible: we should have already checked that the
  533. // syntax of the redeclaration matches the prior declaration, and none of
  534. // the name lookups or semantic checks should be allowed to differ between
  535. // the two declarations, so we should have built the same eval block as in
  536. // the prior declaration.
  537. //
  538. // However, that isn't a strong enough invariant that it seems appropriate
  539. // to CHECK-fail here, so we produce a diagnostic with context.TODO()
  540. // instead.
  541. //
  542. // TODO: Add something like context.UNEXPECTED() instead of using
  543. // context.TODO() here because there's not really anything to do.
  544. context.TODO(new_inst_id,
  545. "generic redeclaration differs from previous declaration");
  546. if (old_inst_id.has_value()) {
  547. context.TODO(old_inst_id, "instruction in previous declaration");
  548. }
  549. DiscardGenericDecl(context);
  550. return;
  551. }
  552. auto redecl_generic_id =
  553. context.generic_region_stack().PeekPendingGeneric().generic_id;
  554. // Reattach any instructions that depend on the redeclaration to instead refer
  555. // to the original.
  556. for (auto inst_id : context.generic_region_stack().PeekDependentInsts()) {
  557. // Reattach the type.
  558. auto inst = context.insts().GetWithAttachedType(inst_id);
  559. inst.SetType(ReattachType(context, redecl_generic_id, old_eval_block,
  560. inst.type_id()));
  561. context.sem_ir().insts().Set(inst_id, inst);
  562. // Reattach the constant value.
  563. context.constant_values().Set(
  564. inst_id,
  565. ReattachConstant(context, redecl_generic_id, old_eval_block,
  566. context.constant_values().GetAttached(inst_id)));
  567. }
  568. context.generic_region_stack().Pop();
  569. }
  570. auto FinishGenericDefinition(Context& context, SemIR::GenericId generic_id)
  571. -> void {
  572. if (!generic_id.has_value()) {
  573. DiscardGenericDecl(context);
  574. return;
  575. }
  576. auto definition_block_id = MakeGenericEvalBlock(context);
  577. context.generic_region_stack().Pop();
  578. context.generics().Get(generic_id).definition_block_id = definition_block_id;
  579. }
  580. auto ResolveSpecificDecl(Context& context, SemIR::LocId loc_id,
  581. SemIR::SpecificId specific_id) -> void {
  582. // If this is the first time we've formed this specific, evaluate its decl
  583. // block to form information about the specific.
  584. if (!context.specifics().Get(specific_id).decl_block_id.has_value()) {
  585. // Set a placeholder value as the decl block ID so we won't attempt to
  586. // recursively resolve the same specific.
  587. context.specifics().Get(specific_id).decl_block_id =
  588. SemIR::InstBlockId::Empty;
  589. auto decl_block_id =
  590. TryEvalBlockForSpecific(context, loc_id, specific_id,
  591. SemIR::GenericInstIndex::Region::Declaration);
  592. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  593. // so re-lookup the specific here.
  594. context.specifics().Get(specific_id).decl_block_id = decl_block_id;
  595. }
  596. }
  597. auto MakeSpecific(Context& context, SemIR::LocId loc_id,
  598. SemIR::GenericId generic_id, SemIR::InstBlockId args_id)
  599. -> SemIR::SpecificId {
  600. auto specific_id = context.specifics().GetOrAdd(generic_id, args_id);
  601. ResolveSpecificDecl(context, loc_id, specific_id);
  602. return specific_id;
  603. }
  604. auto MakeSpecific(Context& context, SemIR::LocId loc_id,
  605. SemIR::GenericId generic_id,
  606. llvm::ArrayRef<SemIR::InstId> args) -> SemIR::SpecificId {
  607. auto args_id = context.inst_blocks().AddCanonical(args);
  608. return MakeSpecific(context, loc_id, generic_id, args_id);
  609. }
  610. static auto MakeSelfSpecificId(Context& context, SemIR::GenericId generic_id)
  611. -> SemIR::SpecificId {
  612. if (!generic_id.has_value()) {
  613. return SemIR::SpecificId::None;
  614. }
  615. auto& generic = context.generics().Get(generic_id);
  616. auto args = context.inst_blocks().Get(generic.bindings_id);
  617. // Form a canonical argument list for the generic.
  618. llvm::SmallVector<SemIR::InstId> arg_ids;
  619. arg_ids.reserve(args.size());
  620. for (auto arg_id : args) {
  621. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  622. }
  623. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  624. return context.specifics().GetOrAdd(generic_id, args_id);
  625. }
  626. auto MakeSelfSpecific(Context& context, SemIR::LocId loc_id,
  627. SemIR::GenericId generic_id) -> SemIR::SpecificId {
  628. // Build a corresponding specific.
  629. SemIR::SpecificId specific_id = MakeSelfSpecificId(context, generic_id);
  630. // TODO: This could be made more efficient. We don't need to perform
  631. // substitution here; we know we want identity mappings for all constants and
  632. // types. We could also consider not storing the mapping at all in this case.
  633. ResolveSpecificDecl(context, loc_id, specific_id);
  634. return specific_id;
  635. }
  636. auto ResolveSpecificDefinition(Context& context, SemIR::LocId loc_id,
  637. SemIR::SpecificId specific_id) -> bool {
  638. // TODO: Handle recursive resolution of the same generic definition.
  639. auto& specific = context.specifics().Get(specific_id);
  640. auto generic_id = specific.generic_id;
  641. CARBON_CHECK(generic_id.has_value(), "Specific with no generic ID");
  642. if (!specific.definition_block_id.has_value()) {
  643. // Evaluate the eval block for the definition of the generic.
  644. auto& generic = context.generics().Get(generic_id);
  645. if (!generic.definition_block_id.has_value()) {
  646. // The generic is not defined yet.
  647. return false;
  648. }
  649. auto definition_block_id = TryEvalBlockForSpecific(
  650. context, loc_id, specific_id, SemIR::GenericInstIndex::Definition);
  651. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  652. // so re-lookup the specific here.
  653. context.specifics().Get(specific_id).definition_block_id =
  654. definition_block_id;
  655. }
  656. return true;
  657. }
  658. auto DiagnoseIfGenericMissingExplicitParameters(
  659. Context& context, SemIR::EntityWithParamsBase& entity_base) -> void {
  660. if (!entity_base.implicit_param_patterns_id.has_value() ||
  661. entity_base.param_patterns_id.has_value()) {
  662. return;
  663. }
  664. CARBON_DIAGNOSTIC(GenericMissingExplicitParameters, Error,
  665. "expected explicit parameters after implicit parameters");
  666. context.emitter().Emit(entity_base.last_param_node_id,
  667. GenericMissingExplicitParameters);
  668. }
  669. } // namespace Carbon::Check