generic.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. #include "toolchain/sem_ir/inst.h"
  11. namespace Carbon::Check {
  12. auto StartGenericDecl(Context& context) -> void {
  13. context.generic_region_stack().Push();
  14. }
  15. auto StartGenericDefinition(Context& context) -> void {
  16. // Push a generic region even if we don't have a generic_id. We might still
  17. // have locally-introduced generic parameters to track:
  18. //
  19. // fn F() {
  20. // let T:! type = i32;
  21. // var x: T;
  22. // }
  23. context.generic_region_stack().Push();
  24. }
  25. // Adds an instruction `generic_inst_id` to the eval block for a generic region,
  26. // which is the current instruction block. The instruction `generic_inst_id` is
  27. // expected to compute the value of the constant described by `const_inst_id` in
  28. // each specific. Forms and returns a corresponding symbolic constant ID that
  29. // refers to the substituted value of that instruction in each specific.
  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. // A map from an instruction ID representing a canonical symbolic constant to an
  42. // instruction within an eval block of the generic that computes the specific
  43. // value for that constant.
  44. //
  45. // We arbitrarily use a small size of 256 bytes for the map.
  46. // TODO: Determine a better number based on measurements.
  47. using ConstantsInGenericMap = Map<SemIR::InstId, SemIR::InstId, 256>;
  48. // Substitution callbacks to rebuild a generic constant in the eval block for a
  49. // generic region.
  50. class RebuildGenericConstantInEvalBlockCallbacks final
  51. : public SubstInstCallbacks {
  52. public:
  53. RebuildGenericConstantInEvalBlockCallbacks(
  54. Context& context, SemIR::GenericId generic_id,
  55. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  56. ConstantsInGenericMap& constants_in_generic)
  57. : context_(context),
  58. generic_id_(generic_id),
  59. region_(region),
  60. loc_id_(loc_id),
  61. constants_in_generic_(constants_in_generic) {}
  62. // Check for instructions for which we already have a mapping into the eval
  63. // block, and substitute them for the instructions in the eval block.
  64. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  65. auto const_id = context_.constant_values().Get(inst_id);
  66. if (!const_id.is_valid()) {
  67. // An unloaded import ref should never contain anything we need to
  68. // substitute into. Don't trigger loading it here.
  69. CARBON_CHECK(
  70. context_.insts().Is<SemIR::ImportRefUnloaded>(inst_id),
  71. "Substituting into instruction with invalid constant ID: {0}",
  72. context_.insts().Get(inst_id));
  73. return true;
  74. }
  75. if (!context_.constant_values().DependsOnGenericParameter(const_id)) {
  76. // This instruction doesn't have a symbolic constant value, so can't
  77. // contain any bindings that need to be substituted.
  78. return true;
  79. }
  80. // If this instruction is in the map, return the known result.
  81. if (auto result = constants_in_generic_.Lookup(
  82. context_.constant_values().GetInstId(const_id))) {
  83. // In order to reuse instructions from the generic as often as possible,
  84. // keep this instruction as-is if it already has the desired symbolic
  85. // constant value.
  86. if (const_id != context_.constant_values().Get(result.value())) {
  87. inst_id = result.value();
  88. }
  89. CARBON_CHECK(inst_id.is_valid());
  90. return true;
  91. }
  92. // If the instruction is a symbolic binding, build a version in the eval
  93. // block.
  94. if (auto binding =
  95. context_.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  96. if (context_.entity_names()
  97. .Get(binding->entity_name_id)
  98. .bind_index.is_valid()) {
  99. inst_id = Rebuild(inst_id, *binding);
  100. return true;
  101. }
  102. }
  103. if (auto pattern =
  104. context_.insts().TryGetAs<SemIR::SymbolicBindingPattern>(inst_id)) {
  105. inst_id = Rebuild(inst_id, *pattern);
  106. return true;
  107. }
  108. return false;
  109. }
  110. // Build a new instruction in the eval block corresponding to the given
  111. // constant.
  112. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  113. -> SemIR::InstId override {
  114. auto const_inst_id =
  115. context_.constant_values().GetConstantInstId(orig_inst_id);
  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. // TODO: Is the location we pick here always appropriate for the new
  123. // instruction?
  124. auto inst_id = context_.sem_ir().insts().AddInNoBlock(
  125. SemIR::LocIdAndInst::UncheckedLoc(loc_id_, new_inst));
  126. auto const_id = AddGenericConstantInstToEvalBlock(
  127. context_, generic_id_, region_, const_inst_id, inst_id);
  128. context_.constant_values().Set(inst_id, const_id);
  129. return inst_id;
  130. });
  131. return result.value();
  132. }
  133. private:
  134. Context& context_;
  135. SemIR::GenericId generic_id_;
  136. SemIR::GenericInstIndex::Region region_;
  137. SemIR::LocId loc_id_;
  138. ConstantsInGenericMap& constants_in_generic_;
  139. };
  140. } // namespace
  141. // Adds instructions to compute the substituted version of `type_id` in each
  142. // specific into the eval block for the generic, which is the current
  143. // instruction block. Returns a symbolic type ID that refers to the substituted
  144. // type in each specific.
  145. static auto AddGenericTypeToEvalBlock(
  146. Context& context, SemIR::GenericId generic_id,
  147. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  148. ConstantsInGenericMap& constants_in_generic, SemIR::TypeId type_id)
  149. -> SemIR::TypeId {
  150. // Substitute into the type's constant instruction and rebuild it in the eval
  151. // block.
  152. auto type_inst_id =
  153. SubstInst(context, context.types().GetInstId(type_id),
  154. RebuildGenericConstantInEvalBlockCallbacks(
  155. context, generic_id, region, loc_id, constants_in_generic));
  156. return context.GetTypeIdForTypeInst(type_inst_id);
  157. }
  158. // Adds instructions to compute the substituted value of `inst_id` in each
  159. // specific into the eval block for the generic, which is the current
  160. // instruction block. Returns a symbolic constant instruction ID that refers to
  161. // the substituted constant value in each specific.
  162. static auto AddGenericConstantToEvalBlock(
  163. Context& context, SemIR::GenericId generic_id,
  164. SemIR::GenericInstIndex::Region region,
  165. ConstantsInGenericMap& constants_in_generic, SemIR::InstId inst_id)
  166. -> SemIR::ConstantId {
  167. // Substitute into the constant value and rebuild it in the eval block if
  168. // we've not encountered it before.
  169. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  170. auto new_inst_id =
  171. SubstInst(context, const_inst_id,
  172. RebuildGenericConstantInEvalBlockCallbacks(
  173. context, generic_id, region,
  174. context.insts().GetLocId(inst_id), constants_in_generic));
  175. CARBON_CHECK(new_inst_id != const_inst_id,
  176. "Did not apply any substitutions to symbolic constant {0}",
  177. context.insts().Get(const_inst_id));
  178. return context.constant_values().Get(new_inst_id);
  179. }
  180. // Populates a map of constants in a generic from the constants in the
  181. // declaration region, in preparation for building the definition region.
  182. static auto PopulateConstantsFromDeclaration(
  183. Context& context, SemIR::GenericId generic_id,
  184. ConstantsInGenericMap& constants_in_generic) {
  185. // For the definition region, populate constants from the declaration.
  186. auto decl_eval_block = context.inst_blocks().Get(
  187. context.generics().Get(generic_id).decl_block_id);
  188. constants_in_generic.GrowForInsertCount(decl_eval_block.size());
  189. for (auto inst_id : decl_eval_block) {
  190. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  191. auto result = constants_in_generic.Insert(const_inst_id, inst_id);
  192. CARBON_CHECK(result.is_inserted(),
  193. "Duplicate constant in generic decl eval block: {0}",
  194. context.insts().Get(const_inst_id));
  195. }
  196. }
  197. // Builds and returns a block of instructions whose constant values need to be
  198. // evaluated in order to resolve a generic to a specific.
  199. static auto MakeGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  200. SemIR::GenericInstIndex::Region region)
  201. -> SemIR::InstBlockId {
  202. context.inst_block_stack().Push();
  203. ConstantsInGenericMap constants_in_generic;
  204. // For the definition region, populate constants from the declaration.
  205. if (region == SemIR::GenericInstIndex::Region::Definition) {
  206. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  207. }
  208. // The work done in this loop might invalidate iterators into the generic
  209. // region stack, but shouldn't add new dependent instructions to the current
  210. // region.
  211. auto num_dependent_insts =
  212. context.generic_region_stack().PeekDependentInsts().size();
  213. for (auto i : llvm::seq(num_dependent_insts)) {
  214. auto [inst_id, dep_kind] =
  215. context.generic_region_stack().PeekDependentInsts()[i];
  216. // If the type is symbolic, replace it with a type specific to this generic.
  217. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicType) !=
  218. GenericRegionStack::DependencyKind::None) {
  219. auto inst = context.insts().Get(inst_id);
  220. auto type_id = AddGenericTypeToEvalBlock(
  221. context, generic_id, region, context.insts().GetLocId(inst_id),
  222. constants_in_generic, inst.type_id());
  223. // TODO: Eventually, completeness requirements should be modeled as
  224. // constraints on the generic rather than properties of the type. For now,
  225. // require the transformed type to be complete if the original was.
  226. // TODO: We'll also need to do this when evaluating the eval block.
  227. if (context.types().IsComplete(inst.type_id())) {
  228. context.TryToCompleteType(type_id);
  229. }
  230. inst.SetType(type_id);
  231. context.sem_ir().insts().Set(inst_id, inst);
  232. }
  233. // If the instruction has a symbolic constant value, then make a note that
  234. // we'll need to evaluate this instruction when forming the specific. Update
  235. // the constant value of the instruction to refer to the result of that
  236. // eventual evaluation.
  237. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicConstant) !=
  238. GenericRegionStack::DependencyKind::None) {
  239. // Update the constant value to refer to this generic.
  240. context.constant_values().Set(
  241. inst_id,
  242. AddGenericConstantToEvalBlock(context, generic_id, region,
  243. constants_in_generic, inst_id));
  244. }
  245. }
  246. CARBON_CHECK(
  247. num_dependent_insts ==
  248. context.generic_region_stack().PeekDependentInsts().size(),
  249. "Building eval block added new dependent insts, for example {0}",
  250. context.insts().Get(context.generic_region_stack()
  251. .PeekDependentInsts()[num_dependent_insts]
  252. .inst_id));
  253. return context.inst_block_stack().Pop();
  254. }
  255. // Builds and returns an eval block, given the list of canonical symbolic
  256. // constants that the instructions in the eval block should produce. This is
  257. // used when importing a generic.
  258. auto RebuildGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  259. SemIR::GenericInstIndex::Region region,
  260. llvm::ArrayRef<SemIR::InstId> const_ids)
  261. -> SemIR::InstBlockId {
  262. context.inst_block_stack().Push();
  263. ConstantsInGenericMap constants_in_generic;
  264. // For the definition region, populate constants from the declaration.
  265. if (region == SemIR::GenericInstIndex::Region::Definition) {
  266. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  267. }
  268. constants_in_generic.GrowForInsertCount(const_ids.size());
  269. for (auto [i, inst_id] : llvm::enumerate(const_ids)) {
  270. // Build a constant in the inst block.
  271. AddGenericConstantToEvalBlock(context, generic_id, region,
  272. constants_in_generic, inst_id);
  273. CARBON_CHECK(
  274. context.inst_block_stack().PeekCurrentBlockContents().size() == i + 1,
  275. "Produced {0} instructions when importing {1}",
  276. (context.inst_block_stack().PeekCurrentBlockContents().size() - i),
  277. context.insts().Get(inst_id));
  278. }
  279. return context.inst_block_stack().Pop();
  280. }
  281. auto DiscardGenericDecl(Context& context) -> void {
  282. context.generic_region_stack().Pop();
  283. }
  284. auto FinishGenericDecl(Context& context, SemIR::InstId decl_id)
  285. -> SemIR::GenericId {
  286. auto all_bindings =
  287. context.scope_stack().compile_time_bindings_stack().PeekAllValues();
  288. if (all_bindings.empty()) {
  289. CARBON_CHECK(context.generic_region_stack().PeekDependentInsts().empty(),
  290. "Have dependent instructions but no compile time bindings are "
  291. "in scope.");
  292. context.generic_region_stack().Pop();
  293. return SemIR::GenericId::Invalid;
  294. }
  295. // Build the new Generic object. Note that we intentionally do not hold a
  296. // persistent reference to it throughout this function, because the `generics`
  297. // collection can have items added to it by import resolution while we are
  298. // building this generic.
  299. auto bindings_id = context.inst_blocks().Add(all_bindings);
  300. auto generic_id = context.generics().Add(
  301. SemIR::Generic{.decl_id = decl_id,
  302. .bindings_id = bindings_id,
  303. .self_specific_id = SemIR::SpecificId::Invalid});
  304. auto decl_block_id = MakeGenericEvalBlock(
  305. context, generic_id, SemIR::GenericInstIndex::Region::Declaration);
  306. context.generic_region_stack().Pop();
  307. context.generics().Get(generic_id).decl_block_id = decl_block_id;
  308. auto self_specific_id = MakeSelfSpecific(context, generic_id);
  309. context.generics().Get(generic_id).self_specific_id = self_specific_id;
  310. return generic_id;
  311. }
  312. auto FinishGenericRedecl(Context& context, SemIR::InstId /*decl_id*/,
  313. SemIR::GenericId /*generic_id*/) -> void {
  314. // TODO: Compare contents of this declaration with the existing one on the
  315. // generic.
  316. context.generic_region_stack().Pop();
  317. }
  318. auto FinishGenericDefinition(Context& context, SemIR::GenericId generic_id)
  319. -> void {
  320. if (!generic_id.is_valid()) {
  321. // TODO: We can have symbolic constants in a context that had a non-generic
  322. // declaration, for example if there's a local generic let binding in a
  323. // function definition. Handle this case somehow -- perhaps by forming
  324. // substituted constant values now.
  325. context.generic_region_stack().Pop();
  326. return;
  327. }
  328. auto definition_block_id = MakeGenericEvalBlock(
  329. context, generic_id, SemIR::GenericInstIndex::Region::Definition);
  330. context.generics().Get(generic_id).definition_block_id = definition_block_id;
  331. context.generic_region_stack().Pop();
  332. }
  333. auto MakeSpecific(Context& context, SemIR::GenericId generic_id,
  334. SemIR::InstBlockId args_id) -> SemIR::SpecificId {
  335. auto specific_id = context.specifics().GetOrAdd(generic_id, args_id);
  336. // If this is the first time we've formed this specific, evaluate its decl
  337. // block to form information about the specific.
  338. if (!context.specifics().Get(specific_id).decl_block_id.is_valid()) {
  339. auto decl_block_id = TryEvalBlockForSpecific(
  340. context, specific_id, SemIR::GenericInstIndex::Region::Declaration);
  341. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  342. // so re-lookup the specific here.
  343. context.specifics().Get(specific_id).decl_block_id = decl_block_id;
  344. }
  345. return specific_id;
  346. }
  347. auto MakeSelfSpecific(Context& context, SemIR::GenericId generic_id)
  348. -> SemIR::SpecificId {
  349. if (!generic_id.is_valid()) {
  350. return SemIR::SpecificId::Invalid;
  351. }
  352. auto& generic = context.generics().Get(generic_id);
  353. auto args = context.inst_blocks().Get(generic.bindings_id);
  354. // Form a canonical argument list for the generic.
  355. llvm::SmallVector<SemIR::InstId> arg_ids;
  356. arg_ids.reserve(args.size());
  357. for (auto arg_id : args) {
  358. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  359. }
  360. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  361. // Build a corresponding specific.
  362. // TODO: This could be made more efficient. We don't need to perform
  363. // substitution here; we know we want identity mappings for all constants and
  364. // types. We could also consider not storing the mapping at all in this case.
  365. return MakeSpecific(context, generic_id, args_id);
  366. }
  367. auto ResolveSpecificDefinition(Context& context, SemIR::SpecificId specific_id)
  368. -> bool {
  369. auto& specific = context.specifics().Get(specific_id);
  370. auto generic_id = specific.generic_id;
  371. CARBON_CHECK(generic_id.is_valid(), "Specific with no generic ID");
  372. if (!specific.definition_block_id.is_valid()) {
  373. // Evaluate the eval block for the definition of the generic.
  374. auto& generic = context.generics().Get(generic_id);
  375. if (!generic.definition_block_id.is_valid()) {
  376. // The generic is not defined yet.
  377. return false;
  378. }
  379. auto definition_block_id = TryEvalBlockForSpecific(
  380. context, specific_id, SemIR::GenericInstIndex::Region::Definition);
  381. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  382. // so re-lookup the specific here.
  383. context.specifics().Get(specific_id).definition_block_id =
  384. definition_block_id;
  385. }
  386. return true;
  387. }
  388. } // namespace Carbon::Check