subst.cpp 18 KB

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