• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "mlir/Transforms/Utils.h"
19 #include "llvm/ADT/DenseMapInfo.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/ScopedHashTable.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/RecyclingAllocator.h"
24 #include <deque>
25 
26 using namespace mlir;
27 
28 namespace {
29 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
getHashValue__anon6e87d7f90111::SimpleOperationInfo30   static unsigned getHashValue(const Operation *opC) {
31     return OperationEquivalence::computeHash(const_cast<Operation *>(opC));
32   }
isEqual__anon6e87d7f90111::SimpleOperationInfo33   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
34     auto *lhs = const_cast<Operation *>(lhsC);
35     auto *rhs = const_cast<Operation *>(rhsC);
36     if (lhs == rhs)
37       return true;
38     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
39         rhs == getTombstoneKey() || rhs == getEmptyKey())
40       return false;
41     return OperationEquivalence::isEquivalentTo(const_cast<Operation *>(lhsC),
42                                                 const_cast<Operation *>(rhsC));
43   }
44 };
45 } // end anonymous namespace
46 
47 namespace {
48 /// Simple common sub-expression elimination.
49 struct CSE : public CSEBase<CSE> {
50   /// Shared implementation of operation elimination and scoped map definitions.
51   using AllocatorTy = llvm::RecyclingAllocator<
52       llvm::BumpPtrAllocator,
53       llvm::ScopedHashTableVal<Operation *, Operation *>>;
54   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
55                                             SimpleOperationInfo, AllocatorTy>;
56 
57   /// Represents a single entry in the depth first traversal of a CFG.
58   struct CFGStackNode {
CFGStackNode__anon6e87d7f90211::CSE::CFGStackNode59     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
60         : scope(knownValues), node(node), childIterator(node->begin()),
61           processed(false) {}
62 
63     /// Scope for the known values.
64     ScopedMapTy::ScopeTy scope;
65 
66     DominanceInfoNode *node;
67     DominanceInfoNode::const_iterator childIterator;
68 
69     /// If this node has been fully processed yet or not.
70     bool processed;
71   };
72 
73   /// Attempt to eliminate a redundant operation. Returns success if the
74   /// operation was marked for removal, failure otherwise.
75   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op);
76 
77   void simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
78                      Block *bb);
79   void simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
80                       Region &region);
81 
82   void runOnOperation() override;
83 
84 private:
85   /// Operations marked as dead and to be erased.
86   std::vector<Operation *> opsToErase;
87 };
88 } // end anonymous namespace
89 
90 /// Attempt to eliminate a redundant operation.
simplifyOperation(ScopedMapTy & knownValues,Operation * op)91 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op) {
92   // Don't simplify terminator operations.
93   if (op->isKnownTerminator())
94     return failure();
95 
96   // If the operation is already trivially dead just add it to the erase list.
97   if (isOpTriviallyDead(op)) {
98     opsToErase.push_back(op);
99     ++numDCE;
100     return success();
101   }
102 
103   // Don't simplify operations with nested blocks. We don't currently model
104   // equality comparisons correctly among other things. It is also unclear
105   // whether we would want to CSE such operations.
106   if (op->getNumRegions() != 0)
107     return failure();
108 
109   // TODO: We currently only eliminate non side-effecting
110   // operations.
111   if (!MemoryEffectOpInterface::hasNoEffect(op))
112     return failure();
113 
114   // Look for an existing definition for the operation.
115   if (auto *existing = knownValues.lookup(op)) {
116     // If we find one then replace all uses of the current operation with the
117     // existing one and mark it for deletion.
118     op->replaceAllUsesWith(existing);
119     opsToErase.push_back(op);
120 
121     // If the existing operation has an unknown location and the current
122     // operation doesn't, then set the existing op's location to that of the
123     // current op.
124     if (existing->getLoc().isa<UnknownLoc>() &&
125         !op->getLoc().isa<UnknownLoc>()) {
126       existing->setLoc(op->getLoc());
127     }
128 
129     ++numCSE;
130     return success();
131   }
132 
133   // Otherwise, we add this operation to the known values map.
134   knownValues.insert(op, op);
135   return failure();
136 }
137 
simplifyBlock(ScopedMapTy & knownValues,DominanceInfo & domInfo,Block * bb)138 void CSE::simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
139                         Block *bb) {
140   for (auto &inst : *bb) {
141     // If the operation is simplified, we don't process any held regions.
142     if (succeeded(simplifyOperation(knownValues, &inst)))
143       continue;
144 
145     // If this operation is isolated above, we can't process nested regions with
146     // the given 'knownValues' map. This would cause the insertion of implicit
147     // captures in explicit capture only regions.
148     if (!inst.isRegistered() || inst.isKnownIsolatedFromAbove()) {
149       ScopedMapTy nestedKnownValues;
150       for (auto &region : inst.getRegions())
151         simplifyRegion(nestedKnownValues, domInfo, region);
152       continue;
153     }
154 
155     // Otherwise, process nested regions normally.
156     for (auto &region : inst.getRegions())
157       simplifyRegion(knownValues, domInfo, region);
158   }
159 }
160 
simplifyRegion(ScopedMapTy & knownValues,DominanceInfo & domInfo,Region & region)161 void CSE::simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
162                          Region &region) {
163   // If the region is empty there is nothing to do.
164   if (region.empty())
165     return;
166 
167   // If the region only contains one block, then simplify it directly.
168   if (std::next(region.begin()) == region.end()) {
169     ScopedMapTy::ScopeTy scope(knownValues);
170     simplifyBlock(knownValues, domInfo, &region.front());
171     return;
172   }
173 
174   // If the region does not have dominanceInfo, then skip it.
175   // TODO: Regions without SSA dominance should define a different
176   // traversal order which is appropriate and can be used here.
177   if (!domInfo.hasDominanceInfo(&region))
178     return;
179 
180   // Note, deque is being used here because there was significant performance
181   // gains over vector when the container becomes very large due to the
182   // specific access patterns. If/when these performance issues are no
183   // longer a problem we can change this to vector. For more information see
184   // the llvm mailing list discussion on this:
185   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
186   std::deque<std::unique_ptr<CFGStackNode>> stack;
187 
188   // Process the nodes of the dom tree for this region.
189   stack.emplace_back(std::make_unique<CFGStackNode>(
190       knownValues, domInfo.getRootNode(&region)));
191 
192   while (!stack.empty()) {
193     auto &currentNode = stack.back();
194 
195     // Check to see if we need to process this node.
196     if (!currentNode->processed) {
197       currentNode->processed = true;
198       simplifyBlock(knownValues, domInfo, currentNode->node->getBlock());
199     }
200 
201     // Otherwise, check to see if we need to process a child node.
202     if (currentNode->childIterator != currentNode->node->end()) {
203       auto *childNode = *(currentNode->childIterator++);
204       stack.emplace_back(
205           std::make_unique<CFGStackNode>(knownValues, childNode));
206     } else {
207       // Finally, if the node and all of its children have been processed
208       // then we delete the node.
209       stack.pop_back();
210     }
211   }
212 }
213 
runOnOperation()214 void CSE::runOnOperation() {
215   /// A scoped hash table of defining operations within a region.
216   ScopedMapTy knownValues;
217 
218   DominanceInfo &domInfo = getAnalysis<DominanceInfo>();
219   for (Region &region : getOperation()->getRegions())
220     simplifyRegion(knownValues, domInfo, region);
221 
222   // If no operations were erased, then we mark all analyses as preserved.
223   if (opsToErase.empty())
224     return markAllAnalysesPreserved();
225 
226   /// Erase any operations that were marked as dead during simplification.
227   for (auto *op : opsToErase)
228     op->erase();
229   opsToErase.clear();
230 
231   // We currently don't remove region operations, so mark dominance as
232   // preserved.
233   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
234 }
235 
createCSEPass()236 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
237