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 //
9a60fdd2bSLorenzo Chelini // This file implements mlir::applyPatternsAndFoldGreedily.
1064d52014SChris Lattner //
1164d52014SChris Lattner //===----------------------------------------------------------------------===//
1264d52014SChris Lattner 
13*b6eb26fdSRiver Riddle #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
14eb623ae8SStephen Neuendorffer #include "mlir/Interfaces/SideEffectInterfaces.h"
15*b6eb26fdSRiver Riddle #include "mlir/Rewrite/PatternApplicator.h"
161982afb1SRiver Riddle #include "mlir/Transforms/FoldUtils.h"
17fafb708bSRiver Riddle #include "mlir/Transforms/RegionUtils.h"
1864d52014SChris Lattner #include "llvm/ADT/DenseMap.h"
195c757087SFeng Liu #include "llvm/Support/CommandLine.h"
205c757087SFeng Liu #include "llvm/Support/Debug.h"
215c757087SFeng Liu #include "llvm/Support/raw_ostream.h"
224e40c832SLei Zhang 
2364d52014SChris Lattner using namespace mlir;
2464d52014SChris Lattner 
255c757087SFeng Liu #define DEBUG_TYPE "pattern-matcher"
265c757087SFeng Liu 
27400ad6f9SRiver Riddle /// The max number of iterations scanning for pattern match.
28400ad6f9SRiver Riddle static unsigned maxPatternMatchIterations = 10;
295c757087SFeng Liu 
3004b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
3104b5274eSUday Bondhugula // GreedyPatternRewriteDriver
3204b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
3304b5274eSUday Bondhugula 
3464d52014SChris Lattner namespace {
3564d52014SChris Lattner /// This is a worklist-driven driver for the PatternMatcher, which repeatedly
3664d52014SChris Lattner /// applies the locally optimal patterns in a roughly "bottom up" way.
374bd9f936SChris Lattner class GreedyPatternRewriteDriver : public PatternRewriter {
3864d52014SChris Lattner public:
392566a72aSRiver Riddle   explicit GreedyPatternRewriteDriver(MLIRContext *ctx,
405290e8c3SRiver Riddle                                       const OwningRewritePatternList &patterns)
416563b1c4SRiver Riddle       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {
4264d52014SChris Lattner     worklist.reserve(64);
433e98fbf4SRiver Riddle 
443e98fbf4SRiver Riddle     // Apply a simple cost model based solely on pattern benefit.
453e98fbf4SRiver Riddle     matcher.applyDefaultCostModel();
4664d52014SChris Lattner   }
4764d52014SChris Lattner 
486b1cc3c6SRiver Riddle   bool simplify(MutableArrayRef<Region> regions, int maxIterations);
4964d52014SChris Lattner 
5099b87c97SRiver Riddle   void addToWorklist(Operation *op) {
515c4f1fddSRiver Riddle     // Check to see if the worklist already contains this op.
525c4f1fddSRiver Riddle     if (worklistMap.count(op))
535c4f1fddSRiver Riddle       return;
545c4f1fddSRiver Riddle 
5564d52014SChris Lattner     worklistMap[op] = worklist.size();
5664d52014SChris Lattner     worklist.push_back(op);
5764d52014SChris Lattner   }
5864d52014SChris Lattner 
5999b87c97SRiver Riddle   Operation *popFromWorklist() {
6064d52014SChris Lattner     auto *op = worklist.back();
6164d52014SChris Lattner     worklist.pop_back();
6264d52014SChris Lattner 
6364d52014SChris Lattner     // This operation is no longer in the worklist, keep worklistMap up to date.
6464d52014SChris Lattner     if (op)
6564d52014SChris Lattner       worklistMap.erase(op);
6664d52014SChris Lattner     return op;
6764d52014SChris Lattner   }
6864d52014SChris Lattner 
6964d52014SChris Lattner   /// If the specified operation is in the worklist, remove it.  If not, this is
7064d52014SChris Lattner   /// a no-op.
7199b87c97SRiver Riddle   void removeFromWorklist(Operation *op) {
7264d52014SChris Lattner     auto it = worklistMap.find(op);
7364d52014SChris Lattner     if (it != worklistMap.end()) {
7464d52014SChris Lattner       assert(worklist[it->second] == op && "malformed worklist data structure");
7564d52014SChris Lattner       worklist[it->second] = nullptr;
76c87c7f57SDiego Caballero       worklistMap.erase(it);
7764d52014SChris Lattner     }
7864d52014SChris Lattner   }
7964d52014SChris Lattner 
804bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
814bd9f936SChris Lattner protected:
82851a8516SRiver Riddle   // Implement the hook for inserting operations, and make sure that newly
83851a8516SRiver Riddle   // inserted ops are added to the worklist for processing.
84359164f8SRiver Riddle   void notifyOperationInserted(Operation *op) override { addToWorklist(op); }
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.
1103e98fbf4SRiver 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.
1149db53a18SRiver Riddle       // TODO: 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 
1243e98fbf4SRiver Riddle   /// The low-level pattern applicator.
1253e98fbf4SRiver Riddle   PatternApplicator 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 
139cbcb12fdSUday Bondhugula /// Performs the rewrites while folding and erasing any dead ops. Returns true
140cbcb12fdSUday Bondhugula /// if the rewrite converges in `maxIterations`.
1416b1cc3c6SRiver Riddle bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions,
1426b1cc3c6SRiver Riddle                                           int maxIterations) {
143bcacef1aSRiver Riddle   // Add the given operation to the worklist.
144bcacef1aSRiver Riddle   auto collectOps = [this](Operation *op) { addToWorklist(op); };
145bcacef1aSRiver Riddle 
1465c757087SFeng Liu   bool changed = false;
1475c757087SFeng Liu   int i = 0;
1485c757087SFeng Liu   do {
149e7a2ef21SRiver Riddle     // Add all nested operations to the worklist.
1506b1cc3c6SRiver Riddle     for (auto &region : regions)
151e7a2ef21SRiver Riddle       region.walk(collectOps);
1524e40c832SLei Zhang 
1534e40c832SLei Zhang     // These are scratch vectors used in the folding loop below.
154e62a6956SRiver Riddle     SmallVector<Value, 8> originalOperands, resultValues;
15564d52014SChris Lattner 
1565c757087SFeng Liu     changed = false;
15764d52014SChris Lattner     while (!worklist.empty()) {
15864d52014SChris Lattner       auto *op = popFromWorklist();
15964d52014SChris Lattner 
1605c757087SFeng Liu       // Nulls get added to the worklist when operations are removed, ignore
1615c757087SFeng Liu       // them.
16264d52014SChris Lattner       if (op == nullptr)
16364d52014SChris Lattner         continue;
16464d52014SChris Lattner 
1650ddba0bdSRiver Riddle       // If the operation is trivially dead - remove it.
1660ddba0bdSRiver Riddle       if (isOpTriviallyDead(op)) {
1676a501e3dSAndy Ly         notifyOperationRemoved(op);
16864d52014SChris Lattner         op->erase();
169f875e55bSUday Bondhugula         changed = true;
17064d52014SChris Lattner         continue;
17164d52014SChris Lattner       }
17264d52014SChris Lattner 
1734e40c832SLei Zhang       // Collects all the operands and result uses of the given `op` into work
1746a501e3dSAndy Ly       // list. Also remove `op` and nested ops from worklist.
1751982afb1SRiver Riddle       originalOperands.assign(op->operand_begin(), op->operand_end());
1766a501e3dSAndy Ly       auto preReplaceAction = [&](Operation *op) {
177a8866258SRiver Riddle         // Add the operands to the worklist for visitation.
1781982afb1SRiver Riddle         addToWorklist(originalOperands);
1791982afb1SRiver Riddle 
1804e40c832SLei Zhang         // Add all the users of the result to the worklist so we make sure
1814e40c832SLei Zhang         // to revisit them.
18235807bc4SRiver Riddle         for (auto result : op->getResults())
183cc673894SUday Bondhugula           for (auto *userOp : result.getUsers())
184cc673894SUday Bondhugula             addToWorklist(userOp);
1856a501e3dSAndy Ly 
1866a501e3dSAndy Ly         notifyOperationRemoved(op);
1874e40c832SLei Zhang       };
18864d52014SChris Lattner 
1891982afb1SRiver Riddle       // Try to fold this op.
190cbcb12fdSUday Bondhugula       bool inPlaceUpdate;
191cbcb12fdSUday Bondhugula       if ((succeeded(folder.tryToFold(op, collectOps, preReplaceAction,
192cbcb12fdSUday Bondhugula                                       &inPlaceUpdate)))) {
193f875e55bSUday Bondhugula         changed = true;
194cbcb12fdSUday Bondhugula         if (!inPlaceUpdate)
195934b6d12SChris Lattner           continue;
19664d52014SChris Lattner       }
19764d52014SChris Lattner 
19832052c84SRiver Riddle       // Try to match one of the patterns. The rewriter is automatically
19932052c84SRiver Riddle       // notified of any necessary changes, so there is nothing else to do here.
2003e98fbf4SRiver Riddle       changed |= succeeded(matcher.matchAndRewrite(op, *this));
20164d52014SChris Lattner     }
202a32f0dcbSRiver Riddle 
203a32f0dcbSRiver Riddle     // After applying patterns, make sure that the CFG of each of the regions is
204a32f0dcbSRiver Riddle     // kept up to date.
2050ddba0bdSRiver Riddle     if (succeeded(simplifyRegions(regions))) {
2060ddba0bdSRiver Riddle       folder.clear();
2070ddba0bdSRiver Riddle       changed = true;
2080ddba0bdSRiver Riddle     }
2095c757087SFeng Liu   } while (changed && ++i < maxIterations);
2105c757087SFeng Liu   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
2115c757087SFeng Liu   return !changed;
21264d52014SChris Lattner }
21364d52014SChris Lattner 
214e7a2ef21SRiver Riddle /// Rewrite the regions of the specified operation, which must be isolated from
215e7a2ef21SRiver Riddle /// above, by repeatedly applying the highest benefit patterns in a greedy
2163e98fbf4SRiver Riddle /// work-list driven manner. Return success if no more patterns can be matched
2173e98fbf4SRiver Riddle /// in the result operation regions. Note: This does not apply patterns to the
2183e98fbf4SRiver Riddle /// top-level operation itself.
21964d52014SChris Lattner ///
2203e98fbf4SRiver Riddle LogicalResult
2213e98fbf4SRiver Riddle mlir::applyPatternsAndFoldGreedily(Operation *op,
2223e98fbf4SRiver Riddle                                    const OwningRewritePatternList &patterns) {
223a5b9316bSUday Bondhugula   return applyPatternsAndFoldGreedily(op->getRegions(), patterns);
2246b1cc3c6SRiver Riddle }
2256b1cc3c6SRiver Riddle /// Rewrite the given regions, which must be isolated from above.
2263e98fbf4SRiver Riddle LogicalResult
2273e98fbf4SRiver Riddle mlir::applyPatternsAndFoldGreedily(MutableArrayRef<Region> regions,
2283e98fbf4SRiver Riddle                                    const OwningRewritePatternList &patterns) {
2296b1cc3c6SRiver Riddle   if (regions.empty())
2303e98fbf4SRiver Riddle     return success();
2316b1cc3c6SRiver Riddle 
232e7a2ef21SRiver Riddle   // The top-level operation must be known to be isolated from above to
233e7a2ef21SRiver Riddle   // prevent performing canonicalizations on operations defined at or above
234e7a2ef21SRiver Riddle   // the region containing 'op'.
2356b1cc3c6SRiver Riddle   auto regionIsIsolated = [](Region &region) {
2366b1cc3c6SRiver Riddle     return region.getParentOp()->isKnownIsolatedFromAbove();
2376b1cc3c6SRiver Riddle   };
2386b1cc3c6SRiver Riddle   (void)regionIsIsolated;
2396b1cc3c6SRiver Riddle   assert(llvm::all_of(regions, regionIsIsolated) &&
2406b1cc3c6SRiver Riddle          "patterns can only be applied to operations IsolatedFromAbove");
241e7a2ef21SRiver Riddle 
2426b1cc3c6SRiver Riddle   // Start the pattern driver.
2436b1cc3c6SRiver Riddle   GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns);
2446b1cc3c6SRiver Riddle   bool converged = driver.simplify(regions, maxPatternMatchIterations);
2455c757087SFeng Liu   LLVM_DEBUG(if (!converged) {
246e7a2ef21SRiver Riddle     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
2475c757087SFeng Liu                  << maxPatternMatchIterations << " times";
2485c757087SFeng Liu   });
2493e98fbf4SRiver Riddle   return success(converged);
25064d52014SChris Lattner }
25104b5274eSUday Bondhugula 
25204b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
25304b5274eSUday Bondhugula // OpPatternRewriteDriver
25404b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
25504b5274eSUday Bondhugula 
25604b5274eSUday Bondhugula namespace {
25704b5274eSUday Bondhugula /// This is a simple driver for the PatternMatcher to apply patterns and perform
25804b5274eSUday Bondhugula /// folding on a single op. It repeatedly applies locally optimal patterns.
25904b5274eSUday Bondhugula class OpPatternRewriteDriver : public PatternRewriter {
26004b5274eSUday Bondhugula public:
26104b5274eSUday Bondhugula   explicit OpPatternRewriteDriver(MLIRContext *ctx,
26204b5274eSUday Bondhugula                                   const OwningRewritePatternList &patterns)
2633e98fbf4SRiver Riddle       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {
2643e98fbf4SRiver Riddle     // Apply a simple cost model based solely on pattern benefit.
2653e98fbf4SRiver Riddle     matcher.applyDefaultCostModel();
2663e98fbf4SRiver Riddle   }
26704b5274eSUday Bondhugula 
2683e98fbf4SRiver Riddle   /// Performs the rewrites and folding only on `op`. The simplification
2693e98fbf4SRiver Riddle   /// converges if the op is erased as a result of being folded, replaced, or
2703e98fbf4SRiver Riddle   /// dead, or no more changes happen in an iteration. Returns success if the
2713e98fbf4SRiver Riddle   /// rewrite converges in `maxIterations`. `erased` is set to true if `op` gets
2723e98fbf4SRiver Riddle   /// erased.
2733e98fbf4SRiver Riddle   LogicalResult simplifyLocally(Operation *op, int maxIterations, bool &erased);
27404b5274eSUday Bondhugula 
27504b5274eSUday Bondhugula   // These are hooks implemented for PatternRewriter.
27604b5274eSUday Bondhugula protected:
27704b5274eSUday Bondhugula   /// If an operation is about to be removed, mark it so that we can let clients
27804b5274eSUday Bondhugula   /// know.
27904b5274eSUday Bondhugula   void notifyOperationRemoved(Operation *op) override {
28004b5274eSUday Bondhugula     opErasedViaPatternRewrites = true;
28104b5274eSUday Bondhugula   }
28204b5274eSUday Bondhugula 
28304b5274eSUday Bondhugula   // When a root is going to be replaced, its removal will be notified as well.
28404b5274eSUday Bondhugula   // So there is nothing to do here.
28504b5274eSUday Bondhugula   void notifyRootReplaced(Operation *op) override {}
28604b5274eSUday Bondhugula 
28704b5274eSUday Bondhugula private:
2883e98fbf4SRiver Riddle   /// The low-level pattern applicator.
2893e98fbf4SRiver Riddle   PatternApplicator matcher;
29004b5274eSUday Bondhugula 
29104b5274eSUday Bondhugula   /// Non-pattern based folder for operations.
29204b5274eSUday Bondhugula   OperationFolder folder;
29304b5274eSUday Bondhugula 
29404b5274eSUday Bondhugula   /// Set to true if the operation has been erased via pattern rewrites.
29504b5274eSUday Bondhugula   bool opErasedViaPatternRewrites = false;
29604b5274eSUday Bondhugula };
29704b5274eSUday Bondhugula 
29804b5274eSUday Bondhugula } // anonymous namespace
29904b5274eSUday Bondhugula 
3003e98fbf4SRiver Riddle LogicalResult OpPatternRewriteDriver::simplifyLocally(Operation *op,
3013e98fbf4SRiver Riddle                                                       int maxIterations,
30204b5274eSUday Bondhugula                                                       bool &erased) {
30304b5274eSUday Bondhugula   bool changed = false;
30404b5274eSUday Bondhugula   erased = false;
30504b5274eSUday Bondhugula   opErasedViaPatternRewrites = false;
30604b5274eSUday Bondhugula   int i = 0;
30704b5274eSUday Bondhugula   // Iterate until convergence or until maxIterations. Deletion of the op as
30804b5274eSUday Bondhugula   // a result of being dead or folded is convergence.
30904b5274eSUday Bondhugula   do {
310ff87c4d3SChristian Sigg     changed = false;
311ff87c4d3SChristian Sigg 
31204b5274eSUday Bondhugula     // If the operation is trivially dead - remove it.
31304b5274eSUday Bondhugula     if (isOpTriviallyDead(op)) {
31404b5274eSUday Bondhugula       op->erase();
31504b5274eSUday Bondhugula       erased = true;
3163e98fbf4SRiver Riddle       return success();
31704b5274eSUday Bondhugula     }
31804b5274eSUday Bondhugula 
31904b5274eSUday Bondhugula     // Try to fold this op.
32004b5274eSUday Bondhugula     bool inPlaceUpdate;
32104b5274eSUday Bondhugula     if (succeeded(folder.tryToFold(op, /*processGeneratedConstants=*/nullptr,
32204b5274eSUday Bondhugula                                    /*preReplaceAction=*/nullptr,
32304b5274eSUday Bondhugula                                    &inPlaceUpdate))) {
32404b5274eSUday Bondhugula       changed = true;
32504b5274eSUday Bondhugula       if (!inPlaceUpdate) {
32604b5274eSUday Bondhugula         erased = true;
3273e98fbf4SRiver Riddle         return success();
32804b5274eSUday Bondhugula       }
32904b5274eSUday Bondhugula     }
33004b5274eSUday Bondhugula 
33104b5274eSUday Bondhugula     // Try to match one of the patterns. The rewriter is automatically
33204b5274eSUday Bondhugula     // notified of any necessary changes, so there is nothing else to do here.
3333e98fbf4SRiver Riddle     changed |= succeeded(matcher.matchAndRewrite(op, *this));
33404b5274eSUday Bondhugula     if ((erased = opErasedViaPatternRewrites))
3353e98fbf4SRiver Riddle       return success();
33604b5274eSUday Bondhugula   } while (changed && ++i < maxIterations);
33704b5274eSUday Bondhugula 
33804b5274eSUday Bondhugula   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
3393e98fbf4SRiver Riddle   return failure(changed);
34004b5274eSUday Bondhugula }
34104b5274eSUday Bondhugula 
34204b5274eSUday Bondhugula /// Rewrites only `op` using the supplied canonicalization patterns and
34304b5274eSUday Bondhugula /// folding. `erased` is set to true if the op is erased as a result of being
34404b5274eSUday Bondhugula /// folded, replaced, or dead.
3453e98fbf4SRiver Riddle LogicalResult mlir::applyOpPatternsAndFold(
3463e98fbf4SRiver Riddle     Operation *op, const OwningRewritePatternList &patterns, bool *erased) {
34704b5274eSUday Bondhugula   // Start the pattern driver.
34804b5274eSUday Bondhugula   OpPatternRewriteDriver driver(op->getContext(), patterns);
34904b5274eSUday Bondhugula   bool opErased;
3503e98fbf4SRiver Riddle   LogicalResult converged =
35104b5274eSUday Bondhugula       driver.simplifyLocally(op, maxPatternMatchIterations, opErased);
35204b5274eSUday Bondhugula   if (erased)
35304b5274eSUday Bondhugula     *erased = opErased;
3543e98fbf4SRiver Riddle   LLVM_DEBUG(if (failed(converged)) {
35504b5274eSUday Bondhugula     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
35604b5274eSUday Bondhugula                  << maxPatternMatchIterations << " times";
35704b5274eSUday Bondhugula   });
35804b5274eSUday Bondhugula   return converged;
35904b5274eSUday Bondhugula }
360