subst.cpp 16 KB

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