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"
2364d52014SChris Lattner #include "mlir/IR/BuiltinOps.h"
247de0da95SChris Lattner #include "mlir/IR/PatternMatch.h"
2564d52014SChris Lattner #include "llvm/ADT/DenseMap.h"
2664d52014SChris Lattner using namespace mlir;
2764d52014SChris Lattner 
2864d52014SChris Lattner namespace {
2964d52014SChris Lattner 
3064d52014SChris Lattner /// This is a worklist-driven driver for the PatternMatcher, which repeatedly
3164d52014SChris Lattner /// applies the locally optimal patterns in a roughly "bottom up" way.
324bd9f936SChris Lattner class GreedyPatternRewriteDriver : public PatternRewriter {
3364d52014SChris Lattner public:
344bd9f936SChris Lattner   explicit GreedyPatternRewriteDriver(Function *fn,
354bd9f936SChris Lattner                                       OwningRewritePatternList &&patterns)
364bd9f936SChris Lattner       : PatternRewriter(fn->getContext()), matcher(std::move(patterns)),
374bd9f936SChris Lattner         builder(fn) {
3864d52014SChris Lattner     worklist.reserve(64);
394bd9f936SChris Lattner 
404bd9f936SChris Lattner     // Add all operations to the worklist.
41b499277fSRiver Riddle     fn->walk([&](Instruction *inst) { addToWorklist(inst); });
4264d52014SChris Lattner   }
4364d52014SChris Lattner 
444bd9f936SChris Lattner   /// Perform the rewrites.
454bd9f936SChris Lattner   void simplifyFunction();
4664d52014SChris Lattner 
47b499277fSRiver Riddle   void addToWorklist(Instruction *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 
56b499277fSRiver Riddle   Instruction *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.
68b499277fSRiver Riddle   void removeFromWorklist(Instruction *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;
7364d52014SChris Lattner     }
7464d52014SChris Lattner   }
7564d52014SChris Lattner 
764bd9f936SChris Lattner   // These are hooks implemented for PatternRewriter.
774bd9f936SChris Lattner protected:
784bd9f936SChris Lattner   // Implement the hook for creating operations, and make sure that newly
794bd9f936SChris Lattner   // created ops are added to the worklist for processing.
80b499277fSRiver Riddle   Instruction *createOperation(const OperationState &state) override {
814bd9f936SChris Lattner     auto *result = builder.createOperation(state);
824bd9f936SChris Lattner     addToWorklist(result);
834bd9f936SChris Lattner     return result;
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.
88b499277fSRiver Riddle   void notifyOperationRemoved(Instruction *op) override {
894bd9f936SChris Lattner     removeFromWorklist(op);
9064d52014SChris Lattner   }
9164d52014SChris Lattner 
92085b687fSChris Lattner   // When the root of a pattern is about to be replaced, it can trigger
93085b687fSChris Lattner   // simplifications to its users - make sure to add them to the worklist
94085b687fSChris Lattner   // before the root is changed.
95b499277fSRiver Riddle   void notifyRootReplaced(Instruction *op) override {
96085b687fSChris Lattner     for (auto *result : op->getResults())
97085b687fSChris Lattner       // TODO: Add a result->getUsers() iterator.
98b499277fSRiver Riddle       for (auto &user : result->getUses())
99b499277fSRiver Riddle         addToWorklist(user.getOwner());
100085b687fSChris Lattner 
101085b687fSChris Lattner     // TODO: Walk the operand list dropping them as we go.  If any of them
102085b687fSChris Lattner     // drop to zero uses, then add them to the worklist to allow them to be
103085b687fSChris Lattner     // deleted as dead.
104085b687fSChris Lattner   }
105085b687fSChris Lattner 
1064bd9f936SChris Lattner private:
1074bd9f936SChris Lattner   /// The low-level pattern matcher.
1084bd9f936SChris Lattner   PatternMatcher matcher;
1094bd9f936SChris Lattner 
1104bd9f936SChris Lattner   /// This builder is used to create new operations.
1114bd9f936SChris Lattner   FuncBuilder builder;
1124bd9f936SChris Lattner 
1134bd9f936SChris Lattner   /// The worklist for this transformation keeps track of the operations that
1144bd9f936SChris Lattner   /// need to be revisited, plus their index in the worklist.  This allows us to
1154bd9f936SChris Lattner   /// efficiently remove operations from the worklist when they are erased from
1164bd9f936SChris Lattner   /// the function, even if they aren't the root of a pattern.
117b499277fSRiver Riddle   std::vector<Instruction *> worklist;
118b499277fSRiver Riddle   DenseMap<Instruction *, unsigned> worklistMap;
1194bd9f936SChris Lattner 
1204bd9f936SChris Lattner   /// As part of canonicalization, we move constants to the top of the entry
1214bd9f936SChris Lattner   /// block of the current function and de-duplicate them.  This keeps track of
1224bd9f936SChris Lattner   /// constants we have done this for.
123b499277fSRiver Riddle   DenseMap<std::pair<Attribute, Type>, Instruction *> uniquedConstants;
12464d52014SChris Lattner };
1254bd9f936SChris Lattner }; // end anonymous namespace
12664d52014SChris Lattner 
1274bd9f936SChris Lattner /// Perform the rewrites.
1284bd9f936SChris Lattner void GreedyPatternRewriteDriver::simplifyFunction() {
12964d52014SChris Lattner   // These are scratch vectors used in the constant folding loop below.
130792d1c25SRiver Riddle   SmallVector<Attribute, 8> operandConstants, resultConstants;
131934b6d12SChris Lattner   SmallVector<Value *, 8> originalOperands, resultValues;
13264d52014SChris Lattner 
13364d52014SChris Lattner   while (!worklist.empty()) {
13464d52014SChris Lattner     auto *op = popFromWorklist();
13564d52014SChris Lattner 
13664d52014SChris Lattner     // Nulls get added to the worklist when operations are removed, ignore them.
13764d52014SChris Lattner     if (op == nullptr)
13864d52014SChris Lattner       continue;
13964d52014SChris Lattner 
14064d52014SChris Lattner     // If we have a constant op, unique it into the entry block.
14164d52014SChris Lattner     if (auto constant = op->dyn_cast<ConstantOp>()) {
14264d52014SChris Lattner       // If this constant is dead, remove it, being careful to keep
14364d52014SChris Lattner       // uniquedConstants up to date.
14464d52014SChris Lattner       if (constant->use_empty()) {
14564d52014SChris Lattner         auto it =
14664d52014SChris Lattner             uniquedConstants.find({constant->getValue(), constant->getType()});
14764d52014SChris Lattner         if (it != uniquedConstants.end() && it->second == op)
14864d52014SChris Lattner           uniquedConstants.erase(it);
14964d52014SChris Lattner         constant->erase();
15064d52014SChris Lattner         continue;
15164d52014SChris Lattner       }
15264d52014SChris Lattner 
15364d52014SChris Lattner       // Check to see if we already have a constant with this type and value:
15464d52014SChris Lattner       auto &entry = uniquedConstants[std::make_pair(constant->getValue(),
15564d52014SChris Lattner                                                     constant->getType())];
15664d52014SChris Lattner       if (entry) {
15764d52014SChris Lattner         // If this constant is already our uniqued one, then leave it alone.
15864d52014SChris Lattner         if (entry == op)
15964d52014SChris Lattner           continue;
16064d52014SChris Lattner 
16164d52014SChris Lattner         // Otherwise replace this redundant constant with the uniqued one.  We
16264d52014SChris Lattner         // know this is safe because we move constants to the top of the
16364d52014SChris Lattner         // function when they are uniqued, so we know they dominate all uses.
16464d52014SChris Lattner         constant->replaceAllUsesWith(entry->getResult(0));
16564d52014SChris Lattner         constant->erase();
16664d52014SChris Lattner         continue;
16764d52014SChris Lattner       }
16864d52014SChris Lattner 
16964d52014SChris Lattner       // If we have no entry, then we should unique this constant as the
17064d52014SChris Lattner       // canonical version.  To ensure safe dominance, move the operation to the
17164d52014SChris Lattner       // top of the function.
17264d52014SChris Lattner       entry = op;
1734bd9f936SChris Lattner       auto &entryBB = builder.getInsertionBlock()->getFunction()->front();
174471c9764SChris Lattner       op->moveBefore(&entryBB, entryBB.begin());
17564d52014SChris Lattner       continue;
17664d52014SChris Lattner     }
17764d52014SChris Lattner 
17864d52014SChris Lattner     // If the operation has no side effects, and no users, then it is trivially
17964d52014SChris Lattner     // dead - remove it.
18064d52014SChris Lattner     if (op->hasNoSideEffect() && op->use_empty()) {
18164d52014SChris Lattner       op->erase();
18264d52014SChris Lattner       continue;
18364d52014SChris Lattner     }
18464d52014SChris Lattner 
18564d52014SChris Lattner     // Check to see if any operands to the instruction is constant and whether
18664d52014SChris Lattner     // the operation knows how to constant fold itself.
18764d52014SChris Lattner     operandConstants.clear();
18864d52014SChris Lattner     for (auto *operand : op->getOperands()) {
189792d1c25SRiver Riddle       Attribute operandCst;
1905187cfcfSChris Lattner       if (auto *operandOp = operand->getDefiningInst()) {
19164d52014SChris Lattner         if (auto operandConstantOp = operandOp->dyn_cast<ConstantOp>())
19264d52014SChris Lattner           operandCst = operandConstantOp->getValue();
19364d52014SChris Lattner       }
19464d52014SChris Lattner       operandConstants.push_back(operandCst);
19564d52014SChris Lattner     }
19664d52014SChris Lattner 
197934b6d12SChris Lattner     // If this is a commutative binary operation with a constant on the left
198934b6d12SChris Lattner     // side move it to the right side.
199934b6d12SChris Lattner     if (operandConstants.size() == 2 && operandConstants[0] &&
200934b6d12SChris Lattner         !operandConstants[1] && op->isCommutative()) {
201934b6d12SChris Lattner       std::swap(op->getInstOperand(0), op->getInstOperand(1));
202934b6d12SChris Lattner       std::swap(operandConstants[0], operandConstants[1]);
203934b6d12SChris Lattner     }
204934b6d12SChris Lattner 
20564d52014SChris Lattner     // If constant folding was successful, create the result constants, RAUW the
20664d52014SChris Lattner     // operation and remove it.
20764d52014SChris Lattner     resultConstants.clear();
20864d52014SChris Lattner     if (!op->constantFold(operandConstants, resultConstants)) {
2094bd9f936SChris Lattner       builder.setInsertionPoint(op);
21064d52014SChris Lattner 
21164d52014SChris Lattner       for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) {
21264d52014SChris Lattner         auto *res = op->getResult(i);
21364d52014SChris Lattner         if (res->use_empty()) // ignore dead uses.
21464d52014SChris Lattner           continue;
21564d52014SChris Lattner 
21664d52014SChris Lattner         // If we already have a canonicalized version of this constant, just
21764d52014SChris Lattner         // reuse it.  Otherwise create a new one.
2183f190312SChris Lattner         Value *cstValue;
21964d52014SChris Lattner         auto it = uniquedConstants.find({resultConstants[i], res->getType()});
22064d52014SChris Lattner         if (it != uniquedConstants.end())
22164d52014SChris Lattner           cstValue = it->second->getResult(0);
22264d52014SChris Lattner         else
22361ec6c09SLei Zhang           cstValue = create<ConstantOp>(op->getLoc(), res->getType(),
22461ec6c09SLei Zhang                                         resultConstants[i]);
225967d9341SChris Lattner 
226967d9341SChris Lattner         // Add all the users of the result to the worklist so we make sure to
227967d9341SChris Lattner         // revisit them.
228967d9341SChris Lattner         //
229967d9341SChris Lattner         // TODO: Add a result->getUsers() iterator.
230b499277fSRiver Riddle         for (auto &operand : op->getResult(i)->getUses())
231b499277fSRiver Riddle           addToWorklist(operand.getOwner());
232967d9341SChris Lattner 
23364d52014SChris Lattner         res->replaceAllUsesWith(cstValue);
23464d52014SChris Lattner       }
23564d52014SChris Lattner 
23664d52014SChris Lattner       assert(op->hasNoSideEffect() && "Constant folded op with side effects?");
23764d52014SChris Lattner       op->erase();
23864d52014SChris Lattner       continue;
23964d52014SChris Lattner     }
24064d52014SChris Lattner 
241934b6d12SChris Lattner     // Otherwise see if we can use the generic folder API to simplify the
242934b6d12SChris Lattner     // operation.
243934b6d12SChris Lattner     originalOperands.assign(op->operand_begin(), op->operand_end());
244934b6d12SChris Lattner     resultValues.clear();
245934b6d12SChris Lattner     if (!op->fold(resultValues)) {
246934b6d12SChris Lattner       // If the result was an in-place simplification (e.g. max(x,x,y) ->
247934b6d12SChris Lattner       // max(x,y)) then add the original operands to the worklist so we can make
248934b6d12SChris Lattner       // sure to revisit them.
249934b6d12SChris Lattner       if (resultValues.empty()) {
250934b6d12SChris Lattner         // TODO: Walk the original operand list dropping them as we go.  If any
251934b6d12SChris Lattner         // of them drop to zero uses, then add them to the worklist to allow
252934b6d12SChris Lattner         // them to be deleted as dead.
253934b6d12SChris Lattner       } else {
254934b6d12SChris Lattner         // Otherwise, the operation is simplified away completely.
255934b6d12SChris Lattner         assert(resultValues.size() == op->getNumResults());
256934b6d12SChris Lattner 
257934b6d12SChris Lattner         // Add all the users of the operation to the worklist so we make sure to
258934b6d12SChris Lattner         // revisit them.
259934b6d12SChris Lattner         //
260934b6d12SChris Lattner         // TODO: Add a result->getUsers() iterator.
261934b6d12SChris Lattner         for (unsigned i = 0, e = resultValues.size(); i != e; ++i) {
262934b6d12SChris Lattner           auto *res = op->getResult(i);
263934b6d12SChris Lattner           if (res->use_empty()) // ignore dead uses.
264934b6d12SChris Lattner             continue;
265934b6d12SChris Lattner 
266b499277fSRiver Riddle           for (auto &operand : op->getResult(i)->getUses())
267b499277fSRiver Riddle             addToWorklist(operand.getOwner());
268934b6d12SChris Lattner           res->replaceAllUsesWith(resultValues[i]);
269934b6d12SChris Lattner         }
270934b6d12SChris Lattner 
271934b6d12SChris Lattner         op->erase();
272*99fee0b1SRiver Riddle       }
273934b6d12SChris Lattner       continue;
27464d52014SChris Lattner     }
27564d52014SChris Lattner 
27664d52014SChris Lattner     // Check to see if we have any patterns that match this node.
27764d52014SChris Lattner     auto match = matcher.findMatch(op);
27864d52014SChris Lattner     if (!match.first)
27964d52014SChris Lattner       continue;
28064d52014SChris Lattner 
28164d52014SChris Lattner     // Make sure that any new operations are inserted at this point.
2824bd9f936SChris Lattner     builder.setInsertionPoint(op);
2833f2530cdSChris Lattner     // We know that any pattern that matched is RewritePattern because we
2843f2530cdSChris Lattner     // initialized the matcher with RewritePatterns.
2853f2530cdSChris Lattner     auto *rewritePattern = static_cast<RewritePattern *>(match.first);
2864bd9f936SChris Lattner     rewritePattern->rewrite(op, std::move(match.second), *this);
28764d52014SChris Lattner   }
28864d52014SChris Lattner 
28964d52014SChris Lattner   uniquedConstants.clear();
29064d52014SChris Lattner }
29164d52014SChris Lattner 
29264d52014SChris Lattner /// Rewrite the specified function by repeatedly applying the highest benefit
29364d52014SChris Lattner /// patterns in a greedy work-list driven manner.
29464d52014SChris Lattner ///
2953f2530cdSChris Lattner void mlir::applyPatternsGreedily(Function *fn,
2963f2530cdSChris Lattner                                  OwningRewritePatternList &&patterns) {
2974bd9f936SChris Lattner   GreedyPatternRewriteDriver driver(fn, std::move(patterns));
2984bd9f936SChris Lattner   driver.simplifyFunction();
29964d52014SChris Lattner }
300