164d52014SChris Lattner //===- GreedyPatternRewriteDriver.cpp - A greedy rewriter -----------------===//
264d52014SChris Lattner //
364d52014SChris Lattner // Copyright 2019 The MLIR Authors.
464d52014SChris Lattner //
564d52014SChris Lattner // Licensed under the Apache License, Version 2.0 (the "License");
664d52014SChris Lattner // you may not use this file except in compliance with the License.
764d52014SChris Lattner // You may obtain a copy of the License at
864d52014SChris Lattner //
964d52014SChris Lattner //   http://www.apache.org/licenses/LICENSE-2.0
1064d52014SChris Lattner //
1164d52014SChris Lattner // Unless required by applicable law or agreed to in writing, software
1264d52014SChris Lattner // distributed under the License is distributed on an "AS IS" BASIS,
1364d52014SChris Lattner // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1464d52014SChris Lattner // See the License for the specific language governing permissions and
1564d52014SChris Lattner // limitations under the License.
1664d52014SChris Lattner // =============================================================================
1764d52014SChris Lattner //
1864d52014SChris Lattner // This file implements mlir::applyPatternsGreedily.
1964d52014SChris Lattner //
2064d52014SChris Lattner //===----------------------------------------------------------------------===//
2164d52014SChris Lattner 
2264d52014SChris Lattner #include "mlir/IR/Builders.h"
237de0da95SChris Lattner #include "mlir/IR/PatternMatch.h"
24f37651c7SRiver Riddle #include "mlir/StandardOps/Ops.h"
254e40c832SLei Zhang #include "mlir/Transforms/ConstantFoldUtils.h"
2664d52014SChris Lattner #include "llvm/ADT/DenseMap.h"
275c757087SFeng Liu #include "llvm/Support/CommandLine.h"
285c757087SFeng Liu #include "llvm/Support/Debug.h"
295c757087SFeng Liu #include "llvm/Support/raw_ostream.h"
304e40c832SLei Zhang 
3164d52014SChris Lattner using namespace mlir;
3264d52014SChris Lattner 
335c757087SFeng Liu #define DEBUG_TYPE "pattern-matcher"
345c757087SFeng Liu 
355c757087SFeng Liu static llvm::cl::opt<unsigned> maxPatternMatchIterations(
365c757087SFeng Liu     "mlir-max-pattern-match-iterations",
375c757087SFeng Liu     llvm::cl::desc(
385c757087SFeng Liu         "Max number of iterations scanning the functions for pattern match"),
395c757087SFeng Liu     llvm::cl::init(10));
405c757087SFeng Liu 
4164d52014SChris Lattner namespace {
4264d52014SChris Lattner 
4364d52014SChris Lattner /// This is a worklist-driven driver for the PatternMatcher, which repeatedly
4464d52014SChris Lattner /// applies the locally optimal patterns in a roughly "bottom up" way.
454bd9f936SChris Lattner class GreedyPatternRewriteDriver : public PatternRewriter {
4664d52014SChris Lattner public:
4746ade282SChris Lattner   explicit GreedyPatternRewriteDriver(Function &fn,
484bd9f936SChris Lattner                                       OwningRewritePatternList &&patterns)
4946ade282SChris Lattner       : PatternRewriter(fn.getContext()), matcher(std::move(patterns), *this),
5046ade282SChris Lattner         builder(&fn) {
5164d52014SChris Lattner     worklist.reserve(64);
5264d52014SChris Lattner   }
5364d52014SChris Lattner 
545c757087SFeng Liu   /// Perform the rewrites. Return true if the rewrite converges in
555c757087SFeng Liu   /// `maxIterations`.
56*2fe8ae4fSJacques Pienaar   bool simplifyFunction(int maxIterations);
5764d52014SChris Lattner 
5899b87c97SRiver Riddle   void addToWorklist(Operation *op) {
595c4f1fddSRiver Riddle     // Check to see if the worklist already contains this op.
605c4f1fddSRiver Riddle     if (worklistMap.count(op))
615c4f1fddSRiver Riddle       return;
625c4f1fddSRiver Riddle 
6364d52014SChris Lattner     worklistMap[op] = worklist.size();
6464d52014SChris Lattner     worklist.push_back(op);
6564d52014SChris Lattner   }
6664d52014SChris Lattner 
6799b87c97SRiver Riddle   Operation *popFromWorklist() {
6864d52014SChris Lattner     auto *op = worklist.back();
6964d52014SChris Lattner     worklist.pop_back();
7064d52014SChris Lattner 
7164d52014SChris Lattner     // This operation is no longer in the worklist, keep worklistMap up to date.
7264d52014SChris Lattner     if (op)
7364d52014SChris Lattner       worklistMap.erase(op);
7464d52014SChris Lattner     return op;
7564d52014SChris Lattner   }
7664d52014SChris Lattner 
7764d52014SChris Lattner   /// If the specified operation is in the worklist, remove it.  If not, this is
7864d52014SChris Lattner   /// a no-op.
7999b87c97SRiver Riddle   void removeFromWorklist(Operation *op) {
8064d52014SChris Lattner     auto it = worklistMap.find(op);
8164d52014SChris Lattner     if (it != worklistMap.end()) {
8264d52014SChris Lattner       assert(worklist[it->second] == op && "malformed worklist data structure");
8364d52014SChris Lattner       worklist[it->second] = nullptr;
8464d52014SChris Lattner     }
8564d52014SChris Lattner   }
8664d52014SChris Lattner 
874bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
884bd9f936SChris Lattner protected:
894bd9f936SChris Lattner   // Implement the hook for creating operations, and make sure that newly
904bd9f936SChris Lattner   // created ops are added to the worklist for processing.
9199b87c97SRiver Riddle   Operation *createOperation(const OperationState &state) override {
924bd9f936SChris Lattner     auto *result = builder.createOperation(state);
934bd9f936SChris Lattner     addToWorklist(result);
944bd9f936SChris Lattner     return result;
954bd9f936SChris Lattner   }
9664d52014SChris Lattner 
9764d52014SChris Lattner   // If an operation is about to be removed, make sure it is not in our
9864d52014SChris Lattner   // worklist anymore because we'd get dangling references to it.
9999b87c97SRiver Riddle   void notifyOperationRemoved(Operation *op) override {
100a8866258SRiver Riddle     addToWorklist(op->getOperands());
1014bd9f936SChris Lattner     removeFromWorklist(op);
10264d52014SChris Lattner   }
10364d52014SChris Lattner 
104085b687fSChris Lattner   // When the root of a pattern is about to be replaced, it can trigger
105085b687fSChris Lattner   // simplifications to its users - make sure to add them to the worklist
106085b687fSChris Lattner   // before the root is changed.
10799b87c97SRiver Riddle   void notifyRootReplaced(Operation *op) override {
108085b687fSChris Lattner     for (auto *result : op->getResults())
109085b687fSChris Lattner       // TODO: Add a result->getUsers() iterator.
110b499277fSRiver Riddle       for (auto &user : result->getUses())
111b499277fSRiver Riddle         addToWorklist(user.getOwner());
112085b687fSChris Lattner   }
113085b687fSChris Lattner 
1144bd9f936SChris Lattner private:
11599b87c97SRiver Riddle   // Look over the provided operands for any defining operations that should
116a8866258SRiver Riddle   // be re-added to the worklist. This function should be called when an
117a8866258SRiver Riddle   // operation is modified or removed, as it may trigger further
118a8866258SRiver Riddle   // simplifications.
119a8866258SRiver Riddle   template <typename Operands> void addToWorklist(Operands &&operands) {
120a8866258SRiver Riddle     for (Value *operand : operands) {
121a8866258SRiver Riddle       // If the use count of this operand is now < 2, we re-add the defining
12299b87c97SRiver Riddle       // operation to the worklist.
12399b87c97SRiver Riddle       // TODO(riverriddle) This is based on the fact that zero use operations
124a8866258SRiver Riddle       // may be deleted, and that single use values often have more
125a8866258SRiver Riddle       // canonicalization opportunities.
1265c757087SFeng Liu       if (!operand->use_empty() && !operand->hasOneUse())
127a8866258SRiver Riddle         continue;
128f9d91531SRiver Riddle       if (auto *defInst = operand->getDefiningOp())
129a8866258SRiver Riddle         addToWorklist(defInst);
130a8866258SRiver Riddle     }
131a8866258SRiver Riddle   }
132a8866258SRiver Riddle 
1334bd9f936SChris Lattner   /// The low-level pattern matcher.
1345de726f4SRiver Riddle   RewritePatternMatcher matcher;
1354bd9f936SChris Lattner 
1364bd9f936SChris Lattner   /// This builder is used to create new operations.
1374bd9f936SChris Lattner   FuncBuilder builder;
1384bd9f936SChris Lattner 
1394bd9f936SChris Lattner   /// The worklist for this transformation keeps track of the operations that
1404bd9f936SChris Lattner   /// need to be revisited, plus their index in the worklist.  This allows us to
1414bd9f936SChris Lattner   /// efficiently remove operations from the worklist when they are erased from
1424bd9f936SChris Lattner   /// the function, even if they aren't the root of a pattern.
14399b87c97SRiver Riddle   std::vector<Operation *> worklist;
14499b87c97SRiver Riddle   DenseMap<Operation *, unsigned> worklistMap;
14564d52014SChris Lattner };
1464bd9f936SChris Lattner }; // end anonymous namespace
14764d52014SChris Lattner 
1484bd9f936SChris Lattner /// Perform the rewrites.
149*2fe8ae4fSJacques Pienaar bool GreedyPatternRewriteDriver::simplifyFunction(int maxIterations) {
1505c757087SFeng Liu   Function *fn = builder.getFunction();
1515c757087SFeng Liu   ConstantFoldHelper helper(fn);
1525c757087SFeng Liu 
1535c757087SFeng Liu   bool changed = false;
1545c757087SFeng Liu   int i = 0;
1555c757087SFeng Liu   do {
1565c757087SFeng Liu     // Add all operations to the worklist.
1575c757087SFeng Liu     fn->walk([&](Operation *op) { addToWorklist(op); });
1584e40c832SLei Zhang 
1594e40c832SLei Zhang     // These are scratch vectors used in the folding loop below.
160934b6d12SChris Lattner     SmallVector<Value *, 8> originalOperands, resultValues;
16164d52014SChris Lattner 
1625c757087SFeng Liu     changed = false;
16364d52014SChris Lattner     while (!worklist.empty()) {
16464d52014SChris Lattner       auto *op = popFromWorklist();
16564d52014SChris Lattner 
1665c757087SFeng Liu       // Nulls get added to the worklist when operations are removed, ignore
1675c757087SFeng Liu       // them.
16864d52014SChris Lattner       if (op == nullptr)
16964d52014SChris Lattner         continue;
17064d52014SChris Lattner 
1715c757087SFeng Liu       // If the operation has no side effects, and no users, then it is
1725c757087SFeng Liu       // trivially dead - remove it.
17364d52014SChris Lattner       if (op->hasNoSideEffect() && op->use_empty()) {
1745c757087SFeng Liu         // Be careful to update bookkeeping in ConstantHelper to keep
1755c757087SFeng Liu         // consistency if this is a constant op.
1764e40c832SLei Zhang         if (op->isa<ConstantOp>())
1774e40c832SLei Zhang           helper.notifyRemoval(op);
17864d52014SChris Lattner         op->erase();
17964d52014SChris Lattner         continue;
18064d52014SChris Lattner       }
18164d52014SChris Lattner 
1824e40c832SLei Zhang       // Collects all the operands and result uses of the given `op` into work
1834e40c832SLei Zhang       // list.
1844e40c832SLei Zhang       auto collectOperandsAndUses = [this](Operation *op) {
185a8866258SRiver Riddle         // Add the operands to the worklist for visitation.
186a8866258SRiver Riddle         addToWorklist(op->getOperands());
1874e40c832SLei Zhang         // Add all the users of the result to the worklist so we make sure
1884e40c832SLei Zhang         // to revisit them.
189967d9341SChris Lattner         //
190967d9341SChris Lattner         // TODO: Add a result->getUsers() iterator.
1914e40c832SLei Zhang         for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) {
192b499277fSRiver Riddle           for (auto &operand : op->getResult(i)->getUses())
193b499277fSRiver Riddle             addToWorklist(operand.getOwner());
19464d52014SChris Lattner         }
1954e40c832SLei Zhang       };
19664d52014SChris Lattner 
1974e40c832SLei Zhang       // Try to constant fold this op.
1984e40c832SLei Zhang       if (helper.tryToConstantFold(op, collectOperandsAndUses)) {
1995c757087SFeng Liu         assert(op->hasNoSideEffect() &&
2005c757087SFeng Liu                "Constant folded op with side effects?");
20164d52014SChris Lattner         op->erase();
2025c757087SFeng Liu         changed |= true;
20364d52014SChris Lattner         continue;
20464d52014SChris Lattner       }
20564d52014SChris Lattner 
206934b6d12SChris Lattner       // Otherwise see if we can use the generic folder API to simplify the
207934b6d12SChris Lattner       // operation.
208934b6d12SChris Lattner       originalOperands.assign(op->operand_begin(), op->operand_end());
209934b6d12SChris Lattner       resultValues.clear();
2105e1f1d2cSRiver Riddle       if (succeeded(op->fold(resultValues))) {
211934b6d12SChris Lattner         // If the result was an in-place simplification (e.g. max(x,x,y) ->
2125c757087SFeng Liu         // max(x,y)) then add the original operands to the worklist so we can
2135c757087SFeng Liu         // make sure to revisit them.
214934b6d12SChris Lattner         if (resultValues.empty()) {
215a8866258SRiver Riddle           // Add the operands back to the worklist as there may be more
216a8866258SRiver Riddle           // canonicalization opportunities now.
217a8866258SRiver Riddle           addToWorklist(originalOperands);
218934b6d12SChris Lattner         } else {
219934b6d12SChris Lattner           // Otherwise, the operation is simplified away completely.
220934b6d12SChris Lattner           assert(resultValues.size() == op->getNumResults());
221934b6d12SChris Lattner 
222a8866258SRiver Riddle           // Notify that we are replacing this operation.
223a8866258SRiver Riddle           notifyRootReplaced(op);
224a8866258SRiver Riddle 
225a8866258SRiver Riddle           // Replace the result values and erase the operation.
226934b6d12SChris Lattner           for (unsigned i = 0, e = resultValues.size(); i != e; ++i) {
227934b6d12SChris Lattner             auto *res = op->getResult(i);
228a8866258SRiver Riddle             if (!res->use_empty())
229934b6d12SChris Lattner               res->replaceAllUsesWith(resultValues[i]);
230934b6d12SChris Lattner           }
231934b6d12SChris Lattner 
232a8866258SRiver Riddle           notifyOperationRemoved(op);
233934b6d12SChris Lattner           op->erase();
23499fee0b1SRiver Riddle         }
2355c757087SFeng Liu         changed |= true;
236934b6d12SChris Lattner         continue;
23764d52014SChris Lattner       }
23864d52014SChris Lattner 
23964d52014SChris Lattner       // Make sure that any new operations are inserted at this point.
2404bd9f936SChris Lattner       builder.setInsertionPoint(op);
2415de726f4SRiver Riddle 
2425de726f4SRiver Riddle       // Try to match one of the canonicalization patterns. The rewriter is
2435c757087SFeng Liu       // automatically notified of any necessary changes, so there is nothing
2445c757087SFeng Liu       // else to do here.
2455c757087SFeng Liu       changed |= matcher.matchAndRewrite(op);
24664d52014SChris Lattner     }
2475c757087SFeng Liu   } while (changed && ++i < maxIterations);
2485c757087SFeng Liu   // Whether the rewrite converges, i.e. wasn't changed in the last iteration.
2495c757087SFeng Liu   return !changed;
25064d52014SChris Lattner }
25164d52014SChris Lattner 
25264d52014SChris Lattner /// Rewrite the specified function by repeatedly applying the highest benefit
2535c757087SFeng Liu /// patterns in a greedy work-list driven manner. Return true if no more
2545c757087SFeng Liu /// patterns can be matched in the result function.
25564d52014SChris Lattner ///
2565c757087SFeng Liu bool mlir::applyPatternsGreedily(Function &fn,
2573f2530cdSChris Lattner                                  OwningRewritePatternList &&patterns) {
2584bd9f936SChris Lattner   GreedyPatternRewriteDriver driver(fn, std::move(patterns));
2595c757087SFeng Liu   bool converged = driver.simplifyFunction(maxPatternMatchIterations);
2605c757087SFeng Liu   LLVM_DEBUG(if (!converged) {
2615c757087SFeng Liu     llvm::dbgs()
2625c757087SFeng Liu         << "The pattern rewrite doesn't converge after scanning the function "
2635c757087SFeng Liu         << maxPatternMatchIterations << " times";
2645c757087SFeng Liu   });
2655c757087SFeng Liu   return converged;
26664d52014SChris Lattner }
267