generic.cpp 32 KB

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