generic.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 "common/map.h"
  6. #include "toolchain/check/eval.h"
  7. #include "toolchain/check/generic_region_stack.h"
  8. #include "toolchain/check/subst.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. namespace Carbon::Check {
  11. auto StartGenericDecl(Context& context) -> void {
  12. context.generic_region_stack().Push();
  13. }
  14. auto StartGenericDefinition(Context& context) -> void {
  15. // Push a generic region even if we don't have a generic_id. We might still
  16. // have locally-introduced generic parameters to track:
  17. //
  18. // fn F() {
  19. // let T:! type = i32;
  20. // var x: T;
  21. // }
  22. context.generic_region_stack().Push();
  23. }
  24. // Adds an instruction `generic_inst_id` to the eval block for a generic region,
  25. // which is the current instruction block. The instruction `generic_inst_id` is
  26. // expected to compute the value of the constant described by `const_inst_id` in
  27. // each specific. Forms and returns a corresponding symbolic constant ID that
  28. // refers to the substituted value of that instruction in each specific.
  29. static auto AddGenericConstantInstToEvalBlock(
  30. Context& context, SemIR::GenericId generic_id,
  31. SemIR::GenericInstIndex::Region region, SemIR::InstId const_inst_id,
  32. SemIR::InstId generic_inst_id) -> SemIR::ConstantId {
  33. auto index = SemIR::GenericInstIndex(
  34. region, context.inst_block_stack().PeekCurrentBlockContents().size());
  35. context.inst_block_stack().AddInstId(generic_inst_id);
  36. return context.constant_values().AddSymbolicConstant(
  37. {.inst_id = const_inst_id, .generic_id = generic_id, .index = index});
  38. }
  39. namespace {
  40. // Substitution callbacks to rebuild a generic constant in the eval block for a
  41. // generic region.
  42. class RebuildGenericConstantInEvalBlockCallbacks final
  43. : public SubstInstCallbacks {
  44. public:
  45. RebuildGenericConstantInEvalBlockCallbacks(
  46. Context& context, SemIR::GenericId generic_id,
  47. SemIR::GenericInstIndex::Region region,
  48. Map<SemIR::InstId, SemIR::InstId>& constants_in_generic)
  49. : context_(context),
  50. generic_id_(generic_id),
  51. region_(region),
  52. constants_in_generic_(constants_in_generic) {}
  53. // Check for instructions for which we already have a mapping into the eval
  54. // block, and substitute them for the instructions in the eval block.
  55. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  56. auto const_id = context_.constant_values().Get(inst_id);
  57. if (!const_id.is_symbolic()) {
  58. // This instruction doesn't have a symbolic constant value, so can't
  59. // contain any bindings that need to be substituted.
  60. return true;
  61. }
  62. // If this instruction is in the map, return the known result.
  63. if (auto result = constants_in_generic_.Lookup(
  64. context_.constant_values().GetInstId(const_id))) {
  65. // In order to reuse instructions from the generic as often as possible,
  66. // keep this instruction as-is if it already has the desired symbolic
  67. // constant value.
  68. if (const_id != context_.constant_values().Get(result.value())) {
  69. inst_id = result.value();
  70. }
  71. CARBON_CHECK(inst_id.is_valid());
  72. return true;
  73. }
  74. // If the instruction is a symbolic binding, build a version in the eval
  75. // block.
  76. if (auto binding =
  77. context_.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  78. inst_id = Rebuild(inst_id, *binding);
  79. return true;
  80. }
  81. return false;
  82. }
  83. // Build a new instruction in the eval block corresponding to the given
  84. // constant.
  85. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  86. -> SemIR::InstId override {
  87. auto const_inst_id =
  88. context_.constant_values().GetConstantInstId(orig_inst_id);
  89. // We might already have an instruction in the eval block if a transitive
  90. // operand of this instruction has the same constant value.
  91. auto result = constants_in_generic_.Insert(const_inst_id, [&] {
  92. // TODO: Add a function on `Context` to add the instruction without
  93. // inserting it into the dependent instructions list or computing a
  94. // constant value for it.
  95. auto inst_id = context_.sem_ir().insts().AddInNoBlock(
  96. SemIR::LocIdAndInst::NoLoc(new_inst));
  97. auto const_id = AddGenericConstantInstToEvalBlock(
  98. context_, generic_id_, region_, const_inst_id, inst_id);
  99. context_.constant_values().Set(inst_id, const_id);
  100. return inst_id;
  101. });
  102. return result.value();
  103. }
  104. private:
  105. Context& context_;
  106. SemIR::GenericId generic_id_;
  107. SemIR::GenericInstIndex::Region region_;
  108. Map<SemIR::InstId, SemIR::InstId>& constants_in_generic_;
  109. };
  110. } // namespace
  111. // Adds instructions to compute the substituted version of `type_id` in each
  112. // specific into the eval block for the generic, which is the current
  113. // instruction block. Returns a symbolic type ID that refers to the substituted
  114. // type in each specific.
  115. static auto AddGenericTypeToEvalBlock(
  116. Context& context, SemIR::GenericId generic_id,
  117. SemIR::GenericInstIndex::Region region,
  118. Map<SemIR::InstId, SemIR::InstId>& constants_in_generic,
  119. SemIR::TypeId type_id) -> SemIR::TypeId {
  120. // Substitute into the type's constant instruction and rebuild it in the eval
  121. // block.
  122. auto type_inst_id =
  123. SubstInst(context, context.types().GetInstId(type_id),
  124. RebuildGenericConstantInEvalBlockCallbacks(
  125. context, generic_id, region, constants_in_generic));
  126. return context.GetTypeIdForTypeInst(type_inst_id);
  127. }
  128. // Adds instructions to compute the substituted value of `inst_id` in each
  129. // specific into the eval block for the generic, which is the current
  130. // instruction block. Returns a symbolic constant instruction ID that refers to
  131. // the substituted constant value in each specific.
  132. static auto AddGenericConstantToEvalBlock(
  133. Context& context, SemIR::GenericId generic_id,
  134. SemIR::GenericInstIndex::Region region,
  135. Map<SemIR::InstId, SemIR::InstId>& constants_in_generic,
  136. SemIR::InstId inst_id) -> SemIR::ConstantId {
  137. // Substitute into the constant value and rebuild it in the eval block if
  138. // we've not encountered it before.
  139. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  140. auto new_inst_id =
  141. SubstInst(context, const_inst_id,
  142. RebuildGenericConstantInEvalBlockCallbacks(
  143. context, generic_id, region, constants_in_generic));
  144. CARBON_CHECK(new_inst_id != const_inst_id)
  145. << "Did not apply any substitutions to symbolic constant "
  146. << context.insts().Get(const_inst_id);
  147. return context.constant_values().Get(new_inst_id);
  148. }
  149. // Builds and returns a block of instructions whose constant values need to be
  150. // evaluated in order to resolve a generic to a specific.
  151. static auto MakeGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  152. SemIR::GenericInstIndex::Region region)
  153. -> SemIR::InstBlockId {
  154. context.inst_block_stack().Push();
  155. Map<SemIR::InstId, SemIR::InstId> constants_in_generic;
  156. // For the definition region, populate constants from the declaration.
  157. if (region == SemIR::GenericInstIndex::Region::Definition) {
  158. auto decl_eval_block = context.inst_blocks().Get(
  159. context.generics().Get(generic_id).decl_block_id);
  160. for (auto inst_id : decl_eval_block) {
  161. constants_in_generic.Insert(
  162. context.constant_values().GetConstantInstId(inst_id), inst_id);
  163. }
  164. }
  165. // The work done in this loop might invalidate iterators into the generic
  166. // region stack, but shouldn't add new dependent instructions to the current
  167. // region.
  168. auto num_dependent_insts =
  169. context.generic_region_stack().PeekDependentInsts().size();
  170. for (auto i : llvm::seq(num_dependent_insts)) {
  171. auto [inst_id, dep_kind] =
  172. context.generic_region_stack().PeekDependentInsts()[i];
  173. // If the type is symbolic, replace it with a type specific to this generic.
  174. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicType) !=
  175. GenericRegionStack::DependencyKind::None) {
  176. auto inst = context.insts().Get(inst_id);
  177. auto type_id = AddGenericTypeToEvalBlock(
  178. context, generic_id, region, constants_in_generic, inst.type_id());
  179. // TODO: Eventually, completeness requirements should be modeled as
  180. // constraints on the generic rather than properties of the type. For now,
  181. // require the transformed type to be complete if the original was.
  182. // TODO: We'll also need to do this when evaluating the eval block.
  183. if (context.types().IsComplete(inst.type_id())) {
  184. context.TryToCompleteType(type_id);
  185. }
  186. inst.SetType(type_id);
  187. context.sem_ir().insts().Set(inst_id, inst);
  188. }
  189. // If the instruction has a symbolic constant value, then make a note that
  190. // we'll need to evaluate this instruction when forming the specific. Update
  191. // the constant value of the instruction to refer to the result of that
  192. // eventual evaluation.
  193. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicConstant) !=
  194. GenericRegionStack::DependencyKind::None) {
  195. // Update the constant value to refer to this generic.
  196. context.constant_values().Set(
  197. inst_id,
  198. AddGenericConstantToEvalBlock(context, generic_id, region,
  199. constants_in_generic, inst_id));
  200. }
  201. }
  202. CARBON_CHECK(num_dependent_insts ==
  203. context.generic_region_stack().PeekDependentInsts().size())
  204. << "Building eval block added new dependent insts, for example "
  205. << context.insts().Get(context.generic_region_stack()
  206. .PeekDependentInsts()[num_dependent_insts]
  207. .inst_id);
  208. return context.inst_block_stack().Pop();
  209. }
  210. auto FinishGenericDecl(Context& context, SemIR::InstId decl_id)
  211. -> SemIR::GenericId {
  212. auto all_bindings =
  213. context.scope_stack().compile_time_bindings_stack().PeekAllValues();
  214. if (all_bindings.empty()) {
  215. CARBON_CHECK(context.generic_region_stack().PeekDependentInsts().empty())
  216. << "Have dependent instructions but no compile time bindings are in "
  217. "scope.";
  218. context.generic_region_stack().Pop();
  219. return SemIR::GenericId::Invalid;
  220. }
  221. // Build the new Generic object. Note that we intentionally do not hold a
  222. // persistent reference to it throughout this function, because the `generics`
  223. // collection can have items added to it by import resolution while we are
  224. // building this generic.
  225. auto bindings_id = context.inst_blocks().Add(all_bindings);
  226. auto generic_id = context.generics().Add(
  227. SemIR::Generic{.decl_id = decl_id,
  228. .bindings_id = bindings_id,
  229. .self_specific_id = SemIR::SpecificId::Invalid});
  230. auto decl_block_id = MakeGenericEvalBlock(
  231. context, generic_id, SemIR::GenericInstIndex::Region::Declaration);
  232. context.generic_region_stack().Pop();
  233. context.generics().Get(generic_id).decl_block_id = decl_block_id;
  234. auto self_specific_id = MakeSelfSpecific(context, generic_id);
  235. context.generics().Get(generic_id).self_specific_id = self_specific_id;
  236. return generic_id;
  237. }
  238. auto FinishGenericRedecl(Context& context, SemIR::InstId /*decl_id*/,
  239. SemIR::GenericId /*generic_id*/) -> void {
  240. // TODO: Compare contents of this declaration with the existing one on the
  241. // generic.
  242. context.generic_region_stack().Pop();
  243. }
  244. auto FinishGenericDefinition(Context& context, SemIR::GenericId generic_id)
  245. -> void {
  246. if (!generic_id.is_valid()) {
  247. // TODO: We can have symbolic constants in a context that had a non-generic
  248. // declaration, for example if there's a local generic let binding in a
  249. // function definition. Handle this case somehow -- perhaps by forming
  250. // substituted constant values now.
  251. context.generic_region_stack().Pop();
  252. return;
  253. }
  254. auto definition_block_id = MakeGenericEvalBlock(
  255. context, generic_id, SemIR::GenericInstIndex::Region::Definition);
  256. context.generics().Get(generic_id).definition_block_id = definition_block_id;
  257. context.generic_region_stack().Pop();
  258. }
  259. auto MakeSpecific(Context& context, SemIR::GenericId generic_id,
  260. SemIR::InstBlockId args_id) -> SemIR::SpecificId {
  261. auto specific_id = context.specifics().GetOrAdd(generic_id, args_id);
  262. // TODO: Remove this once we import generics properly.
  263. if (!generic_id.is_valid()) {
  264. return specific_id;
  265. }
  266. // If this is the first time we've formed this specific, evaluate its decl
  267. // block to form information about the specific.
  268. if (!context.specifics().Get(specific_id).decl_block_id.is_valid()) {
  269. auto decl_block_id = TryEvalBlockForSpecific(
  270. context, specific_id, SemIR::GenericInstIndex::Region::Declaration);
  271. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  272. // so re-lookup the specific here.
  273. context.specifics().Get(specific_id).decl_block_id = decl_block_id;
  274. }
  275. return specific_id;
  276. }
  277. auto MakeSelfSpecific(Context& context, SemIR::GenericId generic_id)
  278. -> SemIR::SpecificId {
  279. if (!generic_id.is_valid()) {
  280. return SemIR::SpecificId::Invalid;
  281. }
  282. auto& generic = context.generics().Get(generic_id);
  283. auto args = context.inst_blocks().Get(generic.bindings_id);
  284. // Form a canonical argument list for the generic.
  285. llvm::SmallVector<SemIR::InstId> arg_ids;
  286. arg_ids.reserve(args.size());
  287. for (auto arg_id : args) {
  288. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  289. }
  290. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  291. // Build a corresponding specific.
  292. // TODO: This could be made more efficient. We don't need to perform
  293. // substitution here; we know we want identity mappings for all constants and
  294. // types. We could also consider not storing the mapping at all in this case.
  295. return MakeSpecific(context, generic_id, args_id);
  296. }
  297. auto ResolveSpecificDefinition(Context& context, SemIR::SpecificId specific_id)
  298. -> bool {
  299. auto& specific = context.specifics().Get(specific_id);
  300. auto generic_id = specific.generic_id;
  301. // TODO: Remove this once we import generics properly.
  302. if (!generic_id.is_valid()) {
  303. return true;
  304. }
  305. if (!specific.definition_block_id.is_valid()) {
  306. // Evaluate the eval block for the definition of the generic.
  307. auto& generic = context.generics().Get(generic_id);
  308. if (!generic.definition_block_id.is_valid()) {
  309. // The generic is not defined yet.
  310. return false;
  311. }
  312. auto definition_block_id = TryEvalBlockForSpecific(
  313. context, specific_id, SemIR::GenericInstIndex::Region::Definition);
  314. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  315. // so re-lookup the specific here.
  316. context.specifics().Get(specific_id).definition_block_id =
  317. definition_block_id;
  318. }
  319. return true;
  320. }
  321. } // namespace Carbon::Check