1 //===- ParallelLoopFusion.cpp - Code to perform loop fusion ---------------===// 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 loop fusion on parallel loops. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/SCF/Transforms/Passes.h" 14 15 #include "mlir/Dialect/MemRef/IR/MemRef.h" 16 #include "mlir/Dialect/SCF/IR/SCF.h" 17 #include "mlir/Dialect/SCF/Transforms/Transforms.h" 18 #include "mlir/IR/BlockAndValueMapping.h" 19 #include "mlir/IR/Builders.h" 20 #include "mlir/IR/OpDefinition.h" 21 22 namespace mlir { 23 #define GEN_PASS_DEF_SCFPARALLELLOOPFUSION 24 #include "mlir/Dialect/SCF/Transforms/Passes.h.inc" 25 } // namespace mlir 26 27 using namespace mlir; 28 using namespace mlir::scf; 29 30 /// Verify there are no nested ParallelOps. 31 static bool hasNestedParallelOp(ParallelOp ploop) { 32 auto walkResult = 33 ploop.getBody()->walk([](ParallelOp) { return WalkResult::interrupt(); }); 34 return walkResult.wasInterrupted(); 35 } 36 37 /// Verify equal iteration spaces. 38 static bool equalIterationSpaces(ParallelOp firstPloop, 39 ParallelOp secondPloop) { 40 if (firstPloop.getNumLoops() != secondPloop.getNumLoops()) 41 return false; 42 43 auto matchOperands = [&](const OperandRange &lhs, 44 const OperandRange &rhs) -> bool { 45 // TODO: Extend this to support aliases and equal constants. 46 return std::equal(lhs.begin(), lhs.end(), rhs.begin()); 47 }; 48 return matchOperands(firstPloop.getLowerBound(), 49 secondPloop.getLowerBound()) && 50 matchOperands(firstPloop.getUpperBound(), 51 secondPloop.getUpperBound()) && 52 matchOperands(firstPloop.getStep(), secondPloop.getStep()); 53 } 54 55 /// Checks if the parallel loops have mixed access to the same buffers. Returns 56 /// `true` if the first parallel loop writes to the same indices that the second 57 /// loop reads. 58 static bool haveNoReadsAfterWriteExceptSameIndex( 59 ParallelOp firstPloop, ParallelOp secondPloop, 60 const BlockAndValueMapping &firstToSecondPloopIndices) { 61 DenseMap<Value, SmallVector<ValueRange, 1>> bufferStores; 62 firstPloop.getBody()->walk([&](memref::StoreOp store) { 63 bufferStores[store.getMemRef()].push_back(store.getIndices()); 64 }); 65 auto walkResult = secondPloop.getBody()->walk([&](memref::LoadOp load) { 66 // Stop if the memref is defined in secondPloop body. Careful alias analysis 67 // is needed. 68 auto *memrefDef = load.getMemRef().getDefiningOp(); 69 if (memrefDef && memrefDef->getBlock() == load->getBlock()) 70 return WalkResult::interrupt(); 71 72 auto write = bufferStores.find(load.getMemRef()); 73 if (write == bufferStores.end()) 74 return WalkResult::advance(); 75 76 // Allow only single write access per buffer. 77 if (write->second.size() != 1) 78 return WalkResult::interrupt(); 79 80 // Check that the load indices of secondPloop coincide with store indices of 81 // firstPloop for the same memrefs. 82 auto storeIndices = write->second.front(); 83 auto loadIndices = load.getIndices(); 84 if (storeIndices.size() != loadIndices.size()) 85 return WalkResult::interrupt(); 86 for (int i = 0, e = storeIndices.size(); i < e; ++i) { 87 if (firstToSecondPloopIndices.lookupOrDefault(storeIndices[i]) != 88 loadIndices[i]) 89 return WalkResult::interrupt(); 90 } 91 return WalkResult::advance(); 92 }); 93 return !walkResult.wasInterrupted(); 94 } 95 96 /// Analyzes dependencies in the most primitive way by checking simple read and 97 /// write patterns. 98 static LogicalResult 99 verifyDependencies(ParallelOp firstPloop, ParallelOp secondPloop, 100 const BlockAndValueMapping &firstToSecondPloopIndices) { 101 if (!haveNoReadsAfterWriteExceptSameIndex(firstPloop, secondPloop, 102 firstToSecondPloopIndices)) 103 return failure(); 104 105 BlockAndValueMapping secondToFirstPloopIndices; 106 secondToFirstPloopIndices.map(secondPloop.getBody()->getArguments(), 107 firstPloop.getBody()->getArguments()); 108 return success(haveNoReadsAfterWriteExceptSameIndex( 109 secondPloop, firstPloop, secondToFirstPloopIndices)); 110 } 111 112 static bool 113 isFusionLegal(ParallelOp firstPloop, ParallelOp secondPloop, 114 const BlockAndValueMapping &firstToSecondPloopIndices) { 115 return !hasNestedParallelOp(firstPloop) && 116 !hasNestedParallelOp(secondPloop) && 117 equalIterationSpaces(firstPloop, secondPloop) && 118 succeeded(verifyDependencies(firstPloop, secondPloop, 119 firstToSecondPloopIndices)); 120 } 121 122 /// Prepends operations of firstPloop's body into secondPloop's body. 123 static void fuseIfLegal(ParallelOp firstPloop, ParallelOp secondPloop, 124 OpBuilder b) { 125 BlockAndValueMapping firstToSecondPloopIndices; 126 firstToSecondPloopIndices.map(firstPloop.getBody()->getArguments(), 127 secondPloop.getBody()->getArguments()); 128 129 if (!isFusionLegal(firstPloop, secondPloop, firstToSecondPloopIndices)) 130 return; 131 132 b.setInsertionPointToStart(secondPloop.getBody()); 133 for (auto &op : firstPloop.getBody()->without_terminator()) 134 b.clone(op, firstToSecondPloopIndices); 135 firstPloop.erase(); 136 } 137 138 void mlir::scf::naivelyFuseParallelOps(Region ®ion) { 139 OpBuilder b(region); 140 // Consider every single block and attempt to fuse adjacent loops. 141 for (auto &block : region) { 142 SmallVector<SmallVector<ParallelOp, 8>, 1> ploopChains{{}}; 143 // Not using `walk()` to traverse only top-level parallel loops and also 144 // make sure that there are no side-effecting ops between the parallel 145 // loops. 146 bool noSideEffects = true; 147 for (auto &op : block) { 148 if (auto ploop = dyn_cast<ParallelOp>(op)) { 149 if (noSideEffects) { 150 ploopChains.back().push_back(ploop); 151 } else { 152 ploopChains.push_back({ploop}); 153 noSideEffects = true; 154 } 155 continue; 156 } 157 // TODO: Handle region side effects properly. 158 noSideEffects &= 159 MemoryEffectOpInterface::hasNoEffect(&op) && op.getNumRegions() == 0; 160 } 161 for (ArrayRef<ParallelOp> ploops : ploopChains) { 162 for (int i = 0, e = ploops.size(); i + 1 < e; ++i) 163 fuseIfLegal(ploops[i], ploops[i + 1], b); 164 } 165 } 166 } 167 168 namespace { 169 struct ParallelLoopFusion 170 : public impl::SCFParallelLoopFusionBase<ParallelLoopFusion> { 171 void runOnOperation() override { 172 getOperation()->walk([&](Operation *child) { 173 for (Region ®ion : child->getRegions()) 174 naivelyFuseParallelOps(region); 175 }); 176 } 177 }; 178 } // namespace 179 180 std::unique_ptr<Pass> mlir::createParallelLoopFusionPass() { 181 return std::make_unique<ParallelLoopFusion>(); 182 } 183