164d52014SChris Lattner //===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===//
264d52014SChris Lattner //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
664d52014SChris Lattner //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
864d52014SChris Lattner //
964d52014SChris Lattner // This file implements mlir::applyPatternsGreedily.
1064d52014SChris Lattner //
1164d52014SChris Lattner //===----------------------------------------------------------------------===//
1264d52014SChris Lattner 
137de0da95SChris Lattner #include "mlir/IR/PatternMatch.h"
14*0ddba0bdSRiver Riddle #include "mlir/Interfaces/SideEffects.h"
151982afb1SRiver Riddle #include "mlir/Transforms/FoldUtils.h"
16fafb708bSRiver Riddle #include "mlir/Transforms/RegionUtils.h"
1764d52014SChris Lattner #include "llvm/ADT/DenseMap.h"
185c757087SFeng Liu #include "llvm/Support/CommandLine.h"
195c757087SFeng Liu #include "llvm/Support/Debug.h"
205c757087SFeng Liu #include "llvm/Support/raw_ostream.h"
214e40c832SLei Zhang 
2264d52014SChris Lattner using namespace mlir;
2364d52014SChris Lattner 
245c757087SFeng Liu #define DEBUG_TYPE "pattern-matcher"
255c757087SFeng Liu 
265c757087SFeng Liu static llvm::cl::opt<unsigned> maxPatternMatchIterations(
275c757087SFeng Liu     "mlir-max-pattern-match-iterations",
28e7a2ef21SRiver Riddle     llvm::cl::desc("Max number of iterations scanning for pattern match"),
295c757087SFeng Liu     llvm::cl::init(10));
305c757087SFeng Liu 
3164d52014SChris Lattner namespace {
3264d52014SChris Lattner 
3364d52014SChris Lattner /// This is a worklist-driven driver for the PatternMatcher, which repeatedly
3464d52014SChris Lattner /// applies the locally optimal patterns in a roughly "bottom up" way.
354bd9f936SChris Lattner class GreedyPatternRewriteDriver : public PatternRewriter {
3664d52014SChris Lattner public:
372566a72aSRiver Riddle   explicit GreedyPatternRewriteDriver(MLIRContext *ctx,
385290e8c3SRiver Riddle                                       const OwningRewritePatternList &patterns)
396563b1c4SRiver Riddle       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {
4064d52014SChris Lattner     worklist.reserve(64);
4164d52014SChris Lattner   }
4264d52014SChris Lattner 
435c757087SFeng Liu   /// Perform the rewrites. Return true if the rewrite converges in
445c757087SFeng Liu   /// `maxIterations`.
456b1cc3c6SRiver Riddle   bool simplify(MutableArrayRef<Region> regions, int maxIterations);
4664d52014SChris Lattner 
4799b87c97SRiver Riddle   void addToWorklist(Operation *op) {
485c4f1fddSRiver Riddle     // Check to see if the worklist already contains this op.
495c4f1fddSRiver Riddle     if (worklistMap.count(op))
505c4f1fddSRiver Riddle       return;
515c4f1fddSRiver Riddle 
5264d52014SChris Lattner     worklistMap[op] = worklist.size();
5364d52014SChris Lattner     worklist.push_back(op);
5464d52014SChris Lattner   }
5564d52014SChris Lattner 
5699b87c97SRiver Riddle   Operation *popFromWorklist() {
5764d52014SChris Lattner     auto *op = worklist.back();
5864d52014SChris Lattner     worklist.pop_back();
5964d52014SChris Lattner 
6064d52014SChris Lattner     // This operation is no longer in the worklist, keep worklistMap up to date.
6164d52014SChris Lattner     if (op)
6264d52014SChris Lattner       worklistMap.erase(op);
6364d52014SChris Lattner     return op;
6464d52014SChris Lattner   }
6564d52014SChris Lattner 
6664d52014SChris Lattner   /// If the specified operation is in the worklist, remove it.  If not, this is
6764d52014SChris Lattner   /// a no-op.
6899b87c97SRiver Riddle   void removeFromWorklist(Operation *op) {
6964d52014SChris Lattner     auto it = worklistMap.find(op);
7064d52014SChris Lattner     if (it != worklistMap.end()) {
7164d52014SChris Lattner       assert(worklist[it->second] == op && "malformed worklist data structure");
7264d52014SChris Lattner       worklist[it->second] = nullptr;
73c87c7f57SDiego Caballero       worklistMap.erase(it);
7464d52014SChris Lattner     }
7564d52014SChris Lattner   }
7664d52014SChris Lattner 
774bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
784bd9f936SChris Lattner protected:
79851a8516SRiver Riddle   // Implement the hook for inserting operations, and make sure that newly
80851a8516SRiver Riddle   // inserted ops are added to the worklist for processing.
81851a8516SRiver Riddle   Operation *insert(Operation *op) override {
82851a8516SRiver Riddle     addToWorklist(op);
83851a8516SRiver Riddle     return OpBuilder::insert(op);
844bd9f936SChris Lattner   }
8564d52014SChris Lattner 
8664d52014SChris Lattner   // If an operation is about to be removed, make sure it is not in our
8764d52014SChris Lattner   // worklist anymore because we'd get dangling references to it.
8899b87c97SRiver Riddle   void notifyOperationRemoved(Operation *op) override {
89a8866258SRiver Riddle     addToWorklist(op->getOperands());
9055f2e24aSAndy Ly     op->walk([this](Operation *operation) {
9155f2e24aSAndy Ly       removeFromWorklist(operation);
9255f2e24aSAndy Ly       folder.notifyRemoval(operation);
9355f2e24aSAndy Ly     });
9464d52014SChris Lattner   }
9564d52014SChris Lattner 
96085b687fSChris Lattner   // When the root of a pattern is about to be replaced, it can trigger
97085b687fSChris Lattner   // simplifications to its users - make sure to add them to the worklist
98085b687fSChris Lattner   // before the root is changed.
9999b87c97SRiver Riddle   void notifyRootReplaced(Operation *op) override {
10035807bc4SRiver Riddle     for (auto result : op->getResults())
1012bdf33ccSRiver Riddle       for (auto *user : result.getUsers())
1028780d8d8SRiver Riddle         addToWorklist(user);
103085b687fSChris Lattner   }
104085b687fSChris Lattner 
1054bd9f936SChris Lattner private:
10699b87c97SRiver Riddle   // Look over the provided operands for any defining operations that should
107a8866258SRiver Riddle   // be re-added to the worklist. This function should be called when an
108a8866258SRiver Riddle   // operation is modified or removed, as it may trigger further
109a8866258SRiver Riddle   // simplifications.
110a8866258SRiver Riddle   template <typename Operands> void addToWorklist(Operands &&operands) {
111e62a6956SRiver Riddle     for (Value operand : operands) {
112a8866258SRiver Riddle       // If the use count of this operand is now < 2, we re-add the defining
11399b87c97SRiver Riddle       // operation to the worklist.
11499b87c97SRiver Riddle       // TODO(riverriddle) This is based on the fact that zero use operations
115a8866258SRiver Riddle       // may be deleted, and that single use values often have more
116a8866258SRiver Riddle       // canonicalization opportunities.
1172bdf33ccSRiver Riddle       if (!operand.use_empty() && !operand.hasOneUse())
118a8866258SRiver Riddle         continue;
1192bdf33ccSRiver Riddle       if (auto *defInst = operand.getDefiningOp())
120a8866258SRiver Riddle         addToWorklist(defInst);
121a8866258SRiver Riddle     }
122a8866258SRiver Riddle   }
123a8866258SRiver Riddle 
1244bd9f936SChris Lattner   /// The low-level pattern matcher.
1255de726f4SRiver Riddle   RewritePatternMatcher matcher;
1264bd9f936SChris Lattner 
1274bd9f936SChris Lattner   /// The worklist for this transformation keeps track of the operations that
1284bd9f936SChris Lattner   /// need to be revisited, plus their index in the worklist.  This allows us to
129e7a2ef21SRiver Riddle   /// efficiently remove operations from the worklist when they are erased, even
130e7a2ef21SRiver Riddle   /// if they aren't the root of a pattern.
13199b87c97SRiver Riddle   std::vector<Operation *> worklist;
13299b87c97SRiver Riddle   DenseMap<Operation *, unsigned> worklistMap;
13360a29837SRiver Riddle 
13460a29837SRiver Riddle   /// Non-pattern based folder for operations.
13560a29837SRiver Riddle   OperationFolder folder;
13664d52014SChris Lattner };
13791f07810SMehdi Amini } // end anonymous namespace
13864d52014SChris Lattner 
1394bd9f936SChris Lattner /// Perform the rewrites.
1406b1cc3c6SRiver Riddle bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions,
1416b1cc3c6SRiver Riddle                                           int maxIterations) {
142bcacef1aSRiver Riddle   // Add the given operation to the worklist.
143bcacef1aSRiver Riddle   auto collectOps = [this](Operation *op) { addToWorklist(op); };
144bcacef1aSRiver Riddle 
1455c757087SFeng Liu   bool changed = false;
1465c757087SFeng Liu   int i = 0;
1475c757087SFeng Liu   do {
148e7a2ef21SRiver Riddle     // Add all nested operations to the worklist.
1496b1cc3c6SRiver Riddle     for (auto &region : regions)
150e7a2ef21SRiver Riddle       region.walk(collectOps);
1514e40c832SLei Zhang 
1524e40c832SLei Zhang     // These are scratch vectors used in the folding loop below.
153e62a6956SRiver Riddle     SmallVector<Value, 8> originalOperands, resultValues;
15464d52014SChris Lattner 
1555c757087SFeng Liu     changed = false;
15664d52014SChris Lattner     while (!worklist.empty()) {
15764d52014SChris Lattner       auto *op = popFromWorklist();
15864d52014SChris Lattner 
1595c757087SFeng Liu       // Nulls get added to the worklist when operations are removed, ignore
1605c757087SFeng Liu       // them.
16164d52014SChris Lattner       if (op == nullptr)
16264d52014SChris Lattner         continue;
16364d52014SChris Lattner 
164*0ddba0bdSRiver Riddle       // If the operation is trivially dead - remove it.
165*0ddba0bdSRiver Riddle       if (isOpTriviallyDead(op)) {
1666a501e3dSAndy Ly         notifyOperationRemoved(op);
16764d52014SChris Lattner         op->erase();
16864d52014SChris Lattner         continue;
16964d52014SChris Lattner       }
17064d52014SChris Lattner 
1714e40c832SLei Zhang       // Collects all the operands and result uses of the given `op` into work
1726a501e3dSAndy Ly       // list. Also remove `op` and nested ops from worklist.
1731982afb1SRiver Riddle       originalOperands.assign(op->operand_begin(), op->operand_end());
1746a501e3dSAndy Ly       auto preReplaceAction = [&](Operation *op) {
175a8866258SRiver Riddle         // Add the operands to the worklist for visitation.
1761982afb1SRiver Riddle         addToWorklist(originalOperands);
1771982afb1SRiver Riddle 
1784e40c832SLei Zhang         // Add all the users of the result to the worklist so we make sure
1794e40c832SLei Zhang         // to revisit them.
18035807bc4SRiver Riddle         for (auto result : op->getResults())
1812bdf33ccSRiver Riddle           for (auto *operand : result.getUsers())
1828780d8d8SRiver Riddle             addToWorklist(operand);
1836a501e3dSAndy Ly 
1846a501e3dSAndy Ly         notifyOperationRemoved(op);
1854e40c832SLei Zhang       };
18664d52014SChris Lattner 
1871982afb1SRiver Riddle       // Try to fold this op.
1886a501e3dSAndy Ly       if (succeeded(folder.tryToFold(op, collectOps, preReplaceAction))) {
1895c757087SFeng Liu         changed |= true;
190934b6d12SChris Lattner         continue;
19164d52014SChris Lattner       }
19264d52014SChris Lattner 
19364d52014SChris Lattner       // Make sure that any new operations are inserted at this point.
194eb5ec039SRiver Riddle       setInsertionPoint(op);
1955de726f4SRiver Riddle 
19632052c84SRiver Riddle       // Try to match one of the patterns. The rewriter is automatically
19732052c84SRiver Riddle       // notified of any necessary changes, so there is nothing else to do here.
1983de0c769SRiver Riddle       changed |= matcher.matchAndRewrite(op, *this);
19964d52014SChris Lattner     }
200a32f0dcbSRiver Riddle 
201a32f0dcbSRiver Riddle     // After applying patterns, make sure that the CFG of each of the regions is
202a32f0dcbSRiver Riddle     // kept up to date.
203*0ddba0bdSRiver Riddle     if (succeeded(simplifyRegions(regions))) {
204*0ddba0bdSRiver Riddle       folder.clear();
205*0ddba0bdSRiver Riddle       changed = true;
206*0ddba0bdSRiver Riddle     }
2075c757087SFeng Liu   } while (changed && ++i < maxIterations);
2085c757087SFeng Liu   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
2095c757087SFeng Liu   return !changed;
21064d52014SChris Lattner }
21164d52014SChris Lattner 
212e7a2ef21SRiver Riddle /// Rewrite the regions of the specified operation, which must be isolated from
213e7a2ef21SRiver Riddle /// above, by repeatedly applying the highest benefit patterns in a greedy
214e7a2ef21SRiver Riddle /// work-list driven manner. Return true if no more patterns can be matched in
215e7a2ef21SRiver Riddle /// the result operation regions.
216e7a2ef21SRiver Riddle /// Note: This does not apply patterns to the top-level operation itself.
21764d52014SChris Lattner ///
218e7a2ef21SRiver Riddle bool mlir::applyPatternsGreedily(Operation *op,
2195290e8c3SRiver Riddle                                  const OwningRewritePatternList &patterns) {
2206b1cc3c6SRiver Riddle   return applyPatternsGreedily(op->getRegions(), patterns);
2216b1cc3c6SRiver Riddle }
2226b1cc3c6SRiver Riddle 
2236b1cc3c6SRiver Riddle /// Rewrite the given regions, which must be isolated from above.
2246b1cc3c6SRiver Riddle bool mlir::applyPatternsGreedily(MutableArrayRef<Region> regions,
2256b1cc3c6SRiver Riddle                                  const OwningRewritePatternList &patterns) {
2266b1cc3c6SRiver Riddle   if (regions.empty())
2276b1cc3c6SRiver Riddle     return true;
2286b1cc3c6SRiver Riddle 
229e7a2ef21SRiver Riddle   // The top-level operation must be known to be isolated from above to
230e7a2ef21SRiver Riddle   // prevent performing canonicalizations on operations defined at or above
231e7a2ef21SRiver Riddle   // the region containing 'op'.
2326b1cc3c6SRiver Riddle   auto regionIsIsolated = [](Region &region) {
2336b1cc3c6SRiver Riddle     return region.getParentOp()->isKnownIsolatedFromAbove();
2346b1cc3c6SRiver Riddle   };
2356b1cc3c6SRiver Riddle   (void)regionIsIsolated;
2366b1cc3c6SRiver Riddle   assert(llvm::all_of(regions, regionIsIsolated) &&
2376b1cc3c6SRiver Riddle          "patterns can only be applied to operations IsolatedFromAbove");
238e7a2ef21SRiver Riddle 
2396b1cc3c6SRiver Riddle   // Start the pattern driver.
2406b1cc3c6SRiver Riddle   GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns);
2416b1cc3c6SRiver Riddle   bool converged = driver.simplify(regions, maxPatternMatchIterations);
2425c757087SFeng Liu   LLVM_DEBUG(if (!converged) {
243e7a2ef21SRiver Riddle     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
2445c757087SFeng Liu                  << maxPatternMatchIterations << " times";
2455c757087SFeng Liu   });
2465c757087SFeng Liu   return converged;
24764d52014SChris Lattner }
248