generic.cpp 38 KB

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