subst.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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/subst.h"
  5. #include "toolchain/check/eval.h"
  6. #include "toolchain/check/generic.h"
  7. #include "toolchain/sem_ir/copy_on_write_block.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. namespace Carbon::Check {
  10. namespace {
  11. // Information about an instruction that we are substituting into.
  12. struct WorklistItem {
  13. // The instruction that we are substituting into.
  14. SemIR::InstId inst_id;
  15. // Whether the operands of this instruction have been added to the worklist.
  16. bool is_expanded : 1;
  17. // The index of the worklist item to process after we finish updating this
  18. // one. For the final child of an instruction, this is the parent. For any
  19. // other child, this is the index of the next child of the parent. For the
  20. // root, this is -1.
  21. int next_index : 31;
  22. };
  23. // A list of instructions that we're currently in the process of substituting
  24. // into. For details of the algorithm used here, see `SubstConstant`.
  25. class Worklist {
  26. public:
  27. explicit Worklist(SemIR::InstId root_id) {
  28. worklist_.push_back(
  29. {.inst_id = root_id, .is_expanded = false, .next_index = -1});
  30. }
  31. auto operator[](int index) -> WorklistItem& { return worklist_[index]; }
  32. auto size() -> int { return worklist_.size(); }
  33. auto back() -> WorklistItem& { return worklist_.back(); }
  34. auto Push(SemIR::InstId inst_id) -> void {
  35. worklist_.push_back({.inst_id = inst_id,
  36. .is_expanded = false,
  37. .next_index = static_cast<int>(worklist_.size() + 1)});
  38. CARBON_CHECK(worklist_.back().next_index > 0) << "Constant too large.";
  39. }
  40. auto Pop() -> SemIR::InstId { return worklist_.pop_back_val().inst_id; }
  41. private:
  42. // Constants can get pretty large, so use a large worklist. This should be
  43. // about 4KiB, which should be small enough to comfortably fit on the stack,
  44. // but large enough that it's unlikely that we'll need a heap allocation.
  45. llvm::SmallVector<WorklistItem, 512> worklist_;
  46. };
  47. } // namespace
  48. // Pushes the specified operand onto the worklist.
  49. static auto PushOperand(Context& context, Worklist& worklist,
  50. SemIR::IdKind kind, int32_t arg) -> void {
  51. switch (kind) {
  52. case SemIR::IdKind::For<SemIR::InstId>:
  53. worklist.Push(SemIR::InstId(arg));
  54. break;
  55. case SemIR::IdKind::For<SemIR::TypeId>:
  56. if (auto type_id = SemIR::TypeId(arg); type_id.is_valid()) {
  57. worklist.Push(context.types().GetInstId(type_id));
  58. }
  59. break;
  60. case SemIR::IdKind::For<SemIR::InstBlockId>:
  61. for (auto inst_id : context.inst_blocks().Get(SemIR::InstBlockId(arg))) {
  62. worklist.Push(inst_id);
  63. }
  64. break;
  65. case SemIR::IdKind::For<SemIR::TypeBlockId>:
  66. for (auto type_id : context.type_blocks().Get(SemIR::TypeBlockId(arg))) {
  67. worklist.Push(context.types().GetInstId(type_id));
  68. }
  69. break;
  70. case SemIR::IdKind::For<SemIR::GenericInstanceId>:
  71. if (auto instance_id = static_cast<SemIR::GenericInstanceId>(arg);
  72. instance_id.is_valid()) {
  73. PushOperand(context, worklist, SemIR::IdKind::For<SemIR::InstBlockId>,
  74. context.generic_instances().Get(instance_id).args_id.index);
  75. }
  76. break;
  77. default:
  78. break;
  79. }
  80. }
  81. // Converts the operands of this instruction into `InstId`s and pushes them onto
  82. // the worklist.
  83. static auto ExpandOperands(Context& context, Worklist& worklist,
  84. SemIR::InstId inst_id) -> void {
  85. auto inst = context.insts().Get(inst_id);
  86. auto kinds = inst.ArgKinds();
  87. PushOperand(context, worklist, SemIR::IdKind::For<SemIR::TypeId>,
  88. inst.type_id().index);
  89. PushOperand(context, worklist, kinds.first, inst.arg0());
  90. PushOperand(context, worklist, kinds.second, inst.arg1());
  91. }
  92. // Pops the specified operand from the worklist and returns it.
  93. static auto PopOperand(Context& context, Worklist& worklist, SemIR::IdKind kind,
  94. int32_t arg) -> int32_t {
  95. switch (kind) {
  96. case SemIR::IdKind::For<SemIR::InstId>:
  97. return worklist.Pop().index;
  98. case SemIR::IdKind::For<SemIR::TypeId>: {
  99. auto type_id = SemIR::TypeId(arg);
  100. if (!type_id.is_valid()) {
  101. return arg;
  102. }
  103. return context.GetTypeIdForTypeInst(worklist.Pop()).index;
  104. }
  105. case SemIR::IdKind::For<SemIR::InstBlockId>: {
  106. auto old_inst_block_id = SemIR::InstBlockId(arg);
  107. auto size = context.inst_blocks().Get(old_inst_block_id).size();
  108. SemIR::CopyOnWriteInstBlock new_inst_block(context.sem_ir(),
  109. old_inst_block_id);
  110. for (auto i : llvm::reverse(llvm::seq(size))) {
  111. new_inst_block.Set(i, worklist.Pop());
  112. }
  113. return new_inst_block.GetCanonical().index;
  114. }
  115. case SemIR::IdKind::For<SemIR::TypeBlockId>: {
  116. auto old_type_block_id = SemIR::TypeBlockId(arg);
  117. auto size = context.type_blocks().Get(old_type_block_id).size();
  118. SemIR::CopyOnWriteTypeBlock new_type_block(context.sem_ir(),
  119. old_type_block_id);
  120. for (auto i : llvm::index_range(0, size)) {
  121. new_type_block.Set(size - i - 1,
  122. context.GetTypeIdForTypeInst(worklist.Pop()));
  123. }
  124. return new_type_block.GetCanonical().index;
  125. }
  126. case SemIR::IdKind::For<SemIR::GenericInstanceId>: {
  127. auto instance_id = static_cast<SemIR::GenericInstanceId>(arg);
  128. if (!instance_id.is_valid()) {
  129. return arg;
  130. }
  131. auto& instance = context.generic_instances().Get(instance_id);
  132. auto args_id =
  133. PopOperand(context, worklist, SemIR::IdKind::For<SemIR::InstBlockId>,
  134. instance.args_id.index);
  135. return MakeGenericInstance(context, instance.generic_id,
  136. static_cast<SemIR::InstBlockId>(args_id))
  137. .index;
  138. }
  139. default:
  140. return arg;
  141. }
  142. }
  143. // Pops the operands of the specified instruction off the worklist and rebuilds
  144. // the instruction with the updated operands.
  145. static auto Rebuild(Context& context, Worklist& worklist, SemIR::InstId inst_id)
  146. -> SemIR::InstId {
  147. auto inst = context.insts().Get(inst_id);
  148. auto kinds = inst.ArgKinds();
  149. // Note that we pop in reverse order because we pushed them in forwards order.
  150. int32_t arg1 = PopOperand(context, worklist, kinds.second, inst.arg1());
  151. int32_t arg0 = PopOperand(context, worklist, kinds.first, inst.arg0());
  152. int32_t type_id =
  153. PopOperand(context, worklist, SemIR::IdKind::For<SemIR::TypeId>,
  154. inst.type_id().index);
  155. if (type_id == inst.type_id().index && arg0 == inst.arg0() &&
  156. arg1 == inst.arg1()) {
  157. return inst_id;
  158. }
  159. // TODO: Do we need to require this type to be complete?
  160. inst.SetType(SemIR::TypeId(type_id));
  161. inst.SetArgs(arg0, arg1);
  162. auto result_id = TryEvalInst(context, SemIR::InstId::Invalid, inst);
  163. CARBON_CHECK(result_id.is_constant())
  164. << "Substitution into constant produced non-constant";
  165. return context.constant_values().GetInstId(result_id);
  166. }
  167. auto SubstConstant(Context& context, SemIR::ConstantId const_id,
  168. Substitutions substitutions) -> SemIR::ConstantId {
  169. CARBON_CHECK(const_id.is_constant()) << "Substituting into non-constant";
  170. if (substitutions.empty()) {
  171. // Nothing to substitute.
  172. return const_id;
  173. }
  174. if (!const_id.is_symbolic()) {
  175. // A template constant can't contain a reference to a symbolic binding.
  176. return const_id;
  177. }
  178. // TODO: Consider caching; we may perform the same substitutions repeatedly.
  179. Worklist worklist(context.constant_values().GetInstId(const_id));
  180. // For each instruction that forms part of the constant, we will visit it
  181. // twice:
  182. //
  183. // - First, we visit it with `is_expanded == false`, we add all of its
  184. // operands onto the worklist, and process them by following this same
  185. // process.
  186. // - Then, once all operands are processed, we visit the instruction with
  187. // `is_expanded == true`, pop the operands back off the worklist, and if any
  188. // of them changed, rebuild this instruction.
  189. //
  190. // The second step is skipped if we can detect in the first step that the
  191. // instruction will not need to be rebuilt.
  192. int index = 0;
  193. while (index != -1) {
  194. auto& item = worklist[index];
  195. if (item.is_expanded) {
  196. // Rebuild this item if necessary. Note that this might pop items from the
  197. // worklist but does not reallocate, so does not invalidate `item`.
  198. item.inst_id = Rebuild(context, worklist, item.inst_id);
  199. index = item.next_index;
  200. continue;
  201. }
  202. if (context.constant_values().Get(item.inst_id).is_template()) {
  203. // This instruction is a template constant, so can't contain any
  204. // bindings that need to be substituted.
  205. index = item.next_index;
  206. continue;
  207. }
  208. if (auto bind =
  209. context.insts().TryGetAs<SemIR::BindSymbolicName>(item.inst_id)) {
  210. // This is a symbolic binding. Check if we're substituting it.
  211. // TODO: Consider building a hash map for substitutions. We might have a
  212. // lot of them.
  213. for (auto [bind_index, replacement_id] : substitutions) {
  214. if (context.bind_names().Get(bind->bind_name_id).bind_index ==
  215. bind_index) {
  216. // This is the binding we're replacing. Perform substitution.
  217. item.inst_id = context.constant_values().GetInstId(replacement_id);
  218. break;
  219. }
  220. }
  221. // If it's not being substituted, don't look through it. Its constant
  222. // value doesn't depend on its operand.
  223. index = item.next_index;
  224. continue;
  225. }
  226. // Extract the operands of this item into the worklist. Note that this
  227. // modifies the worklist, so it's not safe to use `item` after
  228. // `ExpandOperands` returns.
  229. item.is_expanded = true;
  230. int first_operand = worklist.size();
  231. int next_index = item.next_index;
  232. ExpandOperands(context, worklist, item.inst_id);
  233. // If there are any operands, go and update them before rebuilding this
  234. // item.
  235. if (worklist.size() > first_operand) {
  236. worklist.back().next_index = index;
  237. index = first_operand;
  238. } else {
  239. // No need to rebuild this instruction.
  240. index = next_index;
  241. }
  242. }
  243. CARBON_CHECK(worklist.size() == 1)
  244. << "Unexpected data left behind in work list";
  245. return context.constant_values().Get(worklist.back().inst_id);
  246. }
  247. auto SubstType(Context& context, SemIR::TypeId type_id,
  248. Substitutions substitutions) -> SemIR::TypeId {
  249. return context.GetTypeIdForTypeConstant(SubstConstant(
  250. context, context.types().GetConstantId(type_id), substitutions));
  251. }
  252. } // namespace Carbon::Check