1 //===- CSE.cpp - Common Sub-expression Elimination ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This transformation pass performs a simple common sub-expression elimination
10 // algorithm on operations within a region.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PassDetail.h"
15 #include "mlir/IR/Dominance.h"
16 #include "mlir/Pass/Pass.h"
17 #include "mlir/Transforms/Passes.h"
18 #include "llvm/ADT/DenseMapInfo.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/ScopedHashTable.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/RecyclingAllocator.h"
23 #include <deque>
24 
25 using namespace mlir;
26 
27 namespace {
28 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
29   static unsigned getHashValue(const Operation *opC) {
30     return OperationEquivalence::computeHash(
31         const_cast<Operation *>(opC),
32         /*hashOperands=*/OperationEquivalence::directHashValue,
33         /*hashResults=*/OperationEquivalence::ignoreHashValue,
34         OperationEquivalence::IgnoreLocations);
35   }
36   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
37     auto *lhs = const_cast<Operation *>(lhsC);
38     auto *rhs = const_cast<Operation *>(rhsC);
39     if (lhs == rhs)
40       return true;
41     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
42         rhs == getTombstoneKey() || rhs == getEmptyKey())
43       return false;
44     return OperationEquivalence::isEquivalentTo(
45         const_cast<Operation *>(lhsC), const_cast<Operation *>(rhsC),
46         /*mapOperands=*/OperationEquivalence::exactValueMatch,
47         /*mapResults=*/OperationEquivalence::ignoreValueEquivalence,
48         OperationEquivalence::IgnoreLocations);
49   }
50 };
51 } // namespace
52 
53 namespace {
54 /// Simple common sub-expression elimination.
55 struct CSE : public CSEBase<CSE> {
56   /// Shared implementation of operation elimination and scoped map definitions.
57   using AllocatorTy = llvm::RecyclingAllocator<
58       llvm::BumpPtrAllocator,
59       llvm::ScopedHashTableVal<Operation *, Operation *>>;
60   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
61                                             SimpleOperationInfo, AllocatorTy>;
62 
63   /// Represents a single entry in the depth first traversal of a CFG.
64   struct CFGStackNode {
65     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
66         : scope(knownValues), node(node), childIterator(node->begin()),
67           processed(false) {}
68 
69     /// Scope for the known values.
70     ScopedMapTy::ScopeTy scope;
71 
72     DominanceInfoNode *node;
73     DominanceInfoNode::const_iterator childIterator;
74 
75     /// If this node has been fully processed yet or not.
76     bool processed;
77   };
78 
79   /// Attempt to eliminate a redundant operation. Returns success if the
80   /// operation was marked for removal, failure otherwise.
81   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op,
82                                   bool hasSSADominance);
83   void simplifyBlock(ScopedMapTy &knownValues, Block *bb, bool hasSSADominance);
84   void simplifyRegion(ScopedMapTy &knownValues, Region &region);
85 
86   void runOnOperation() override;
87 
88 private:
89   /// Operations marked as dead and to be erased.
90   std::vector<Operation *> opsToErase;
91   DominanceInfo *domInfo = nullptr;
92 };
93 } // namespace
94 
95 /// Attempt to eliminate a redundant operation.
96 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op,
97                                      bool hasSSADominance) {
98   // Don't simplify terminator operations.
99   if (op->hasTrait<OpTrait::IsTerminator>())
100     return failure();
101 
102   // If the operation is already trivially dead just add it to the erase list.
103   if (isOpTriviallyDead(op)) {
104     opsToErase.push_back(op);
105     ++numDCE;
106     return success();
107   }
108 
109   // Don't simplify operations with nested blocks. We don't currently model
110   // equality comparisons correctly among other things. It is also unclear
111   // whether we would want to CSE such operations.
112   if (op->getNumRegions() != 0)
113     return failure();
114 
115   // TODO: We currently only eliminate non side-effecting
116   // operations.
117   if (!MemoryEffectOpInterface::hasNoEffect(op))
118     return failure();
119 
120   // Look for an existing definition for the operation.
121   if (auto *existing = knownValues.lookup(op)) {
122 
123     // If we find one then replace all uses of the current operation with the
124     // existing one and mark it for deletion. We can only replace an operand in
125     // an operation if it has not been visited yet.
126     if (hasSSADominance) {
127       // If the region has SSA dominance, then we are guaranteed to have not
128       // visited any use of the current operation.
129       op->replaceAllUsesWith(existing);
130       opsToErase.push_back(op);
131     } else {
132       // When the region does not have SSA dominance, we need to check if we
133       // have visited a use before replacing any use.
134       for (auto it : llvm::zip(op->getResults(), existing->getResults())) {
135         std::get<0>(it).replaceUsesWithIf(
136             std::get<1>(it), [&](OpOperand &operand) {
137               return !knownValues.count(operand.getOwner());
138             });
139       }
140 
141       // There may be some remaining uses of the operation.
142       if (op->use_empty())
143         opsToErase.push_back(op);
144     }
145 
146     // If the existing operation has an unknown location and the current
147     // operation doesn't, then set the existing op's location to that of the
148     // current op.
149     if (existing->getLoc().isa<UnknownLoc>() &&
150         !op->getLoc().isa<UnknownLoc>()) {
151       existing->setLoc(op->getLoc());
152     }
153 
154     ++numCSE;
155     return success();
156   }
157 
158   // Otherwise, we add this operation to the known values map.
159   knownValues.insert(op, op);
160   return failure();
161 }
162 
163 void CSE::simplifyBlock(ScopedMapTy &knownValues, Block *bb,
164                         bool hasSSADominance) {
165   for (auto &op : *bb) {
166     // If the operation is simplified, we don't process any held regions.
167     if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance)))
168       continue;
169 
170     // Most operations don't have regions, so fast path that case.
171     if (op.getNumRegions() == 0)
172       continue;
173 
174     // If this operation is isolated above, we can't process nested regions with
175     // the given 'knownValues' map. This would cause the insertion of implicit
176     // captures in explicit capture only regions.
177     if (op.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) {
178       ScopedMapTy nestedKnownValues;
179       for (auto &region : op.getRegions())
180         simplifyRegion(nestedKnownValues, region);
181       continue;
182     }
183 
184     // Otherwise, process nested regions normally.
185     for (auto &region : op.getRegions())
186       simplifyRegion(knownValues, region);
187   }
188 }
189 
190 void CSE::simplifyRegion(ScopedMapTy &knownValues, Region &region) {
191   // If the region is empty there is nothing to do.
192   if (region.empty())
193     return;
194 
195   bool hasSSADominance = domInfo->hasSSADominance(&region);
196 
197   // If the region only contains one block, then simplify it directly.
198   if (region.hasOneBlock()) {
199     ScopedMapTy::ScopeTy scope(knownValues);
200     simplifyBlock(knownValues, &region.front(), hasSSADominance);
201     return;
202   }
203 
204   // If the region does not have dominanceInfo, then skip it.
205   // TODO: Regions without SSA dominance should define a different
206   // traversal order which is appropriate and can be used here.
207   if (!hasSSADominance)
208     return;
209 
210   // Note, deque is being used here because there was significant performance
211   // gains over vector when the container becomes very large due to the
212   // specific access patterns. If/when these performance issues are no
213   // longer a problem we can change this to vector. For more information see
214   // the llvm mailing list discussion on this:
215   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
216   std::deque<std::unique_ptr<CFGStackNode>> stack;
217 
218   // Process the nodes of the dom tree for this region.
219   stack.emplace_back(std::make_unique<CFGStackNode>(
220       knownValues, domInfo->getRootNode(&region)));
221 
222   while (!stack.empty()) {
223     auto &currentNode = stack.back();
224 
225     // Check to see if we need to process this node.
226     if (!currentNode->processed) {
227       currentNode->processed = true;
228       simplifyBlock(knownValues, currentNode->node->getBlock(),
229                     hasSSADominance);
230     }
231 
232     // Otherwise, check to see if we need to process a child node.
233     if (currentNode->childIterator != currentNode->node->end()) {
234       auto *childNode = *(currentNode->childIterator++);
235       stack.emplace_back(
236           std::make_unique<CFGStackNode>(knownValues, childNode));
237     } else {
238       // Finally, if the node and all of its children have been processed
239       // then we delete the node.
240       stack.pop_back();
241     }
242   }
243 }
244 
245 void CSE::runOnOperation() {
246   /// A scoped hash table of defining operations within a region.
247   ScopedMapTy knownValues;
248 
249   domInfo = &getAnalysis<DominanceInfo>();
250   Operation *rootOp = getOperation();
251 
252   for (auto &region : rootOp->getRegions())
253     simplifyRegion(knownValues, region);
254 
255   // If no operations were erased, then we mark all analyses as preserved.
256   if (opsToErase.empty())
257     return markAllAnalysesPreserved();
258 
259   /// Erase any operations that were marked as dead during simplification.
260   for (auto *op : opsToErase)
261     op->erase();
262   opsToErase.clear();
263 
264   // We currently don't remove region operations, so mark dominance as
265   // preserved.
266   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
267   domInfo = nullptr;
268 }
269 
270 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
271