subst.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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/base/kind_switch.h"
  6. #include "toolchain/check/eval.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/sem_ir/copy_on_write_block.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. #include "toolchain/sem_ir/inst.h"
  11. namespace Carbon::Check {
  12. namespace {
  13. // Information about an instruction that we are substituting into.
  14. struct WorklistItem {
  15. // The instruction that we are substituting into.
  16. SemIR::InstId inst_id;
  17. // Whether the operands of this instruction have been added to the worklist.
  18. bool is_expanded : 1;
  19. // The index of the worklist item to process after we finish updating this
  20. // one. For the final child of an instruction, this is the parent. For any
  21. // other child, this is the index of the next child of the parent. For the
  22. // root, this is -1.
  23. int next_index : 31;
  24. };
  25. // A list of instructions that we're currently in the process of substituting
  26. // into. For details of the algorithm used here, see `SubstConstant`.
  27. class Worklist {
  28. public:
  29. explicit Worklist(SemIR::InstId root_id) {
  30. worklist_.push_back(
  31. {.inst_id = root_id, .is_expanded = false, .next_index = -1});
  32. }
  33. auto operator[](int index) -> WorklistItem& { return worklist_[index]; }
  34. auto size() -> int { return worklist_.size(); }
  35. auto back() -> WorklistItem& { return worklist_.back(); }
  36. auto Push(SemIR::InstId inst_id) -> void {
  37. CARBON_CHECK(inst_id.has_value());
  38. worklist_.push_back({.inst_id = inst_id,
  39. .is_expanded = false,
  40. .next_index = static_cast<int>(worklist_.size() + 1)});
  41. CARBON_CHECK(worklist_.back().next_index > 0, "Constant too large.");
  42. }
  43. auto Pop() -> SemIR::InstId { return worklist_.pop_back_val().inst_id; }
  44. private:
  45. // Constants can get pretty large, so use a large worklist. This should be
  46. // about 4KiB, which should be small enough to comfortably fit on the stack,
  47. // but large enough that it's unlikely that we'll need a heap allocation.
  48. llvm::SmallVector<WorklistItem, 512> worklist_;
  49. };
  50. } // namespace
  51. // Pushes the specified operand onto the worklist.
  52. static auto PushOperand(Context& context, Worklist& worklist,
  53. SemIR::Inst::ArgAndKind arg) -> void {
  54. auto push_block = [&](SemIR::InstBlockId block_id) {
  55. for (auto inst_id :
  56. context.inst_blocks().Get(SemIR::InstBlockId(block_id))) {
  57. worklist.Push(inst_id);
  58. }
  59. };
  60. auto push_specific = [&](SemIR::SpecificId specific_id) {
  61. if (specific_id.has_value()) {
  62. push_block(context.specifics().Get(specific_id).args_id);
  63. }
  64. };
  65. CARBON_KIND_SWITCH(arg) {
  66. case CARBON_KIND(SemIR::InstId inst_id): {
  67. if (inst_id.has_value()) {
  68. worklist.Push(inst_id);
  69. }
  70. break;
  71. }
  72. case CARBON_KIND(SemIR::MetaInstId inst_id): {
  73. if (inst_id.has_value()) {
  74. worklist.Push(inst_id);
  75. }
  76. break;
  77. }
  78. case CARBON_KIND(SemIR::TypeId type_id): {
  79. if (type_id.has_value()) {
  80. worklist.Push(context.types().GetInstId(type_id));
  81. }
  82. break;
  83. }
  84. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  85. push_block(inst_block_id);
  86. break;
  87. }
  88. case CARBON_KIND(SemIR::StructTypeFieldsId fields_id): {
  89. for (auto field : context.struct_type_fields().Get(fields_id)) {
  90. worklist.Push(context.types().GetInstId(field.type_id));
  91. }
  92. break;
  93. }
  94. case CARBON_KIND(SemIR::TypeBlockId type_block_id): {
  95. for (auto type_id : context.type_blocks().Get(type_block_id)) {
  96. worklist.Push(context.types().GetInstId(type_id));
  97. }
  98. break;
  99. }
  100. case CARBON_KIND(SemIR::SpecificId specific_id): {
  101. push_specific(specific_id);
  102. break;
  103. }
  104. case CARBON_KIND(SemIR::SpecificInterfaceId interface_id): {
  105. auto interface = context.specific_interfaces().Get(interface_id);
  106. push_specific(interface.specific_id);
  107. break;
  108. }
  109. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  110. const auto& facet_type_info = context.facet_types().Get(facet_type_id);
  111. for (auto interface : facet_type_info.impls_constraints) {
  112. push_specific(interface.specific_id);
  113. }
  114. for (auto rewrite : facet_type_info.rewrite_constraints) {
  115. auto lhs_inst_id =
  116. context.constant_values().GetInstId(rewrite.lhs_const_id);
  117. auto rhs_inst_id =
  118. context.constant_values().GetInstId(rewrite.rhs_const_id);
  119. worklist.Push(lhs_inst_id);
  120. worklist.Push(rhs_inst_id);
  121. }
  122. // TODO: Process other requirements as well.
  123. break;
  124. }
  125. default:
  126. break;
  127. }
  128. }
  129. // Converts the operands of this instruction into `InstId`s and pushes them onto
  130. // the worklist.
  131. static auto ExpandOperands(Context& context, Worklist& worklist,
  132. SemIR::InstId inst_id) -> void {
  133. auto inst = context.insts().Get(inst_id);
  134. PushOperand(context, worklist, inst.type_id_and_kind());
  135. PushOperand(context, worklist, inst.arg0_and_kind());
  136. PushOperand(context, worklist, inst.arg1_and_kind());
  137. }
  138. // Pops the specified operand from the worklist and returns it.
  139. static auto PopOperand(Context& context, Worklist& worklist,
  140. SemIR::Inst::ArgAndKind arg) -> int32_t {
  141. auto pop_block_id = [&](SemIR::InstBlockId old_inst_block_id) {
  142. auto size = context.inst_blocks().Get(old_inst_block_id).size();
  143. SemIR::CopyOnWriteInstBlock new_inst_block(&context.sem_ir(),
  144. old_inst_block_id);
  145. for (auto i : llvm::reverse(llvm::seq(size))) {
  146. new_inst_block.Set(i, worklist.Pop());
  147. }
  148. return new_inst_block.GetCanonical();
  149. };
  150. auto pop_specific = [&](SemIR::SpecificId specific_id) {
  151. if (!specific_id.has_value()) {
  152. return specific_id;
  153. }
  154. auto& specific = context.specifics().Get(specific_id);
  155. auto args_id = pop_block_id(specific.args_id);
  156. return context.specifics().GetOrAdd(specific.generic_id, args_id);
  157. };
  158. CARBON_KIND_SWITCH(arg) {
  159. case CARBON_KIND(SemIR::InstId inst_id): {
  160. if (!inst_id.has_value()) {
  161. return arg.value();
  162. }
  163. return worklist.Pop().index;
  164. }
  165. case CARBON_KIND(SemIR::MetaInstId inst_id): {
  166. if (!inst_id.has_value()) {
  167. return arg.value();
  168. }
  169. return worklist.Pop().index;
  170. }
  171. case CARBON_KIND(SemIR::TypeId type_id): {
  172. if (!type_id.has_value()) {
  173. return arg.value();
  174. }
  175. return context.types().GetTypeIdForTypeInstId(worklist.Pop()).index;
  176. }
  177. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  178. return pop_block_id(inst_block_id).index;
  179. }
  180. case CARBON_KIND(SemIR::StructTypeFieldsId old_fields_id): {
  181. auto old_fields = context.struct_type_fields().Get(old_fields_id);
  182. SemIR::CopyOnWriteStructTypeFieldsBlock new_fields(&context.sem_ir(),
  183. old_fields_id);
  184. for (auto i : llvm::reverse(llvm::seq(old_fields.size()))) {
  185. new_fields.Set(i, {.name_id = old_fields[i].name_id,
  186. .type_id = context.types().GetTypeIdForTypeInstId(
  187. worklist.Pop())});
  188. }
  189. return new_fields.GetCanonical().index;
  190. }
  191. case CARBON_KIND(SemIR::TypeBlockId old_type_block_id): {
  192. auto size = context.type_blocks().Get(old_type_block_id).size();
  193. SemIR::CopyOnWriteTypeBlock new_type_block(&context.sem_ir(),
  194. old_type_block_id);
  195. for (auto i : llvm::reverse(llvm::seq(size))) {
  196. new_type_block.Set(
  197. i, context.types().GetTypeIdForTypeInstId(worklist.Pop()));
  198. }
  199. return new_type_block.GetCanonical().index;
  200. }
  201. case CARBON_KIND(SemIR::SpecificId specific_id): {
  202. return pop_specific(specific_id).index;
  203. }
  204. case CARBON_KIND(SemIR::SpecificInterfaceId interface_id): {
  205. auto interface = context.specific_interfaces().Get(interface_id);
  206. auto specific_id = pop_specific(interface.specific_id);
  207. return context.specific_interfaces()
  208. .Add({
  209. .interface_id = interface.interface_id,
  210. .specific_id = specific_id,
  211. })
  212. .index;
  213. }
  214. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  215. const auto& old_facet_type_info =
  216. context.facet_types().Get(facet_type_id);
  217. SemIR::FacetTypeInfo new_facet_type_info;
  218. // Since these were added to a stack, we get them back in reverse order.
  219. new_facet_type_info.rewrite_constraints.resize(
  220. old_facet_type_info.rewrite_constraints.size(),
  221. SemIR::FacetTypeInfo::RewriteConstraint::None);
  222. for (auto& new_constraint :
  223. llvm::reverse(new_facet_type_info.rewrite_constraints)) {
  224. auto rhs_id = context.constant_values().Get(worklist.Pop());
  225. auto lhs_id = context.constant_values().Get(worklist.Pop());
  226. new_constraint = {.lhs_const_id = lhs_id, .rhs_const_id = rhs_id};
  227. }
  228. new_facet_type_info.impls_constraints.resize(
  229. old_facet_type_info.impls_constraints.size(),
  230. SemIR::SpecificInterface::None);
  231. for (auto [old_constraint, new_constraint] :
  232. llvm::reverse(llvm::zip(old_facet_type_info.impls_constraints,
  233. new_facet_type_info.impls_constraints))) {
  234. new_constraint = {
  235. .interface_id = old_constraint.interface_id,
  236. .specific_id = pop_specific(old_constraint.specific_id)};
  237. }
  238. new_facet_type_info.other_requirements =
  239. old_facet_type_info.other_requirements;
  240. new_facet_type_info.Canonicalize();
  241. return context.facet_types().Add(new_facet_type_info).index;
  242. }
  243. default:
  244. return arg.value();
  245. }
  246. }
  247. // Pops the operands of the specified instruction off the worklist and rebuilds
  248. // the instruction with the updated operands if it has changed.
  249. static auto Rebuild(Context& context, Worklist& worklist, SemIR::InstId inst_id,
  250. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  251. auto inst = context.insts().Get(inst_id);
  252. // Note that we pop in reverse order because we pushed them in forwards order.
  253. int32_t arg1 = PopOperand(context, worklist, inst.arg1_and_kind());
  254. int32_t arg0 = PopOperand(context, worklist, inst.arg0_and_kind());
  255. int32_t type_id = PopOperand(context, worklist, inst.type_id_and_kind());
  256. if (type_id == inst.type_id().index && arg0 == inst.arg0() &&
  257. arg1 == inst.arg1()) {
  258. return callbacks.ReuseUnchanged(inst_id);
  259. }
  260. // TODO: Do we need to require this type to be complete?
  261. inst.SetType(SemIR::TypeId(type_id));
  262. inst.SetArgs(arg0, arg1);
  263. return callbacks.Rebuild(inst_id, inst);
  264. }
  265. auto SubstInst(Context& context, SemIR::InstId inst_id,
  266. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  267. Worklist worklist(inst_id);
  268. // For each instruction that forms part of the constant, we will visit it
  269. // twice:
  270. //
  271. // - First, we visit it with `is_expanded == false`, we add all of its
  272. // operands onto the worklist, and process them by following this same
  273. // process.
  274. // - Then, once all operands are processed, we visit the instruction with
  275. // `is_expanded == true`, pop the operands back off the worklist, and if any
  276. // of them changed, rebuild this instruction.
  277. //
  278. // The second step is skipped if we can detect in the first step that the
  279. // instruction will not need to be rebuilt.
  280. int index = 0;
  281. while (index != -1) {
  282. auto& item = worklist[index];
  283. if (item.is_expanded) {
  284. // Rebuild this item if necessary. Note that this might pop items from the
  285. // worklist but does not reallocate, so does not invalidate `item`.
  286. item.inst_id = Rebuild(context, worklist, item.inst_id, callbacks);
  287. index = item.next_index;
  288. continue;
  289. }
  290. if (callbacks.Subst(item.inst_id)) {
  291. index = item.next_index;
  292. continue;
  293. }
  294. // Extract the operands of this item into the worklist. Note that this
  295. // modifies the worklist, so it's not safe to use `item` after
  296. // `ExpandOperands` returns.
  297. item.is_expanded = true;
  298. int first_operand = worklist.size();
  299. int next_index = item.next_index;
  300. ExpandOperands(context, worklist, item.inst_id);
  301. // If there are any operands, go and update them before rebuilding this
  302. // item.
  303. if (worklist.size() > first_operand) {
  304. worklist.back().next_index = index;
  305. index = first_operand;
  306. } else {
  307. // No need to rebuild this instruction: its operands can't be changed by
  308. // substitution because it has none.
  309. index = next_index;
  310. }
  311. }
  312. CARBON_CHECK(worklist.size() == 1,
  313. "Unexpected data left behind in work list");
  314. return worklist.back().inst_id;
  315. }
  316. namespace {
  317. // Callbacks for performing substitution of a set of Substitutions into a
  318. // symbolic constant.
  319. class SubstConstantCallbacks final : public SubstInstCallbacks {
  320. public:
  321. // `context` must not be null.
  322. SubstConstantCallbacks(Context* context, Substitutions substitutions)
  323. : context_(context), substitutions_(substitutions) {}
  324. // Applies the given Substitutions to an instruction, in order to replace
  325. // BindSymbolicName instructions with the value of the binding.
  326. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  327. if (context_->constant_values().Get(inst_id).is_concrete()) {
  328. // This instruction is a concrete constant, so can't contain any
  329. // bindings that need to be substituted.
  330. return true;
  331. }
  332. auto entity_name_id = SemIR::EntityNameId::None;
  333. if (auto bind =
  334. context_->insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  335. entity_name_id = bind->entity_name_id;
  336. } else if (auto bind =
  337. context_->insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  338. inst_id)) {
  339. entity_name_id = bind->entity_name_id;
  340. } else {
  341. return false;
  342. }
  343. // This is a symbolic binding. Check if we're substituting it.
  344. // TODO: Consider building a hash map for substitutions. We might have a
  345. // lot of them.
  346. for (auto [bind_index, replacement_id] : substitutions_) {
  347. if (context_->entity_names().Get(entity_name_id).bind_index() ==
  348. bind_index) {
  349. // This is the binding we're replacing. Perform substitution.
  350. inst_id = context_->constant_values().GetInstId(replacement_id);
  351. return true;
  352. }
  353. }
  354. // If it's not being substituted, don't look through it. Its constant
  355. // value doesn't depend on its operand.
  356. return true;
  357. }
  358. // Rebuilds an instruction by building a new constant.
  359. auto Rebuild(SemIR::InstId /*old_inst_id*/, SemIR::Inst new_inst) const
  360. -> SemIR::InstId override {
  361. auto result_id = TryEvalInst(*context_, SemIR::InstId::None, new_inst);
  362. CARBON_CHECK(result_id.is_constant(),
  363. "Substitution into constant produced non-constant");
  364. return context_->constant_values().GetInstId(result_id);
  365. }
  366. private:
  367. Context* context_;
  368. Substitutions substitutions_;
  369. };
  370. } // namespace
  371. auto SubstConstant(Context& context, SemIR::ConstantId const_id,
  372. Substitutions substitutions) -> SemIR::ConstantId {
  373. CARBON_CHECK(const_id.is_constant(), "Substituting into non-constant");
  374. if (substitutions.empty()) {
  375. // Nothing to substitute.
  376. return const_id;
  377. }
  378. if (!const_id.is_symbolic()) {
  379. // A concrete constant can't contain a reference to a symbolic binding.
  380. return const_id;
  381. }
  382. auto subst_inst_id =
  383. SubstInst(context, context.constant_values().GetInstId(const_id),
  384. SubstConstantCallbacks(&context, substitutions));
  385. return context.constant_values().Get(subst_inst_id);
  386. }
  387. } // namespace Carbon::Check