MLIR 24.0.0git
CSE.cpp
Go to the documentation of this file.
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 file implements common sub-expression elimination as a library utility.
10// The matching CSE pass is a thin wrapper over the APIs declared here.
11//
12//===----------------------------------------------------------------------===//
13
14#include "mlir/Transforms/CSE.h"
15
16#include "mlir/IR/Dominance.h"
19#include "llvm/ADT/DenseMapInfo.h"
20#include "llvm/ADT/ScopedHashTable.h"
21#include "llvm/Support/Allocator.h"
22#include "llvm/Support/DebugLog.h"
23#include "llvm/Support/RecyclingAllocator.h"
24#include <deque>
25
26using namespace mlir;
27
28#define DEBUG_TYPE "cse"
29
30namespace {
31struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> {
32 static unsigned getHashValue(const Operation *opC) {
34 const_cast<Operation *>(opC),
38 }
39 static bool isEqual(const Operation *lhsC, const Operation *rhsC) {
40 auto *lhs = const_cast<Operation *>(lhsC);
41 auto *rhs = const_cast<Operation *>(rhsC);
42 if (lhs == rhs)
43 return true;
45 const_cast<Operation *>(lhsC), const_cast<Operation *>(rhsC),
47 }
48};
49} // namespace
50
51namespace {
52/// Simple common sub-expression elimination.
53class CSEDriver {
54public:
55 CSEDriver(RewriterBase &rewriter, DominanceInfo *domInfo)
56 : rewriter(rewriter), domInfo(domInfo) {}
57
58 /// Simplify all operations within the given op.
59 void simplify(Operation *op, bool *changed = nullptr);
60
61 /// Simplify operations within the given region.
62 void simplify(Region &region, bool *changed = nullptr);
63
64 int64_t getNumCSE() const { return numCSE; }
65 int64_t getNumDCE() const { return numDCE; }
66
67private:
68 /// Shared implementation of operation elimination and scoped map definitions.
69 using AllocatorTy = llvm::RecyclingAllocator<
70 llvm::BumpPtrAllocator,
71 llvm::ScopedHashTableVal<Operation *, Operation *>>;
72 using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
73 SimpleOperationInfo, AllocatorTy>;
74
75 /// Index writes and unknown effects in block order, retaining each read's
76 /// progress through the index for resource-specific queries.
77 struct MemEffectsCache {
78 SmallVector<Operation *> writes;
80 Operation *lastScanned = nullptr;
81 };
82
83 /// Represents a single entry in the depth first traversal of a CFG.
84 struct CFGStackNode {
85 CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node)
86 : scope(knownValues), node(node), childIterator(node->begin()) {}
87
88 /// Scope for the known values.
89 ScopedMapTy::ScopeTy scope;
90
92 DominanceInfoNode::const_iterator childIterator;
93
94 /// If this node has been fully processed yet or not.
95 bool processed = false;
96 };
97
98 /// Attempt to eliminate a redundant operation. Returns success if the
99 /// operation was marked for removal, failure otherwise.
100 LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op,
101 bool hasSSADominance,
102 MemEffectsCache &memEffectsCache);
103 void simplifyBlock(ScopedMapTy &knownValues, Block *bb, bool hasSSADominance);
104 void simplifyRegion(ScopedMapTy &knownValues, Region &region);
105
106 /// Erase opertion that were marked as dead during simplification, and remove
107 /// their associated dominator trees.
108 void eraseDeadOp(Operation *op);
109
110 void replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
111 Operation *existing, bool hasSSADominance);
112
113 /// Check if there is side-effecting operations other than the given effect
114 /// between the two operations.
115 bool hasOtherSideEffectingOpInBetween(Operation *fromOp, Operation *toOp,
116 MemEffectsCache &memEffectsCache);
117
118 /// A rewriter for modifying the IR.
119 RewriterBase &rewriter;
120
121 DominanceInfo *domInfo = nullptr;
122
123 // Various statistics.
124 int64_t numCSE = 0;
125 int64_t numDCE = 0;
126};
127} // namespace
128
129void CSEDriver::replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
130 Operation *existing,
131 bool hasSSADominance) {
132 // If the existing operation has an unknown location and the current
133 // operation doesn't, then set the existing op's location to that of the
134 // current op.
135 if (isa<UnknownLoc>(existing->getLoc()) && !isa<UnknownLoc>(op->getLoc()))
136 existing->setLoc(op->getLoc());
137
138 ++numCSE;
139
140 // If we find one then replace all uses of the current operation with the
141 // existing one and delete it.
142 if (hasSSADominance) {
143 // If the region has SSA dominance, then we are guaranteed to have not
144 // visited any use of the current operation.
145 // Replace all uses, but do not remove the operation yet.
146 rewriter.replaceAllOpUsesWith(op, existing->getResults());
147 eraseDeadOp(op);
148 return;
149 }
150
151 // When the region does not have SSA dominance, we need to check if we
152 // have visited a use before replacing any use.
153 auto wasVisited = [&](OpOperand &operand) {
154 return !knownValues.count(operand.getOwner());
155 };
156 if (auto *rewriteListener =
157 dyn_cast_if_present<RewriterBase::Listener>(rewriter.getListener()))
158 for (Value v : op->getResults())
159 if (all_of(v.getUses(), wasVisited))
160 rewriteListener->notifyOperationReplaced(op, existing);
161
162 // Replace all uses, but do not remove the operation yet. This does not
163 // notify the listener because the original op is not erased.
164 rewriter.replaceUsesWithIf(op->getResults(), existing->getResults(),
165 wasVisited);
166
167 // There may be some remaining uses of the operation.
168 if (op->use_empty())
169 eraseDeadOp(op);
170}
171
172bool CSEDriver::hasOtherSideEffectingOpInBetween(Operation *fromOp,
173 Operation *toOp,
174 MemEffectsCache &cache) {
175 assert(fromOp->getBlock() == toOp->getBlock());
176 assert(hasEffect<MemoryEffects::Read>(fromOp) &&
177 "expected read effect on fromOp");
178 assert(hasEffect<MemoryEffects::Read>(toOp) &&
179 "expected read effect on toOp");
180 if (fromOp->getNextNode() == toOp)
181 return false;
182
183 SmallVector<MemoryEffects::EffectInstance> readEffects;
184 cast<MemoryEffectOpInterface>(fromOp).getEffects(readEffects);
185 auto getEffects = [](Operation *op) {
186 LDBG() << "CSE checking effects: " << op->getName();
187 // TODO: Cache recursive effects in shared infrastructure to avoid quadratic
188 // walks when CSE also visits nested operations.
189 return getEffectsRecursively(op);
190 };
191 auto canConflict = [&](const auto &effects) {
192 if (!effects)
193 return true;
194 return llvm::any_of(*effects, [&](const auto &effect) {
195 if (!isa<MemoryEffects::Write>(effect.getEffect()))
196 return false;
197 SideEffects::Resource *writeResource = effect.getResource();
198 return llvm::any_of(readEffects, [&](const auto &readEffect) {
199 SideEffects::Resource *readResource = readEffect.getResource();
200 if (writeResource->isDisjointFrom(readResource))
201 return false;
202 if (readEffect.getValue() && !writeResource->isAddressable())
203 return false;
204 if (effect.getValue() && !readResource->isAddressable())
205 return false;
206 return true;
207 });
208 });
209 };
210
211 auto isBefore = [](Operation *a, Operation *b) {
212 return a->isBeforeInBlock(b);
213 };
214 auto first = llvm::upper_bound(cache.writes, fromOp, isBefore);
215 unsigned &nextWrite = cache.nextWrite[fromOp];
216 nextWrite = std::max(nextWrite, unsigned(first - cache.writes.begin()));
217 for (; nextWrite < cache.writes.size(); ++nextWrite)
218 if (canConflict(getEffects(cache.writes[nextWrite])))
219 return true;
220
221 // Index only already simplified operations: the query endpoint may be erased.
222 for (Operation *op = cache.lastScanned->getNextNode(); op != toOp;
223 op = op->getNextNode()) {
224 cache.lastScanned = op;
225 auto effects = getEffects(op);
226 if (effects && llvm::none_of(*effects, [](const auto &effect) {
227 return isa<MemoryEffects::Write>(effect.getEffect());
228 }))
229 continue;
230 cache.writes.push_back(op);
231 if (fromOp->isBeforeInBlock(op) && canConflict(effects))
232 return true;
233 nextWrite = cache.writes.size();
234 }
235 return false;
236}
237
238/// Attempt to eliminate a redundant operation.
239LogicalResult CSEDriver::simplifyOperation(ScopedMapTy &knownValues,
240 Operation *op, bool hasSSADominance,
241 MemEffectsCache &memEffectsCache) {
242 // Don't simplify terminator operations.
243 if (op->hasTrait<OpTrait::IsTerminator>())
244 return failure();
245
246 // Don't simplify operations with regions that have multiple blocks.
247 // TODO: We need additional tests to verify that we handle such IR correctly.
248 if (!llvm::all_of(op->getRegions(),
249 [](Region &r) { return r.empty() || r.hasOneBlock(); }))
250 return failure();
251
252 // Some simple use case of operation with memory side-effect are dealt with
253 // here. Operations with no side-effect are done after.
254 if (!isMemoryEffectFree(op)) {
255 // TODO: Only basic use case for operations with MemoryEffects::Read can be
256 // eleminated now. More work needs to be done for more complicated patterns
257 // and other side-effects.
259 return failure();
260
261 if (!memEffectsCache.lastScanned)
262 memEffectsCache.lastScanned = op;
263
264 // Look for an existing definition for the operation.
265 if (auto *existing = knownValues.lookup(op)) {
266 if (existing->getBlock() == op->getBlock() &&
267 !hasOtherSideEffectingOpInBetween(existing, op, memEffectsCache)) {
268 // The operation that can be deleted has been reach with no
269 // side-effecting operations in between the existing operation and
270 // this one so we can remove the duplicate.
271 replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
272 return success();
273 }
274 }
275 knownValues.insert(op, op);
276 return failure();
277 }
278
279 // Look for an existing definition for the operation.
280 if (auto *existing = knownValues.lookup(op)) {
281 replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
282 return success();
283 }
284
285 // Otherwise, we add this operation to the known values map.
286 knownValues.insert(op, op);
287 return failure();
288}
289
290void CSEDriver::simplifyBlock(ScopedMapTy &knownValues, Block *bb,
291 bool hasSSADominance) {
292 MemEffectsCache memEffectsCache;
293 for (auto &op : llvm::make_early_inc_range(*bb)) {
294 // If the operation is already trivially dead just add it to the erase list.
295 // This also avoids calling `simplifyRegion` on dead region ops
296 // unnecessarily.
297 if (isOpTriviallyDead(&op)) {
298 eraseDeadOp(&op);
299 ++numDCE;
300 continue;
301 }
302
303 // Most operations don't have regions, so fast path that case.
304 if (op.getNumRegions() != 0) {
305 // If this operation is isolated above, we can't process nested regions
306 // with the given 'knownValues' map. This would cause the insertion of
307 // implicit captures in explicit capture only regions.
308 if (op.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) {
309 ScopedMapTy nestedKnownValues;
310 for (auto &region : op.getRegions())
311 simplifyRegion(nestedKnownValues, region);
312 } else {
313 // Otherwise, process nested regions normally.
314 for (auto &region : op.getRegions())
315 simplifyRegion(knownValues, region);
316 }
317 }
318
319 // If the operation is simplified, we don't process any held regions.
320 if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance,
321 memEffectsCache)))
322 continue;
323 }
324}
325
326void CSEDriver::simplifyRegion(ScopedMapTy &knownValues, Region &region) {
327 // If the region is empty there is nothing to do.
328 if (region.empty())
329 return;
330
331 bool hasSSADominance = domInfo->hasSSADominance(&region);
332
333 // If the region only contains one block, then simplify it directly.
334 if (region.hasOneBlock()) {
335 ScopedMapTy::ScopeTy scope(knownValues);
336 simplifyBlock(knownValues, &region.front(), hasSSADominance);
337 return;
338 }
339
340 // If the region does not have dominanceInfo, then skip it.
341 // TODO: Regions without SSA dominance should define a different
342 // traversal order which is appropriate and can be used here.
343 if (!hasSSADominance)
344 return;
345
346 // Note, deque is being used here because there was significant performance
347 // gains over vector when the container becomes very large due to the
348 // specific access patterns. If/when these performance issues are no
349 // longer a problem we can change this to vector. For more information see
350 // the llvm mailing list discussion on this:
351 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
352 std::deque<std::unique_ptr<CFGStackNode>> stack;
353
354 // Process the nodes of the dom tree for this region.
355 stack.emplace_back(std::make_unique<CFGStackNode>(
356 knownValues, domInfo->getRootNode(&region)));
357
358 while (!stack.empty()) {
359 auto &currentNode = stack.back();
360
361 // Check to see if we need to process this node.
362 if (!currentNode->processed) {
363 currentNode->processed = true;
364 simplifyBlock(knownValues, currentNode->node->getBlock(),
365 hasSSADominance);
366 }
367
368 // Otherwise, check to see if we need to process a child node.
369 if (currentNode->childIterator != currentNode->node->end()) {
370 auto *childNode = *(currentNode->childIterator++);
371 stack.emplace_back(
372 std::make_unique<CFGStackNode>(knownValues, childNode));
373 } else {
374 // Finally, if the node and all of its children have been processed
375 // then we delete the node.
376 stack.pop_back();
377 }
378 }
379}
380
381void CSEDriver::eraseDeadOp(Operation *op) {
382 for (Region &region : op->getRegions())
383 domInfo->invalidate(&region);
384 rewriter.eraseOp(op);
385
386 // Note: CSE only removes ops within blocks, without adding or removing
387 // blocks themselves. Since DominanceInfo captures relationships between
388 // the direct blocks of the region being analyzed, not the blocks inside
389 // any nested regions of those ops, it remains valid after CSE.
390}
391
392void CSEDriver::simplify(Operation *op, bool *changed) {
393 // Simplify all regions.
394 ScopedMapTy knownValues;
395 for (auto &region : op->getRegions())
396 simplifyRegion(knownValues, region);
397 if (changed)
398 *changed = numCSE || numDCE;
399}
400
401void CSEDriver::simplify(Region &region, bool *changed) {
402 ScopedMapTy knownValues;
403 simplifyRegion(knownValues, region);
404 if (changed)
405 *changed = numCSE || numDCE;
406}
407
409 DominanceInfo &domInfo, Operation *op,
410 bool *changed, int64_t *numCSE,
411 int64_t *numDCE) {
412 CSEDriver driver(rewriter, &domInfo);
413 driver.simplify(op, changed);
414 if (numCSE)
415 *numCSE = driver.getNumCSE();
416 if (numDCE)
417 *numDCE = driver.getNumDCE();
418}
419
421 DominanceInfo &domInfo, Region &region,
422 bool *changed) {
423 CSEDriver driver(rewriter, &domInfo);
424 driver.simplify(region, changed);
425}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
template bool mlir::hasEffect< MemoryEffects::Read >(Operation *)
template bool mlir::hasSingleEffect< MemoryEffects::Read >(Operation *)
A class for computing basic dominance information.
Definition Dominance.h:143
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition Builders.h:323
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void setLoc(Location loc)
Set the source location the operation was defined or derived from.
Definition Operation.h:243
bool use_empty()
Returns true if this operation has no uses.
Definition Operation.h:906
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Definition Operation.h:811
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
result_range getResults()
Definition Operation.h:442
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
bool empty()
Definition Region.h:60
bool hasOneBlock()
Return true if this region has exactly one block.
Definition Region.h:68
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void replaceAllOpUsesWith(Operation *from, ValueRange to)
Find uses of from and replace them with to.
virtual bool replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
virtual bool isAddressable() const
Returns true if this resource is addressable (effects on it can alias pointer-based memory).
bool isDisjointFrom(const Resource *other) const
Returns true if this resource is disjoint from another.
DominanceInfoNode * getRootNode(Region *region)
Get the root dominance node of the given region.
Definition Dominance.h:77
bool hasSSADominance(Block *block) const
Return true if operations in the specified block are known to obey SSA dominance requirements.
Definition Dominance.h:95
void invalidate()
Invalidate dominance info.
Definition Dominance.cpp:37
Include the generated interface declarations.
void eliminateCommonSubExpressions(RewriterBase &rewriter, DominanceInfo &domInfo, Operation *op, bool *changed=nullptr, int64_t *numCSE=nullptr, int64_t *numDCE=nullptr)
Eliminate common subexpressions within the given operation.
Definition CSE.cpp:408
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::DomTreeNodeBase< Block > DominanceInfoNode
Definition Dominance.h:30
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
std::optional< llvm::SmallVector< MemoryEffects::EffectInstance > > getEffectsRecursively(Operation *rootOp)
Returns the side effects of an operation.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
static llvm::hash_code ignoreHashValue(Value)
Helper that can be used with computeHash above to ignore operation operands/result mapping.
static bool isEquivalentTo(Operation *lhs, Operation *rhs, function_ref< LogicalResult(Value, Value)> checkEquivalent, function_ref< void(Value, Value)> markEquivalent=nullptr, Flags flags=Flags::None, function_ref< LogicalResult(ValueRange, ValueRange)> checkCommutativeEquivalent=nullptr)
Compare two operations (including their regions) and return if they are equivalent.
static llvm::hash_code directHashValue(Value v)
Helper that can be used with computeHash to compute the hash value of operands/results directly.
static llvm::hash_code computeHash(Operation *op, function_ref< llvm::hash_code(Value)> hashOperands=[](Value v) { return hash_value(v);}, function_ref< llvm::hash_code(Value)> hashResults=[](Value v) { return hash_value(v);}, Flags flags=Flags::None)
Compute a hash for the given operation.