1 //===- CSE.cpp - Common Sub-expression Elimination ------------------------===//
2 //
3 // Part of the MLIR 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 function.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Analysis/Dominance.h"
15 #include "mlir/IR/Attributes.h"
16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/Function.h"
18 #include "mlir/Pass/Pass.h"
19 #include "mlir/Support/Functional.h"
20 #include "mlir/Transforms/Passes.h"
21 #include "mlir/Transforms/Utils.h"
22 #include "llvm/ADT/DenseMapInfo.h"
23 #include "llvm/ADT/Hashing.h"
24 #include "llvm/ADT/ScopedHashTable.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/RecyclingAllocator.h"
27 #include <deque>
28 using namespace mlir;
29 
30 namespace {
31 // TODO(riverriddle) Handle commutative operations.
32 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
33   static unsigned getHashValue(const Operation *opC) {
34     auto *op = const_cast<Operation *>(opC);
35     // Hash the operations based upon their:
36     //   - Operation Name
37     //   - Attributes
38     //   - Result Types
39     //   - Operands
40     return hash_combine(
41         op->getName(), op->getAttrList().getDictionary(),
42         hash_combine_range(op->result_type_begin(), op->result_type_end()),
43         hash_combine_range(op->operand_begin(), op->operand_end()));
44   }
45   static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
46     auto *lhs = const_cast<Operation *>(lhsC);
47     auto *rhs = const_cast<Operation *>(rhsC);
48     if (lhs == rhs)
49       return true;
50     if (lhs == getTombstoneKey() || lhs == getEmptyKey() ||
51         rhs == getTombstoneKey() || rhs == getEmptyKey())
52       return false;
53 
54     // Compare the operation name.
55     if (lhs->getName() != rhs->getName())
56       return false;
57     // Check operand and result type counts.
58     if (lhs->getNumOperands() != rhs->getNumOperands() ||
59         lhs->getNumResults() != rhs->getNumResults())
60       return false;
61     // Compare attributes.
62     if (lhs->getAttrList() != rhs->getAttrList())
63       return false;
64     // Compare operands.
65     if (!std::equal(lhs->operand_begin(), lhs->operand_end(),
66                     rhs->operand_begin()))
67       return false;
68     // Compare result types.
69     return std::equal(lhs->result_type_begin(), lhs->result_type_end(),
70                       rhs->result_type_begin());
71   }
72 };
73 } // end anonymous namespace
74 
75 namespace {
76 /// Simple common sub-expression elimination.
77 struct CSE : public OperationPass<CSE> {
78   CSE() = default;
79   CSE(const CSE &) {}
80 
81   /// Shared implementation of operation elimination and scoped map definitions.
82   using AllocatorTy = llvm::RecyclingAllocator<
83       llvm::BumpPtrAllocator,
84       llvm::ScopedHashTableVal<Operation *, Operation *>>;
85   using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
86                                             SimpleOperationInfo, AllocatorTy>;
87 
88   /// Represents a single entry in the depth first traversal of a CFG.
89   struct CFGStackNode {
90     CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
91         : scope(knownValues), node(node), childIterator(node->begin()),
92           processed(false) {}
93 
94     /// Scope for the known values.
95     ScopedMapTy::ScopeTy scope;
96 
97     DominanceInfoNode *node;
98     DominanceInfoNode::iterator childIterator;
99 
100     /// If this node has been fully processed yet or not.
101     bool processed;
102   };
103 
104   /// Attempt to eliminate a redundant operation. Returns success if the
105   /// operation was marked for removal, failure otherwise.
106   LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op);
107 
108   void simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
109                      Block *bb);
110   void simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
111                       Region &region);
112 
113   void runOnOperation() override;
114 
115 private:
116   /// Operations marked as dead and to be erased.
117   std::vector<Operation *> opsToErase;
118 
119   /// Statistics for CSE.
120   Statistic numCSE{this, "num-cse'd", "Number of operations CSE'd"};
121   Statistic numDCE{this, "num-dce'd", "Number of operations trivially DCE'd"};
122 };
123 } // end anonymous namespace
124 
125 /// Attempt to eliminate a redundant operation.
126 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op) {
127   // Don't simplify operations with nested blocks. We don't currently model
128   // equality comparisons correctly among other things. It is also unclear
129   // whether we would want to CSE such operations.
130   if (op->getNumRegions() != 0)
131     return failure();
132 
133   // TODO(riverriddle) We currently only eliminate non side-effecting
134   // operations.
135   if (!op->hasNoSideEffect())
136     return failure();
137 
138   // If the operation is already trivially dead just add it to the erase list.
139   if (op->use_empty()) {
140     opsToErase.push_back(op);
141     ++numDCE;
142     return success();
143   }
144 
145   // Look for an existing definition for the operation.
146   if (auto *existing = knownValues.lookup(op)) {
147     // If we find one then replace all uses of the current operation with the
148     // existing one and mark it for deletion.
149     op->replaceAllUsesWith(existing);
150     opsToErase.push_back(op);
151 
152     // If the existing operation has an unknown location and the current
153     // operation doesn't, then set the existing op's location to that of the
154     // current op.
155     if (existing->getLoc().isa<UnknownLoc>() &&
156         !op->getLoc().isa<UnknownLoc>()) {
157       existing->setLoc(op->getLoc());
158     }
159 
160     ++numCSE;
161     return success();
162   }
163 
164   // Otherwise, we add this operation to the known values map.
165   knownValues.insert(op, op);
166   return failure();
167 }
168 
169 void CSE::simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo,
170                         Block *bb) {
171   for (auto &inst : *bb) {
172     // If the operation is simplified, we don't process any held regions.
173     if (succeeded(simplifyOperation(knownValues, &inst)))
174       continue;
175 
176     // If this operation is isolated above, we can't process nested regions with
177     // the given 'knownValues' map. This would cause the insertion of implicit
178     // captures in explicit capture only regions.
179     if (!inst.isRegistered() || inst.isKnownIsolatedFromAbove()) {
180       ScopedMapTy nestedKnownValues;
181       for (auto &region : inst.getRegions())
182         simplifyRegion(nestedKnownValues, domInfo, region);
183       continue;
184     }
185 
186     // Otherwise, process nested regions normally.
187     for (auto &region : inst.getRegions())
188       simplifyRegion(knownValues, domInfo, region);
189   }
190 }
191 
192 void CSE::simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo,
193                          Region &region) {
194   // If the region is empty there is nothing to do.
195   if (region.empty())
196     return;
197 
198   // If the region only contains one block, then simplify it directly.
199   if (std::next(region.begin()) == region.end()) {
200     ScopedMapTy::ScopeTy scope(knownValues);
201     simplifyBlock(knownValues, domInfo, &region.front());
202     return;
203   }
204 
205   // Note, deque is being used here because there was significant performance
206   // gains over vector when the container becomes very large due to the
207   // specific access patterns. If/when these performance issues are no
208   // longer a problem we can change this to vector. For more information see
209   // the llvm mailing list discussion on this:
210   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
211   std::deque<std::unique_ptr<CFGStackNode>> stack;
212 
213   // Process the nodes of the dom tree for this region.
214   stack.emplace_back(std::make_unique<CFGStackNode>(
215       knownValues, domInfo.getRootNode(&region)));
216 
217   while (!stack.empty()) {
218     auto &currentNode = stack.back();
219 
220     // Check to see if we need to process this node.
221     if (!currentNode->processed) {
222       currentNode->processed = true;
223       simplifyBlock(knownValues, domInfo, currentNode->node->getBlock());
224     }
225 
226     // Otherwise, check to see if we need to process a child node.
227     if (currentNode->childIterator != currentNode->node->end()) {
228       auto *childNode = *(currentNode->childIterator++);
229       stack.emplace_back(
230           std::make_unique<CFGStackNode>(knownValues, childNode));
231     } else {
232       // Finally, if the node and all of its children have been processed
233       // then we delete the node.
234       stack.pop_back();
235     }
236   }
237 }
238 
239 void CSE::runOnOperation() {
240   /// A scoped hash table of defining operations within a region.
241   ScopedMapTy knownValues;
242 
243   DominanceInfo &domInfo = getAnalysis<DominanceInfo>();
244   for (Region &region : getOperation()->getRegions())
245     simplifyRegion(knownValues, domInfo, region);
246 
247   // If no operations were erased, then we mark all analyses as preserved.
248   if (opsToErase.empty())
249     return markAllAnalysesPreserved();
250 
251   /// Erase any operations that were marked as dead during simplification.
252   for (auto *op : opsToErase)
253     op->erase();
254   opsToErase.clear();
255 
256   // We currently don't remove region operations, so mark dominance as
257   // preserved.
258   markAnalysesPreserved<DominanceInfo, PostDominanceInfo>();
259 }
260 
261 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); }
262 
263 static PassRegistration<CSE> pass("cse", "Eliminate common sub-expressions");
264