subst.cpp 16 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/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.extend_constraints) {
  112. push_specific(interface.specific_id);
  113. }
  114. for (auto interface : facet_type_info.self_impls_constraints) {
  115. push_specific(interface.specific_id);
  116. }
  117. for (auto rewrite : facet_type_info.rewrite_constraints) {
  118. auto lhs_inst_id =
  119. context.constant_values().GetInstId(rewrite.lhs_const_id);
  120. auto rhs_inst_id =
  121. context.constant_values().GetInstId(rewrite.rhs_const_id);
  122. worklist.Push(lhs_inst_id);
  123. worklist.Push(rhs_inst_id);
  124. }
  125. // TODO: Process other requirements as well.
  126. break;
  127. }
  128. default:
  129. break;
  130. }
  131. }
  132. // Converts the operands of this instruction into `InstId`s and pushes them onto
  133. // the worklist.
  134. static auto ExpandOperands(Context& context, Worklist& worklist,
  135. SemIR::InstId inst_id) -> void {
  136. auto inst = context.insts().Get(inst_id);
  137. PushOperand(context, worklist, inst.type_id_and_kind());
  138. PushOperand(context, worklist, inst.arg0_and_kind());
  139. PushOperand(context, worklist, inst.arg1_and_kind());
  140. }
  141. // Pops the specified operand from the worklist and returns it.
  142. static auto PopOperand(Context& context, Worklist& worklist,
  143. SemIR::Inst::ArgAndKind arg) -> int32_t {
  144. auto pop_block_id = [&](SemIR::InstBlockId old_inst_block_id) {
  145. auto size = context.inst_blocks().Get(old_inst_block_id).size();
  146. SemIR::CopyOnWriteInstBlock new_inst_block(&context.sem_ir(),
  147. old_inst_block_id);
  148. for (auto i : llvm::reverse(llvm::seq(size))) {
  149. new_inst_block.Set(i, worklist.Pop());
  150. }
  151. return new_inst_block.GetCanonical();
  152. };
  153. auto pop_specific = [&](SemIR::SpecificId specific_id) {
  154. if (!specific_id.has_value()) {
  155. return specific_id;
  156. }
  157. auto& specific = context.specifics().Get(specific_id);
  158. auto args_id = pop_block_id(specific.args_id);
  159. return context.specifics().GetOrAdd(specific.generic_id, args_id);
  160. };
  161. CARBON_KIND_SWITCH(arg) {
  162. case CARBON_KIND(SemIR::InstId inst_id): {
  163. if (!inst_id.has_value()) {
  164. return arg.value();
  165. }
  166. return worklist.Pop().index;
  167. }
  168. case CARBON_KIND(SemIR::MetaInstId inst_id): {
  169. if (!inst_id.has_value()) {
  170. return arg.value();
  171. }
  172. return worklist.Pop().index;
  173. }
  174. case CARBON_KIND(SemIR::TypeId type_id): {
  175. if (!type_id.has_value()) {
  176. return arg.value();
  177. }
  178. return context.types().GetTypeIdForTypeInstId(worklist.Pop()).index;
  179. }
  180. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  181. return pop_block_id(inst_block_id).index;
  182. }
  183. case CARBON_KIND(SemIR::StructTypeFieldsId old_fields_id): {
  184. auto old_fields = context.struct_type_fields().Get(old_fields_id);
  185. SemIR::CopyOnWriteStructTypeFieldsBlock new_fields(&context.sem_ir(),
  186. old_fields_id);
  187. for (auto i : llvm::reverse(llvm::seq(old_fields.size()))) {
  188. new_fields.Set(i, {.name_id = old_fields[i].name_id,
  189. .type_id = context.types().GetTypeIdForTypeInstId(
  190. worklist.Pop())});
  191. }
  192. return new_fields.GetCanonical().index;
  193. }
  194. case CARBON_KIND(SemIR::TypeBlockId old_type_block_id): {
  195. auto size = context.type_blocks().Get(old_type_block_id).size();
  196. SemIR::CopyOnWriteTypeBlock new_type_block(&context.sem_ir(),
  197. old_type_block_id);
  198. for (auto i : llvm::reverse(llvm::seq(size))) {
  199. new_type_block.Set(
  200. i, context.types().GetTypeIdForTypeInstId(worklist.Pop()));
  201. }
  202. return new_type_block.GetCanonical().index;
  203. }
  204. case CARBON_KIND(SemIR::SpecificId specific_id): {
  205. return pop_specific(specific_id).index;
  206. }
  207. case CARBON_KIND(SemIR::SpecificInterfaceId interface_id): {
  208. auto interface = context.specific_interfaces().Get(interface_id);
  209. auto specific_id = pop_specific(interface.specific_id);
  210. return context.specific_interfaces()
  211. .Add({
  212. .interface_id = interface.interface_id,
  213. .specific_id = specific_id,
  214. })
  215. .index;
  216. }
  217. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  218. const auto& old_facet_type_info =
  219. context.facet_types().Get(facet_type_id);
  220. SemIR::FacetTypeInfo new_facet_type_info;
  221. // Since these were added to a stack, we get them back in reverse order.
  222. new_facet_type_info.rewrite_constraints.resize(
  223. old_facet_type_info.rewrite_constraints.size(),
  224. SemIR::FacetTypeInfo::RewriteConstraint::None);
  225. for (auto& new_constraint :
  226. llvm::reverse(new_facet_type_info.rewrite_constraints)) {
  227. auto rhs_id = context.constant_values().Get(worklist.Pop());
  228. auto lhs_id = context.constant_values().Get(worklist.Pop());
  229. new_constraint = {.lhs_const_id = lhs_id, .rhs_const_id = rhs_id};
  230. }
  231. new_facet_type_info.self_impls_constraints.resize(
  232. old_facet_type_info.self_impls_constraints.size(),
  233. SemIR::SpecificInterface::None);
  234. for (auto [old_constraint, new_constraint] : llvm::reverse(
  235. llvm::zip(old_facet_type_info.self_impls_constraints,
  236. new_facet_type_info.self_impls_constraints))) {
  237. new_constraint = {
  238. .interface_id = old_constraint.interface_id,
  239. .specific_id = pop_specific(old_constraint.specific_id)};
  240. }
  241. new_facet_type_info.extend_constraints.resize(
  242. old_facet_type_info.extend_constraints.size(),
  243. SemIR::SpecificInterface::None);
  244. for (auto [old_constraint, new_constraint] :
  245. llvm::reverse(llvm::zip(old_facet_type_info.extend_constraints,
  246. new_facet_type_info.extend_constraints))) {
  247. new_constraint = {
  248. .interface_id = old_constraint.interface_id,
  249. .specific_id = pop_specific(old_constraint.specific_id)};
  250. }
  251. new_facet_type_info.other_requirements =
  252. old_facet_type_info.other_requirements;
  253. new_facet_type_info.Canonicalize();
  254. return context.facet_types().Add(new_facet_type_info).index;
  255. }
  256. default:
  257. return arg.value();
  258. }
  259. }
  260. // Pops the operands of the specified instruction off the worklist and rebuilds
  261. // the instruction with the updated operands if it has changed.
  262. static auto Rebuild(Context& context, Worklist& worklist, SemIR::InstId inst_id,
  263. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  264. auto inst = context.insts().Get(inst_id);
  265. // Note that we pop in reverse order because we pushed them in forwards order.
  266. int32_t arg1 = PopOperand(context, worklist, inst.arg1_and_kind());
  267. int32_t arg0 = PopOperand(context, worklist, inst.arg0_and_kind());
  268. int32_t type_id = PopOperand(context, worklist, inst.type_id_and_kind());
  269. if (type_id == inst.type_id().index && arg0 == inst.arg0() &&
  270. arg1 == inst.arg1()) {
  271. return callbacks.ReuseUnchanged(inst_id);
  272. }
  273. // TODO: Do we need to require this type to be complete?
  274. inst.SetType(SemIR::TypeId(type_id));
  275. inst.SetArgs(arg0, arg1);
  276. return callbacks.Rebuild(inst_id, inst);
  277. }
  278. auto SubstInst(Context& context, SemIR::InstId inst_id,
  279. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  280. Worklist worklist(inst_id);
  281. // For each instruction that forms part of the constant, we will visit it
  282. // twice:
  283. //
  284. // - First, we visit it with `is_expanded == false`, we add all of its
  285. // operands onto the worklist, and process them by following this same
  286. // process.
  287. // - Then, once all operands are processed, we visit the instruction with
  288. // `is_expanded == true`, pop the operands back off the worklist, and if any
  289. // of them changed, rebuild this instruction.
  290. //
  291. // The second step is skipped if we can detect in the first step that the
  292. // instruction will not need to be rebuilt.
  293. int index = 0;
  294. while (index != -1) {
  295. auto& item = worklist[index];
  296. if (item.is_expanded) {
  297. // Rebuild this item if necessary. Note that this might pop items from the
  298. // worklist but does not reallocate, so does not invalidate `item`.
  299. item.inst_id = Rebuild(context, worklist, item.inst_id, callbacks);
  300. index = item.next_index;
  301. continue;
  302. }
  303. if (callbacks.Subst(item.inst_id)) {
  304. index = item.next_index;
  305. continue;
  306. }
  307. // Extract the operands of this item into the worklist. Note that this
  308. // modifies the worklist, so it's not safe to use `item` after
  309. // `ExpandOperands` returns.
  310. item.is_expanded = true;
  311. int first_operand = worklist.size();
  312. int next_index = item.next_index;
  313. ExpandOperands(context, worklist, item.inst_id);
  314. // If there are any operands, go and update them before rebuilding this
  315. // item.
  316. if (worklist.size() > first_operand) {
  317. worklist.back().next_index = index;
  318. index = first_operand;
  319. } else {
  320. // No need to rebuild this instruction: its operands can't be changed by
  321. // substitution because it has none.
  322. index = next_index;
  323. }
  324. }
  325. CARBON_CHECK(worklist.size() == 1,
  326. "Unexpected data left behind in work list");
  327. return worklist.back().inst_id;
  328. }
  329. namespace {
  330. // Callbacks for performing substitution of a set of Substitutions into a
  331. // symbolic constant.
  332. class SubstConstantCallbacks final : public SubstInstCallbacks {
  333. public:
  334. // `context` must not be null.
  335. SubstConstantCallbacks(Context* context, Substitutions substitutions)
  336. : context_(context), substitutions_(substitutions) {}
  337. // Applies the given Substitutions to an instruction, in order to replace
  338. // BindSymbolicName instructions with the value of the binding.
  339. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  340. if (context_->constant_values().Get(inst_id).is_concrete()) {
  341. // This instruction is a concrete constant, so can't contain any
  342. // bindings that need to be substituted.
  343. return true;
  344. }
  345. auto entity_name_id = SemIR::EntityNameId::None;
  346. if (auto bind =
  347. context_->insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  348. entity_name_id = bind->entity_name_id;
  349. } else if (auto bind =
  350. context_->insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  351. inst_id)) {
  352. entity_name_id = bind->entity_name_id;
  353. } else {
  354. return false;
  355. }
  356. // This is a symbolic binding. Check if we're substituting it.
  357. // TODO: Consider building a hash map for substitutions. We might have a
  358. // lot of them.
  359. for (auto [bind_index, replacement_id] : substitutions_) {
  360. if (context_->entity_names().Get(entity_name_id).bind_index() ==
  361. bind_index) {
  362. // This is the binding we're replacing. Perform substitution.
  363. inst_id = context_->constant_values().GetInstId(replacement_id);
  364. return true;
  365. }
  366. }
  367. // If it's not being substituted, don't look through it. Its constant
  368. // value doesn't depend on its operand.
  369. return true;
  370. }
  371. // Rebuilds an instruction by building a new constant.
  372. auto Rebuild(SemIR::InstId /*old_inst_id*/, SemIR::Inst new_inst) const
  373. -> SemIR::InstId override {
  374. auto result_id = TryEvalInst(*context_, SemIR::InstId::None, new_inst);
  375. CARBON_CHECK(result_id.is_constant(),
  376. "Substitution into constant produced non-constant");
  377. return context_->constant_values().GetInstId(result_id);
  378. }
  379. private:
  380. Context* context_;
  381. Substitutions substitutions_;
  382. };
  383. } // namespace
  384. auto SubstConstant(Context& context, SemIR::ConstantId const_id,
  385. Substitutions substitutions) -> SemIR::ConstantId {
  386. CARBON_CHECK(const_id.is_constant(), "Substituting into non-constant");
  387. if (substitutions.empty()) {
  388. // Nothing to substitute.
  389. return const_id;
  390. }
  391. if (!const_id.is_symbolic()) {
  392. // A concrete constant can't contain a reference to a symbolic binding.
  393. return const_id;
  394. }
  395. auto subst_inst_id =
  396. SubstInst(context, context.constant_values().GetInstId(const_id),
  397. SubstConstantCallbacks(&context, substitutions));
  398. return context.constant_values().Get(subst_inst_id);
  399. }
  400. } // namespace Carbon::Check