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