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 
13b6eb26fdSRiver Riddle #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
14eb623ae8SStephen Neuendorffer #include "mlir/Interfaces/SideEffectInterfaces.h"
15b6eb26fdSRiver 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,
40*648f34a2SChris Lattner                                       const FrozenRewritePatternSet &patterns,
41*648f34a2SChris Lattner                                       bool useTopDownTraversal)
42*648f34a2SChris Lattner       : PatternRewriter(ctx), matcher(patterns), folder(ctx),
43*648f34a2SChris Lattner         useTopDownTraversal(useTopDownTraversal) {
4464d52014SChris Lattner     worklist.reserve(64);
453e98fbf4SRiver Riddle 
463e98fbf4SRiver Riddle     // Apply a simple cost model based solely on pattern benefit.
473e98fbf4SRiver Riddle     matcher.applyDefaultCostModel();
4864d52014SChris Lattner   }
4964d52014SChris Lattner 
506b1cc3c6SRiver Riddle   bool simplify(MutableArrayRef<Region> regions, int maxIterations);
5164d52014SChris Lattner 
5299b87c97SRiver Riddle   void addToWorklist(Operation *op) {
535c4f1fddSRiver Riddle     // Check to see if the worklist already contains this op.
545c4f1fddSRiver Riddle     if (worklistMap.count(op))
555c4f1fddSRiver Riddle       return;
565c4f1fddSRiver Riddle 
5764d52014SChris Lattner     worklistMap[op] = worklist.size();
5864d52014SChris Lattner     worklist.push_back(op);
5964d52014SChris Lattner   }
6064d52014SChris Lattner 
6199b87c97SRiver Riddle   Operation *popFromWorklist() {
6264d52014SChris Lattner     auto *op = worklist.back();
6364d52014SChris Lattner     worklist.pop_back();
6464d52014SChris Lattner 
6564d52014SChris Lattner     // This operation is no longer in the worklist, keep worklistMap up to date.
6664d52014SChris Lattner     if (op)
6764d52014SChris Lattner       worklistMap.erase(op);
6864d52014SChris Lattner     return op;
6964d52014SChris Lattner   }
7064d52014SChris Lattner 
7164d52014SChris Lattner   /// If the specified operation is in the worklist, remove it.  If not, this is
7264d52014SChris Lattner   /// a no-op.
7399b87c97SRiver Riddle   void removeFromWorklist(Operation *op) {
7464d52014SChris Lattner     auto it = worklistMap.find(op);
7564d52014SChris Lattner     if (it != worklistMap.end()) {
7664d52014SChris Lattner       assert(worklist[it->second] == op && "malformed worklist data structure");
7764d52014SChris Lattner       worklist[it->second] = nullptr;
78c87c7f57SDiego Caballero       worklistMap.erase(it);
7964d52014SChris Lattner     }
8064d52014SChris Lattner   }
8164d52014SChris Lattner 
824bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
834bd9f936SChris Lattner protected:
84851a8516SRiver Riddle   // Implement the hook for inserting operations, and make sure that newly
85851a8516SRiver Riddle   // inserted ops are added to the worklist for processing.
86359164f8SRiver Riddle   void notifyOperationInserted(Operation *op) override { addToWorklist(op); }
8764d52014SChris Lattner 
8864d52014SChris Lattner   // If an operation is about to be removed, make sure it is not in our
8964d52014SChris Lattner   // worklist anymore because we'd get dangling references to it.
9099b87c97SRiver Riddle   void notifyOperationRemoved(Operation *op) override {
91a8866258SRiver Riddle     addToWorklist(op->getOperands());
9255f2e24aSAndy Ly     op->walk([this](Operation *operation) {
9355f2e24aSAndy Ly       removeFromWorklist(operation);
9455f2e24aSAndy Ly       folder.notifyRemoval(operation);
9555f2e24aSAndy Ly     });
9664d52014SChris Lattner   }
9764d52014SChris Lattner 
98085b687fSChris Lattner   // When the root of a pattern is about to be replaced, it can trigger
99085b687fSChris Lattner   // simplifications to its users - make sure to add them to the worklist
100085b687fSChris Lattner   // before the root is changed.
10199b87c97SRiver Riddle   void notifyRootReplaced(Operation *op) override {
10235807bc4SRiver Riddle     for (auto result : op->getResults())
1032bdf33ccSRiver Riddle       for (auto *user : result.getUsers())
1048780d8d8SRiver Riddle         addToWorklist(user);
105085b687fSChris Lattner   }
106085b687fSChris Lattner 
1074bd9f936SChris Lattner private:
10899b87c97SRiver Riddle   // Look over the provided operands for any defining operations that should
109a8866258SRiver Riddle   // be re-added to the worklist. This function should be called when an
110a8866258SRiver Riddle   // operation is modified or removed, as it may trigger further
111a8866258SRiver Riddle   // simplifications.
112361b7d12SChris Lattner   template <typename Operands>
113361b7d12SChris Lattner   void addToWorklist(Operands &&operands) {
114e62a6956SRiver Riddle     for (Value operand : operands) {
115a8866258SRiver Riddle       // If the use count of this operand is now < 2, we re-add the defining
11699b87c97SRiver Riddle       // operation to the worklist.
1179db53a18SRiver Riddle       // TODO: This is based on the fact that zero use operations
118a8866258SRiver Riddle       // may be deleted, and that single use values often have more
119a8866258SRiver Riddle       // canonicalization opportunities.
120d75a611aSRiver Riddle       if (!operand || (!operand.use_empty() && !operand.hasOneUse()))
121a8866258SRiver Riddle         continue;
1222bdf33ccSRiver Riddle       if (auto *defInst = operand.getDefiningOp())
123a8866258SRiver Riddle         addToWorklist(defInst);
124a8866258SRiver Riddle     }
125a8866258SRiver Riddle   }
126a8866258SRiver Riddle 
1273e98fbf4SRiver Riddle   /// The low-level pattern applicator.
1283e98fbf4SRiver Riddle   PatternApplicator matcher;
1294bd9f936SChris Lattner 
1304bd9f936SChris Lattner   /// The worklist for this transformation keeps track of the operations that
1314bd9f936SChris Lattner   /// need to be revisited, plus their index in the worklist.  This allows us to
132e7a2ef21SRiver Riddle   /// efficiently remove operations from the worklist when they are erased, even
133e7a2ef21SRiver Riddle   /// if they aren't the root of a pattern.
13499b87c97SRiver Riddle   std::vector<Operation *> worklist;
13599b87c97SRiver Riddle   DenseMap<Operation *, unsigned> worklistMap;
13660a29837SRiver Riddle 
13760a29837SRiver Riddle   /// Non-pattern based folder for operations.
13860a29837SRiver Riddle   OperationFolder folder;
139*648f34a2SChris Lattner 
140*648f34a2SChris Lattner   /// Whether to use a top-down or bottom-up traversal to seed the initial
141*648f34a2SChris Lattner   /// worklist.
142*648f34a2SChris Lattner   bool useTopDownTraversal;
14364d52014SChris Lattner };
14491f07810SMehdi Amini } // end anonymous namespace
14564d52014SChris Lattner 
146cbcb12fdSUday Bondhugula /// Performs the rewrites while folding and erasing any dead ops. Returns true
147cbcb12fdSUday Bondhugula /// if the rewrite converges in `maxIterations`.
1486b1cc3c6SRiver Riddle bool GreedyPatternRewriteDriver::simplify(MutableArrayRef<Region> regions,
1496b1cc3c6SRiver Riddle                                           int maxIterations) {
150*648f34a2SChris Lattner   // For maximum compatibility with existing passes, do not process existing
151*648f34a2SChris Lattner   // constants unless we're performing a top-down traversal.
152*648f34a2SChris Lattner   // TODO: This is just for compatibility with older MLIR, remove this.
153*648f34a2SChris Lattner   if (useTopDownTraversal) {
154*648f34a2SChris Lattner     // Perform a prepass over the IR to discover constants.
155*648f34a2SChris Lattner     for (auto &region : regions)
156*648f34a2SChris Lattner       folder.processExistingConstants(region);
157*648f34a2SChris Lattner   }
158bcacef1aSRiver Riddle 
1595c757087SFeng Liu   bool changed = false;
160*648f34a2SChris Lattner   int iteration = 0;
1615c757087SFeng Liu   do {
162*648f34a2SChris Lattner     worklist.clear();
163*648f34a2SChris Lattner     worklistMap.clear();
164*648f34a2SChris Lattner 
165*648f34a2SChris Lattner     // Add all nested operations to the worklist in preorder.
1666b1cc3c6SRiver Riddle     for (auto &region : regions)
167*648f34a2SChris Lattner       if (useTopDownTraversal)
168*648f34a2SChris Lattner         region.walk<WalkOrder::PreOrder>(
169*648f34a2SChris Lattner             [this](Operation *op) { worklist.push_back(op); });
170*648f34a2SChris Lattner       else
171*648f34a2SChris Lattner         region.walk([this](Operation *op) { addToWorklist(op); });
172*648f34a2SChris Lattner 
173*648f34a2SChris Lattner     if (useTopDownTraversal) {
174*648f34a2SChris Lattner       // Reverse the list so our pop-back loop processes them in-order.
175*648f34a2SChris Lattner       std::reverse(worklist.begin(), worklist.end());
176*648f34a2SChris Lattner       // Remember the reverse index.
177*648f34a2SChris Lattner       for (size_t i = 0, e = worklist.size(); i != e; ++i)
178*648f34a2SChris Lattner         worklistMap[worklist[i]] = i;
179*648f34a2SChris Lattner     }
1804e40c832SLei Zhang 
1814e40c832SLei Zhang     // These are scratch vectors used in the folding loop below.
182e62a6956SRiver Riddle     SmallVector<Value, 8> originalOperands, resultValues;
18364d52014SChris Lattner 
1845c757087SFeng Liu     changed = false;
18564d52014SChris Lattner     while (!worklist.empty()) {
18664d52014SChris Lattner       auto *op = popFromWorklist();
18764d52014SChris Lattner 
1885c757087SFeng Liu       // Nulls get added to the worklist when operations are removed, ignore
1895c757087SFeng Liu       // them.
19064d52014SChris Lattner       if (op == nullptr)
19164d52014SChris Lattner         continue;
19264d52014SChris Lattner 
1930ddba0bdSRiver Riddle       // If the operation is trivially dead - remove it.
1940ddba0bdSRiver Riddle       if (isOpTriviallyDead(op)) {
1956a501e3dSAndy Ly         notifyOperationRemoved(op);
19664d52014SChris Lattner         op->erase();
197f875e55bSUday Bondhugula         changed = true;
19864d52014SChris Lattner         continue;
19964d52014SChris Lattner       }
20064d52014SChris Lattner 
2014e40c832SLei Zhang       // Collects all the operands and result uses of the given `op` into work
2026a501e3dSAndy Ly       // list. Also remove `op` and nested ops from worklist.
2031982afb1SRiver Riddle       originalOperands.assign(op->operand_begin(), op->operand_end());
2046a501e3dSAndy Ly       auto preReplaceAction = [&](Operation *op) {
205a8866258SRiver Riddle         // Add the operands to the worklist for visitation.
2061982afb1SRiver Riddle         addToWorklist(originalOperands);
2071982afb1SRiver Riddle 
2084e40c832SLei Zhang         // Add all the users of the result to the worklist so we make sure
2094e40c832SLei Zhang         // to revisit them.
21035807bc4SRiver Riddle         for (auto result : op->getResults())
211cc673894SUday Bondhugula           for (auto *userOp : result.getUsers())
212cc673894SUday Bondhugula             addToWorklist(userOp);
2136a501e3dSAndy Ly 
2146a501e3dSAndy Ly         notifyOperationRemoved(op);
2154e40c832SLei Zhang       };
21664d52014SChris Lattner 
217*648f34a2SChris Lattner       // Add the given operation to the worklist.
218*648f34a2SChris Lattner       auto collectOps = [this](Operation *op) { addToWorklist(op); };
219*648f34a2SChris Lattner 
2201982afb1SRiver Riddle       // Try to fold this op.
221cbcb12fdSUday Bondhugula       bool inPlaceUpdate;
222cbcb12fdSUday Bondhugula       if ((succeeded(folder.tryToFold(op, collectOps, preReplaceAction,
223cbcb12fdSUday Bondhugula                                       &inPlaceUpdate)))) {
224f875e55bSUday Bondhugula         changed = true;
225cbcb12fdSUday Bondhugula         if (!inPlaceUpdate)
226934b6d12SChris Lattner           continue;
22764d52014SChris Lattner       }
22864d52014SChris Lattner 
22932052c84SRiver Riddle       // Try to match one of the patterns. The rewriter is automatically
230*648f34a2SChris Lattner       // notified of any necessary changes, so there is nothing else to do
231*648f34a2SChris Lattner       // here.
2323e98fbf4SRiver Riddle       changed |= succeeded(matcher.matchAndRewrite(op, *this));
23364d52014SChris Lattner     }
234a32f0dcbSRiver Riddle 
235*648f34a2SChris Lattner     // After applying patterns, make sure that the CFG of each of the regions
236*648f34a2SChris Lattner     // is kept up to date.
237d75a611aSRiver Riddle     changed |= succeeded(simplifyRegions(*this, regions));
238*648f34a2SChris Lattner   } while (changed && ++iteration < maxIterations);
239*648f34a2SChris Lattner 
2405c757087SFeng Liu   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
2415c757087SFeng Liu   return !changed;
24264d52014SChris Lattner }
24364d52014SChris Lattner 
244e7a2ef21SRiver Riddle /// Rewrite the regions of the specified operation, which must be isolated from
245e7a2ef21SRiver Riddle /// above, by repeatedly applying the highest benefit patterns in a greedy
2463e98fbf4SRiver Riddle /// work-list driven manner. Return success if no more patterns can be matched
2473e98fbf4SRiver Riddle /// in the result operation regions. Note: This does not apply patterns to the
2483e98fbf4SRiver Riddle /// top-level operation itself.
24964d52014SChris Lattner ///
2503e98fbf4SRiver Riddle LogicalResult
2513e98fbf4SRiver Riddle mlir::applyPatternsAndFoldGreedily(Operation *op,
2520b20413eSUday Bondhugula                                    const FrozenRewritePatternSet &patterns,
253*648f34a2SChris Lattner                                    bool useTopDownTraversal) {
254*648f34a2SChris Lattner   return applyPatternsAndFoldGreedily(op, patterns, maxPatternMatchIterations,
255*648f34a2SChris Lattner                                       useTopDownTraversal);
256*648f34a2SChris Lattner }
257*648f34a2SChris Lattner LogicalResult mlir::applyPatternsAndFoldGreedily(
258*648f34a2SChris Lattner     Operation *op, const FrozenRewritePatternSet &patterns,
259*648f34a2SChris Lattner     unsigned maxIterations, bool useTopDownTraversal) {
260*648f34a2SChris Lattner   return applyPatternsAndFoldGreedily(op->getRegions(), patterns, maxIterations,
261*648f34a2SChris Lattner                                       useTopDownTraversal);
2626b1cc3c6SRiver Riddle }
2636b1cc3c6SRiver Riddle /// Rewrite the given regions, which must be isolated from above.
2643e98fbf4SRiver Riddle LogicalResult
2653e98fbf4SRiver Riddle mlir::applyPatternsAndFoldGreedily(MutableArrayRef<Region> regions,
2660b20413eSUday Bondhugula                                    const FrozenRewritePatternSet &patterns,
267*648f34a2SChris Lattner                                    bool useTopDownTraversal) {
268*648f34a2SChris Lattner   return applyPatternsAndFoldGreedily(
269*648f34a2SChris Lattner       regions, patterns, maxPatternMatchIterations, useTopDownTraversal);
270*648f34a2SChris Lattner }
271*648f34a2SChris Lattner LogicalResult mlir::applyPatternsAndFoldGreedily(
272*648f34a2SChris Lattner     MutableArrayRef<Region> regions, const FrozenRewritePatternSet &patterns,
273*648f34a2SChris Lattner     unsigned maxIterations, bool useTopDownTraversal) {
2746b1cc3c6SRiver Riddle   if (regions.empty())
2753e98fbf4SRiver Riddle     return success();
2766b1cc3c6SRiver Riddle 
277e7a2ef21SRiver Riddle   // The top-level operation must be known to be isolated from above to
278e7a2ef21SRiver Riddle   // prevent performing canonicalizations on operations defined at or above
279e7a2ef21SRiver Riddle   // the region containing 'op'.
2806b1cc3c6SRiver Riddle   auto regionIsIsolated = [](Region &region) {
281fe7c0d90SRiver Riddle     return region.getParentOp()->hasTrait<OpTrait::IsIsolatedFromAbove>();
2826b1cc3c6SRiver Riddle   };
2836b1cc3c6SRiver Riddle   (void)regionIsIsolated;
2846b1cc3c6SRiver Riddle   assert(llvm::all_of(regions, regionIsIsolated) &&
2856b1cc3c6SRiver Riddle          "patterns can only be applied to operations IsolatedFromAbove");
286e7a2ef21SRiver Riddle 
2876b1cc3c6SRiver Riddle   // Start the pattern driver.
288*648f34a2SChris Lattner   GreedyPatternRewriteDriver driver(regions[0].getContext(), patterns,
289*648f34a2SChris Lattner                                     useTopDownTraversal);
290fbceee2dSLex Augusteijn   bool converged = driver.simplify(regions, maxIterations);
2915c757087SFeng Liu   LLVM_DEBUG(if (!converged) {
292e7a2ef21SRiver Riddle     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
293d8113cdaSMehdi Amini                  << maxIterations << " times\n";
2945c757087SFeng Liu   });
2953e98fbf4SRiver Riddle   return success(converged);
29664d52014SChris Lattner }
29704b5274eSUday Bondhugula 
29804b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
29904b5274eSUday Bondhugula // OpPatternRewriteDriver
30004b5274eSUday Bondhugula //===----------------------------------------------------------------------===//
30104b5274eSUday Bondhugula 
30204b5274eSUday Bondhugula namespace {
30304b5274eSUday Bondhugula /// This is a simple driver for the PatternMatcher to apply patterns and perform
30404b5274eSUday Bondhugula /// folding on a single op. It repeatedly applies locally optimal patterns.
30504b5274eSUday Bondhugula class OpPatternRewriteDriver : public PatternRewriter {
30604b5274eSUday Bondhugula public:
30704b5274eSUday Bondhugula   explicit OpPatternRewriteDriver(MLIRContext *ctx,
30879d7f618SChris Lattner                                   const FrozenRewritePatternSet &patterns)
3093e98fbf4SRiver Riddle       : PatternRewriter(ctx), matcher(patterns), folder(ctx) {
3103e98fbf4SRiver Riddle     // Apply a simple cost model based solely on pattern benefit.
3113e98fbf4SRiver Riddle     matcher.applyDefaultCostModel();
3123e98fbf4SRiver Riddle   }
31304b5274eSUday Bondhugula 
3143e98fbf4SRiver Riddle   /// Performs the rewrites and folding only on `op`. The simplification
3153e98fbf4SRiver Riddle   /// converges if the op is erased as a result of being folded, replaced, or
3163e98fbf4SRiver Riddle   /// dead, or no more changes happen in an iteration. Returns success if the
3173e98fbf4SRiver Riddle   /// rewrite converges in `maxIterations`. `erased` is set to true if `op` gets
3183e98fbf4SRiver Riddle   /// erased.
3193e98fbf4SRiver Riddle   LogicalResult simplifyLocally(Operation *op, int maxIterations, bool &erased);
32004b5274eSUday Bondhugula 
32104b5274eSUday Bondhugula   // These are hooks implemented for PatternRewriter.
32204b5274eSUday Bondhugula protected:
32304b5274eSUday Bondhugula   /// If an operation is about to be removed, mark it so that we can let clients
32404b5274eSUday Bondhugula   /// know.
32504b5274eSUday Bondhugula   void notifyOperationRemoved(Operation *op) override {
32604b5274eSUday Bondhugula     opErasedViaPatternRewrites = true;
32704b5274eSUday Bondhugula   }
32804b5274eSUday Bondhugula 
32904b5274eSUday Bondhugula   // When a root is going to be replaced, its removal will be notified as well.
33004b5274eSUday Bondhugula   // So there is nothing to do here.
33104b5274eSUday Bondhugula   void notifyRootReplaced(Operation *op) override {}
33204b5274eSUday Bondhugula 
33304b5274eSUday Bondhugula private:
3343e98fbf4SRiver Riddle   /// The low-level pattern applicator.
3353e98fbf4SRiver Riddle   PatternApplicator matcher;
33604b5274eSUday Bondhugula 
33704b5274eSUday Bondhugula   /// Non-pattern based folder for operations.
33804b5274eSUday Bondhugula   OperationFolder folder;
33904b5274eSUday Bondhugula 
34004b5274eSUday Bondhugula   /// Set to true if the operation has been erased via pattern rewrites.
34104b5274eSUday Bondhugula   bool opErasedViaPatternRewrites = false;
34204b5274eSUday Bondhugula };
34304b5274eSUday Bondhugula 
34404b5274eSUday Bondhugula } // anonymous namespace
34504b5274eSUday Bondhugula 
3463e98fbf4SRiver Riddle LogicalResult OpPatternRewriteDriver::simplifyLocally(Operation *op,
3473e98fbf4SRiver Riddle                                                       int maxIterations,
34804b5274eSUday Bondhugula                                                       bool &erased) {
34904b5274eSUday Bondhugula   bool changed = false;
35004b5274eSUday Bondhugula   erased = false;
35104b5274eSUday Bondhugula   opErasedViaPatternRewrites = false;
35204b5274eSUday Bondhugula   int i = 0;
35304b5274eSUday Bondhugula   // Iterate until convergence or until maxIterations. Deletion of the op as
35404b5274eSUday Bondhugula   // a result of being dead or folded is convergence.
35504b5274eSUday Bondhugula   do {
356ff87c4d3SChristian Sigg     changed = false;
357ff87c4d3SChristian Sigg 
35804b5274eSUday Bondhugula     // If the operation is trivially dead - remove it.
35904b5274eSUday Bondhugula     if (isOpTriviallyDead(op)) {
36004b5274eSUday Bondhugula       op->erase();
36104b5274eSUday Bondhugula       erased = true;
3623e98fbf4SRiver Riddle       return success();
36304b5274eSUday Bondhugula     }
36404b5274eSUday Bondhugula 
36504b5274eSUday Bondhugula     // Try to fold this op.
36604b5274eSUday Bondhugula     bool inPlaceUpdate;
36704b5274eSUday Bondhugula     if (succeeded(folder.tryToFold(op, /*processGeneratedConstants=*/nullptr,
36804b5274eSUday Bondhugula                                    /*preReplaceAction=*/nullptr,
36904b5274eSUday Bondhugula                                    &inPlaceUpdate))) {
37004b5274eSUday Bondhugula       changed = true;
37104b5274eSUday Bondhugula       if (!inPlaceUpdate) {
37204b5274eSUday Bondhugula         erased = true;
3733e98fbf4SRiver Riddle         return success();
37404b5274eSUday Bondhugula       }
37504b5274eSUday Bondhugula     }
37604b5274eSUday Bondhugula 
37704b5274eSUday Bondhugula     // Try to match one of the patterns. The rewriter is automatically
37804b5274eSUday Bondhugula     // notified of any necessary changes, so there is nothing else to do here.
3793e98fbf4SRiver Riddle     changed |= succeeded(matcher.matchAndRewrite(op, *this));
38004b5274eSUday Bondhugula     if ((erased = opErasedViaPatternRewrites))
3813e98fbf4SRiver Riddle       return success();
38204b5274eSUday Bondhugula   } while (changed && ++i < maxIterations);
38304b5274eSUday Bondhugula 
38404b5274eSUday Bondhugula   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
3853e98fbf4SRiver Riddle   return failure(changed);
38604b5274eSUday Bondhugula }
38704b5274eSUday Bondhugula 
38804b5274eSUday Bondhugula /// Rewrites only `op` using the supplied canonicalization patterns and
38904b5274eSUday Bondhugula /// folding. `erased` is set to true if the op is erased as a result of being
39004b5274eSUday Bondhugula /// folded, replaced, or dead.
3913e98fbf4SRiver Riddle LogicalResult mlir::applyOpPatternsAndFold(
39279d7f618SChris Lattner     Operation *op, const FrozenRewritePatternSet &patterns, bool *erased) {
39304b5274eSUday Bondhugula   // Start the pattern driver.
39404b5274eSUday Bondhugula   OpPatternRewriteDriver driver(op->getContext(), patterns);
39504b5274eSUday Bondhugula   bool opErased;
3963e98fbf4SRiver Riddle   LogicalResult converged =
39704b5274eSUday Bondhugula       driver.simplifyLocally(op, maxPatternMatchIterations, opErased);
39804b5274eSUday Bondhugula   if (erased)
39904b5274eSUday Bondhugula     *erased = opErased;
4003e98fbf4SRiver Riddle   LLVM_DEBUG(if (failed(converged)) {
40104b5274eSUday Bondhugula     llvm::dbgs() << "The pattern rewrite doesn't converge after scanning "
40204b5274eSUday Bondhugula                  << maxPatternMatchIterations << " times";
40304b5274eSUday Bondhugula   });
40404b5274eSUday Bondhugula   return converged;
40504b5274eSUday Bondhugula }
406