subst.cpp 16 KB

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