|
| 1 | +#include "mlir/Dialect/SCF/IR/SCF.h" |
| 2 | +#include "mlir/IR/Dominance.h" |
| 3 | +#include "mlir/Pass/Pass.h" |
| 4 | +#include "mlir/Transforms/CSE.h" |
| 5 | +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" |
| 6 | +#include "llvm/ADT/EquivalenceClasses.h" |
| 7 | + |
| 8 | +using namespace mlir; |
| 9 | + |
| 10 | +namespace mlir::triton { |
| 11 | +#define GEN_PASS_DEF_TRITONLOOPAWARECSE |
| 12 | +#include "triton/Dialect/Triton/Transforms/Passes.h.inc" |
| 13 | +} // namespace mlir::triton |
| 14 | + |
| 15 | +namespace { |
| 16 | +class ValueEquivalence { |
| 17 | +public: |
| 18 | + std::optional<bool> getKnownEquivalence(Value a, Value b) { |
| 19 | + if (auto it = equalValues.find(normalizeKey(a, b)); it != equalValues.end()) |
| 20 | + return it->second; |
| 21 | + return std::nullopt; |
| 22 | + } |
| 23 | + void setKnownEquivalence(Value a, Value b, bool eq) { |
| 24 | + equalValues.insert_or_assign(normalizeKey(a, b), eq); |
| 25 | + } |
| 26 | + |
| 27 | +private: |
| 28 | + // Commutatively query the equivalence of two values by sorting the key by |
| 29 | + // pointer value. |
| 30 | + std::pair<Value, Value> normalizeKey(Value a, Value b) { |
| 31 | + if ((uintptr_t)a.getAsOpaquePointer() < (uintptr_t)b.getAsOpaquePointer()) |
| 32 | + return {a, b}; |
| 33 | + return {b, a}; |
| 34 | + } |
| 35 | + |
| 36 | + DenseMap<std::pair<Value, Value>, bool> equalValues; |
| 37 | +}; |
| 38 | + |
| 39 | +struct LoopCSEDriver { |
| 40 | + LoopCSEDriver(scf::ForOp loop) : loop(loop) {} |
| 41 | + |
| 42 | + bool areIterArgsEqual(int i, int j); |
| 43 | + bool areEqualInLoop(Value a, Value b); |
| 44 | + |
| 45 | + scf::ForOp loop; |
| 46 | + ValueEquivalence equalValues; |
| 47 | +}; |
| 48 | +} // namespace |
| 49 | + |
| 50 | +bool LoopCSEDriver::areIterArgsEqual(int i, int j) { |
| 51 | + if (i == j) |
| 52 | + return true; |
| 53 | + if (loop.getInitArgs()[i] != loop.getInitArgs()[j]) |
| 54 | + return false; |
| 55 | + BlockArgument aArg = loop.getRegionIterArg(i); |
| 56 | + BlockArgument bArg = loop.getRegionIterArg(j); |
| 57 | + // First, assume the arguments are equal. This is how recursion is broken. |
| 58 | + equalValues.setKnownEquivalence(aArg, bArg, true); |
| 59 | + bool result = |
| 60 | + areEqualInLoop(loop.getYieldedValues()[i], loop.getYieldedValues()[j]); |
| 61 | + // Now update the equivalence based on the actual result. |
| 62 | + equalValues.setKnownEquivalence(aArg, bArg, result); |
| 63 | + return result; |
| 64 | +} |
| 65 | + |
| 66 | +bool LoopCSEDriver::areEqualInLoop(Value a, Value b) { |
| 67 | + // Check trivial case. |
| 68 | + if (a == b) |
| 69 | + return true; |
| 70 | + if (a.getType() != b.getType()) |
| 71 | + return false; |
| 72 | + |
| 73 | + Block *aBlock = a.getParentBlock(); |
| 74 | + Block *bBlock = b.getParentBlock(); |
| 75 | + // Values from outside the loop must have been equal. |
| 76 | + if (aBlock != loop.getBody() || bBlock != loop.getBody()) { |
| 77 | + return false; |
| 78 | + } |
| 79 | + // Both must be block arguments or not. |
| 80 | + if (isa<BlockArgument>(a) != isa<BlockArgument>(b)) |
| 81 | + return false; |
| 82 | + // Both must be the inductor var or not. |
| 83 | + if (a == loop.getInductionVar() || b == loop.getInductionVar()) |
| 84 | + return false; |
| 85 | + |
| 86 | + if (std::optional<bool> eq = equalValues.getKnownEquivalence(a, b)) |
| 87 | + return *eq; |
| 88 | + |
| 89 | + if (auto aArg = dyn_cast<BlockArgument>(a)) { |
| 90 | + auto bArg = cast<BlockArgument>(b); |
| 91 | + bool result = |
| 92 | + areIterArgsEqual(aArg.getArgNumber() - 1, bArg.getArgNumber() - 1); |
| 93 | + equalValues.setKnownEquivalence(a, b, result); |
| 94 | + return result; |
| 95 | + } |
| 96 | + |
| 97 | + Operation *aDef = a.getDefiningOp(); |
| 98 | + Operation *bDef = b.getDefiningOp(); |
| 99 | + // For it to be known that the operation results have the same value, they |
| 100 | + // must be side effect free. |
| 101 | + if (!isMemoryEffectFree(aDef) || !isMemoryEffectFree(bDef)) |
| 102 | + return false; |
| 103 | + // Don't bother with operations with regions. |
| 104 | + if (aDef->getNumRegions() || bDef->getNumRegions()) |
| 105 | + return false; |
| 106 | + |
| 107 | + bool result = OperationEquivalence::isEquivalentTo( |
| 108 | + aDef, bDef, |
| 109 | + [&](Value a, Value b) { return success(areEqualInLoop(a, b)); }, |
| 110 | + [&](Value a, Value b) { equalValues.setKnownEquivalence(a, b, true); }, |
| 111 | + OperationEquivalence::IgnoreLocations); |
| 112 | + equalValues.setKnownEquivalence(a, b, result); |
| 113 | + return result; |
| 114 | +} |
| 115 | + |
| 116 | +static void loopCSE(scf::ForOp loop) { |
| 117 | + int numIterArgs = loop.getNumRegionIterArgs(); |
| 118 | + // Group equivalent iter args together. |
| 119 | + llvm::EquivalenceClasses<int> equivalentArgs; |
| 120 | + LoopCSEDriver driver(loop); |
| 121 | + for (int i = 0; i != numIterArgs; ++i) { |
| 122 | + for (int j = i + 1; j != numIterArgs; ++j) { |
| 123 | + if (driver.areIterArgsEqual(i, j)) |
| 124 | + equivalentArgs.unionSets(i, j); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + // For each equivalence class, replace all other args in the class with one. |
| 129 | + for (auto it = equivalentArgs.begin(), end = equivalentArgs.end(); it != end; |
| 130 | + ++it) { |
| 131 | + if (!(*it)->isLeader()) |
| 132 | + continue; |
| 133 | + SmallVector<int> eqArgs; |
| 134 | + for (auto mIt = equivalentArgs.member_begin(**it); |
| 135 | + mIt != equivalentArgs.member_end(); ++mIt) |
| 136 | + eqArgs.push_back(*mIt); |
| 137 | + assert(eqArgs.size() > 1); |
| 138 | + // Sort the indices so the pass is deterministic. |
| 139 | + llvm::sort(eqArgs); |
| 140 | + BlockArgument unique = loop.getRegionIterArg(eqArgs.front()); |
| 141 | + Value uniqueResult = loop.getResult(eqArgs.front()); |
| 142 | + for (int j : llvm::drop_begin(eqArgs)) { |
| 143 | + BlockArgument other = loop.getRegionIterArg(j); |
| 144 | + other.replaceAllUsesWith(unique); |
| 145 | + // Short-circuit the value. The canonicalizer will clean this up. Leftover |
| 146 | + // subcomputations can now be removed by normal CSE. |
| 147 | + (*loop.getYieldedValuesMutable())[j].set(other); |
| 148 | + loop.getResult(j).replaceAllUsesWith(uniqueResult); |
| 149 | + } |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +namespace { |
| 154 | +struct LoopAwareCSE |
| 155 | + : public triton::impl::TritonLoopAwareCSEBase<LoopAwareCSE> { |
| 156 | + using TritonLoopAwareCSEBase::TritonLoopAwareCSEBase; |
| 157 | + |
| 158 | + void runOnOperation() override { |
| 159 | + // LoopAwareCSE doesn't recursively CSE ops outside of loops, so run CSE |
| 160 | + // first to make sure values from outside loops that are equivalent are made |
| 161 | + // pointer equal. |
| 162 | + IRRewriter rewriter(&getContext()); |
| 163 | + auto &domInfo = getAnalysis<DominanceInfo>(); |
| 164 | + eliminateCommonSubExpressions(rewriter, domInfo, getOperation()); |
| 165 | + |
| 166 | + // CSE region iter args within loop bodies. |
| 167 | + getOperation().walk(loopCSE); |
| 168 | + |
| 169 | + // Now that equivalent iter args have been made pointer equal, run CSE again |
| 170 | + // to clean up the loop body. |
| 171 | + eliminateCommonSubExpressions(rewriter, domInfo, getOperation()); |
| 172 | + |
| 173 | + // Run the `scf.for` canonicalizer to clean up the loops (short-circuited |
| 174 | + // values, unused results, etc.). |
| 175 | + RewritePatternSet patterns(&getContext()); |
| 176 | + scf::ForOp::getCanonicalizationPatterns(patterns, &getContext()); |
| 177 | + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) |
| 178 | + return signalPassFailure(); |
| 179 | + } |
| 180 | +}; |
| 181 | +} // namespace |
0 commit comments