generic.cpp 15 KB

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