MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1 | //===- LoopFusion.cpp - Code to perform loop fusion -----------------------===// |
| 2 | // |
Mehdi Amini | 56222a0 | 2019-12-23 17:35:36 | [diff] [blame^] | 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 |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 6 | // |
Mehdi Amini | 56222a0 | 2019-12-23 17:35:36 | [diff] [blame^] | 7 | //===----------------------------------------------------------------------===// |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 8 | // |
| 9 | // This file implements loop fusion. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "mlir/Analysis/AffineAnalysis.h" |
Uday Bondhugula | dfe07b7 | 2019-02-23 00:51:08 | [diff] [blame] | 14 | #include "mlir/Analysis/AffineStructures.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 15 | #include "mlir/Analysis/LoopAnalysis.h" |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 16 | #include "mlir/Analysis/Utils.h" |
River Riddle | ffde975 | 2019-08-20 22:36:08 | [diff] [blame] | 17 | #include "mlir/Dialect/AffineOps/AffineOps.h" |
River Riddle | ba0fa92 | 2019-08-19 18:00:47 | [diff] [blame] | 18 | #include "mlir/Dialect/StandardOps/Ops.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 19 | #include "mlir/IR/AffineExpr.h" |
| 20 | #include "mlir/IR/AffineMap.h" |
| 21 | #include "mlir/IR/Builders.h" |
River Riddle | 48ccae2 | 2019-02-20 01:17:46 | [diff] [blame] | 22 | #include "mlir/Pass/Pass.h" |
Andy Davis | a560f2c | 2019-05-24 17:54:22 | [diff] [blame] | 23 | #include "mlir/Transforms/LoopFusionUtils.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 24 | #include "mlir/Transforms/LoopUtils.h" |
| 25 | #include "mlir/Transforms/Passes.h" |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 26 | #include "mlir/Transforms/Utils.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 27 | #include "llvm/ADT/DenseMap.h" |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 28 | #include "llvm/ADT/DenseSet.h" |
| 29 | #include "llvm/ADT/SetVector.h" |
MLIR Team | 4eef795 | 2018-12-21 19:06:23 | [diff] [blame] | 30 | #include "llvm/Support/CommandLine.h" |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 31 | #include "llvm/Support/Debug.h" |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 32 | #include "llvm/Support/raw_ostream.h" |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 33 | #include <iomanip> |
Stella Laurenzo | 1a2ad06 | 2019-05-14 01:10:48 | [diff] [blame] | 34 | #include <sstream> |
Nicolas Vasilache | 258e8d9 | 2019-05-03 18:07:37 | [diff] [blame] | 35 | #define DEBUG_TYPE "affine-loop-fusion" |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 36 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 37 | using llvm::SetVector; |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 38 | |
| 39 | using namespace mlir; |
| 40 | |
River Riddle | 75c21e1 | 2019-01-26 06:14:04 | [diff] [blame] | 41 | static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options"); |
| 42 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 43 | /// Disables fusion profitability check and fuses if valid. Ignore any |
| 44 | /// additional (redundant) computation tolerance threshold |
| 45 | /// that would have prevented fusion. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 46 | static llvm::cl::opt<bool> |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 47 | clMaximalLoopFusion("fusion-maximal", |
River Riddle | 75c21e1 | 2019-01-26 06:14:04 | [diff] [blame] | 48 | llvm::cl::desc("Enables maximal loop fusion"), |
| 49 | llvm::cl::cat(clOptionsCategory)); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 50 | |
| 51 | /// A threshold in percent of additional computation allowed when fusing. |
| 52 | static llvm::cl::opt<double> clFusionAddlComputeTolerance( |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 53 | "fusion-compute-tolerance", |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 54 | llvm::cl::desc("Fractional increase in additional " |
| 55 | "computation tolerated while fusing"), |
River Riddle | 75c21e1 | 2019-01-26 06:14:04 | [diff] [blame] | 56 | llvm::cl::cat(clOptionsCategory)); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 57 | |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 58 | static llvm::cl::opt<unsigned> clFusionFastMemorySpace( |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 59 | "fusion-fast-mem-space", |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 60 | llvm::cl::desc("Faster memory space number to promote fusion buffers to"), |
| 61 | llvm::cl::cat(clOptionsCategory)); |
| 62 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 63 | // A local buffer of size less than or equal to this size is automatically |
| 64 | // promoted to fast memory after producer-consumer fusion. |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 65 | static llvm::cl::opt<unsigned long long> clFusionLocalBufThreshold( |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 66 | "fusion-local-buf-threshold", |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 67 | llvm::cl::desc("Threshold size (KiB) for promoting local buffers to fast " |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 68 | "memory space"), |
| 69 | llvm::cl::cat(clOptionsCategory)); |
| 70 | |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 71 | namespace { |
| 72 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 73 | /// Loop fusion pass. This pass currently supports a greedy fusion policy, |
| 74 | /// which fuses loop nests with single-writer/single-reader memref dependences |
| 75 | /// with the goal of improving locality. |
| 76 | |
| 77 | // TODO(andydavis) Support fusion of source loop nests which write to multiple |
| 78 | // memrefs, where each memref can have multiple users (if profitable). |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 79 | // TODO(andydavis) Extend this pass to check for fusion preventing dependences, |
| 80 | // and add support for more general loop fusion algorithms. |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 81 | |
River Riddle | c6c5344 | 2019-02-27 18:59:29 | [diff] [blame] | 82 | struct LoopFusion : public FunctionPass<LoopFusion> { |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 83 | LoopFusion(unsigned fastMemorySpace = 0, uint64_t localBufSizeThreshold = 0, |
| 84 | bool maximalFusion = false) |
River Riddle | c6c5344 | 2019-02-27 18:59:29 | [diff] [blame] | 85 | : localBufSizeThreshold(localBufSizeThreshold), |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 86 | fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {} |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 87 | |
River Riddle | ed5fe20 | 2019-02-28 22:50:42 | [diff] [blame] | 88 | void runOnFunction() override; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 89 | |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 90 | // Any local buffers smaller than this size (in bytes) will be created in |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 91 | // `fastMemorySpace` if provided. |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 92 | uint64_t localBufSizeThreshold; |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 93 | Optional<unsigned> fastMemorySpace = None; |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 94 | // If true, ignore any additional (redundant) computation tolerance threshold |
| 95 | // that would have prevented fusion. |
| 96 | bool maximalFusion; |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 97 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 98 | // The amount of additional computation that is tolerated while fusing |
| 99 | // pair-wise as a fraction of the total computation. |
| 100 | constexpr static double kComputeToleranceThreshold = 0.30f; |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 101 | }; |
| 102 | |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 103 | } // end anonymous namespace |
| 104 | |
River Riddle | f1b100c | 2019-09-13 20:33:46 | [diff] [blame] | 105 | std::unique_ptr<OpPassBase<FuncOp>> |
Mehdi Amini | 926fb68 | 2019-08-13 02:12:42 | [diff] [blame] | 106 | mlir::createLoopFusionPass(unsigned fastMemorySpace, |
| 107 | uint64_t localBufSizeThreshold, bool maximalFusion) { |
Jacques Pienaar | 79f53b0 | 2019-08-17 18:05:35 | [diff] [blame] | 108 | return std::make_unique<LoopFusion>(fastMemorySpace, localBufSizeThreshold, |
| 109 | maximalFusion); |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 110 | } |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 111 | |
River Riddle | 2666b97 | 2019-12-18 18:46:16 | [diff] [blame] | 112 | // TODO(b/117228571) Replace when this is modeled through side-effects/op traits |
| 113 | static bool isMemRefDereferencingOp(Operation &op) { |
| 114 | if (isa<AffineLoadOp>(op) || isa<AffineStoreOp>(op) || |
| 115 | isa<AffineDmaStartOp>(op) || isa<AffineDmaWaitOp>(op)) |
| 116 | return true; |
| 117 | return false; |
| 118 | } |
| 119 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 120 | namespace { |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 121 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 122 | // LoopNestStateCollector walks loop nests and collects load and store |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 123 | // operations, and whether or not an IfInst was encountered in the loop nest. |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 124 | struct LoopNestStateCollector { |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 125 | SmallVector<AffineForOp, 4> forOps; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 126 | SmallVector<Operation *, 4> loadOpInsts; |
| 127 | SmallVector<Operation *, 4> storeOpInsts; |
River Riddle | 7555383 | 2019-01-29 05:23:53 | [diff] [blame] | 128 | bool hasNonForRegion = false; |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 129 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 130 | void collect(Operation *opToWalk) { |
| 131 | opToWalk->walk([&](Operation *op) { |
River Riddle | d5b60ee8 | 2019-05-12 01:59:54 | [diff] [blame] | 132 | if (isa<AffineForOp>(op)) |
River Riddle | adca3c2 | 2019-05-12 00:57:32 | [diff] [blame] | 133 | forOps.push_back(cast<AffineForOp>(op)); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 134 | else if (op->getNumRegions() != 0) |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 135 | hasNonForRegion = true; |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 136 | else if (isa<AffineLoadOp>(op)) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 137 | loadOpInsts.push_back(op); |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 138 | else if (isa<AffineStoreOp>(op)) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 139 | storeOpInsts.push_back(op); |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 140 | }); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 141 | } |
| 142 | }; |
| 143 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 144 | // MemRefDependenceGraph is a graph data structure where graph nodes are |
River Riddle | 8c44367 | 2019-07-09 23:17:55 | [diff] [blame] | 145 | // top-level operations in a FuncOp which contain load/store ops, and edges |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 146 | // are memref dependences between the nodes. |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 147 | // TODO(andydavis) Add a more flexible dependence graph representation. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 148 | // TODO(andydavis) Add a depth parameter to dependence graph construction. |
| 149 | struct MemRefDependenceGraph { |
| 150 | public: |
| 151 | // Node represents a node in the graph. A Node is either an entire loop nest |
| 152 | // rooted at the top level which contains loads/stores, or a top level |
| 153 | // load/store. |
| 154 | struct Node { |
| 155 | // The unique identifier of this node in the graph. |
| 156 | unsigned id; |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 157 | // The top-level statement which is (or contains) a load/store. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 158 | Operation *op; |
Chris Lattner | 5187cfc | 2018-12-28 05:21:41 | [diff] [blame] | 159 | // List of load operations. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 160 | SmallVector<Operation *, 4> loads; |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 161 | // List of store op insts. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 162 | SmallVector<Operation *, 4> stores; |
| 163 | Node(unsigned id, Operation *op) : id(id), op(op) {} |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 164 | |
| 165 | // Returns the load op count for 'memref'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 166 | unsigned getLoadOpCount(ValuePtr memref) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 167 | unsigned loadOpCount = 0; |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 168 | for (auto *loadOpInst : loads) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 169 | if (memref == cast<AffineLoadOp>(loadOpInst).getMemRef()) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 170 | ++loadOpCount; |
| 171 | } |
| 172 | return loadOpCount; |
| 173 | } |
| 174 | |
| 175 | // Returns the store op count for 'memref'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 176 | unsigned getStoreOpCount(ValuePtr memref) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 177 | unsigned storeOpCount = 0; |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 178 | for (auto *storeOpInst : stores) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 179 | if (memref == cast<AffineStoreOp>(storeOpInst).getMemRef()) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 180 | ++storeOpCount; |
| 181 | } |
| 182 | return storeOpCount; |
| 183 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 184 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 185 | // Returns all store ops in 'storeOps' which access 'memref'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 186 | void getStoreOpsForMemref(ValuePtr memref, |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 187 | SmallVectorImpl<Operation *> *storeOps) { |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 188 | for (auto *storeOpInst : stores) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 189 | if (memref == cast<AffineStoreOp>(storeOpInst).getMemRef()) |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 190 | storeOps->push_back(storeOpInst); |
| 191 | } |
| 192 | } |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 193 | |
| 194 | // Returns all load ops in 'loadOps' which access 'memref'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 195 | void getLoadOpsForMemref(ValuePtr memref, |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 196 | SmallVectorImpl<Operation *> *loadOps) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 197 | for (auto *loadOpInst : loads) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 198 | if (memref == cast<AffineLoadOp>(loadOpInst).getMemRef()) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 199 | loadOps->push_back(loadOpInst); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | // Returns all memrefs in 'loadAndStoreMemrefSet' for which this node |
| 204 | // has at least one load and store operation. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 205 | void getLoadAndStoreMemrefSet(DenseSet<ValuePtr> *loadAndStoreMemrefSet) { |
| 206 | llvm::SmallDenseSet<ValuePtr, 2> loadMemrefs; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 207 | for (auto *loadOpInst : loads) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 208 | loadMemrefs.insert(cast<AffineLoadOp>(loadOpInst).getMemRef()); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 209 | } |
| 210 | for (auto *storeOpInst : stores) { |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 211 | auto memref = cast<AffineStoreOp>(storeOpInst).getMemRef(); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 212 | if (loadMemrefs.count(memref) > 0) |
| 213 | loadAndStoreMemrefSet->insert(memref); |
| 214 | } |
| 215 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 216 | }; |
| 217 | |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 218 | // Edge represents a data dependence between nodes in the graph. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 219 | struct Edge { |
| 220 | // The id of the node at the other end of the edge. |
MLIR Team | 1e85191 | 2019-01-31 00:01:46 | [diff] [blame] | 221 | // If this edge is stored in Edge = Node.inEdges[i], then |
| 222 | // 'Node.inEdges[i].id' is the identifier of the source node of the edge. |
| 223 | // If this edge is stored in Edge = Node.outEdges[i], then |
| 224 | // 'Node.outEdges[i].id' is the identifier of the dest node of the edge. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 225 | unsigned id; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 226 | // The SSA value on which this edge represents a dependence. |
| 227 | // If the value is a memref, then the dependence is between graph nodes |
| 228 | // which contain accesses to the same memref 'value'. If the value is a |
| 229 | // non-memref value, then the dependence is between a graph node which |
| 230 | // defines an SSA value and another graph node which uses the SSA value |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 231 | // (e.g. a constant operation defining a value which is used inside a loop |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 232 | // nest). |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 233 | ValuePtr value; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 234 | }; |
| 235 | |
| 236 | // Map from node id to Node. |
| 237 | DenseMap<unsigned, Node> nodes; |
| 238 | // Map from node id to list of input edges. |
| 239 | DenseMap<unsigned, SmallVector<Edge, 2>> inEdges; |
| 240 | // Map from node id to list of output edges. |
| 241 | DenseMap<unsigned, SmallVector<Edge, 2>> outEdges; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 242 | // Map from memref to a count on the dependence edges associated with that |
| 243 | // memref. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 244 | DenseMap<ValuePtr, unsigned> memrefEdgeCount; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 245 | // The next unique identifier to use for newly created graph nodes. |
| 246 | unsigned nextNodeId = 0; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 247 | |
| 248 | MemRefDependenceGraph() {} |
| 249 | |
| 250 | // Initializes the dependence graph based on operations in 'f'. |
| 251 | // Returns true on success, false otherwise. |
River Riddle | 8c44367 | 2019-07-09 23:17:55 | [diff] [blame] | 252 | bool init(FuncOp f); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 253 | |
| 254 | // Returns the graph node for 'id'. |
| 255 | Node *getNode(unsigned id) { |
| 256 | auto it = nodes.find(id); |
| 257 | assert(it != nodes.end()); |
| 258 | return &it->second; |
| 259 | } |
| 260 | |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 261 | // Returns the graph node for 'forOp'. |
| 262 | Node *getForOpNode(AffineForOp forOp) { |
| 263 | for (auto &idAndNode : nodes) |
| 264 | if (idAndNode.second.op == forOp.getOperation()) |
| 265 | return &idAndNode.second; |
| 266 | return nullptr; |
| 267 | } |
| 268 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 269 | // Adds a node with 'op' to the graph and returns its unique identifier. |
| 270 | unsigned addNode(Operation *op) { |
| 271 | Node node(nextNodeId++, op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 272 | nodes.insert({node.id, node}); |
| 273 | return node.id; |
| 274 | } |
| 275 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 276 | // Remove node 'id' (and its associated edges) from graph. |
| 277 | void removeNode(unsigned id) { |
| 278 | // Remove each edge in 'inEdges[id]'. |
| 279 | if (inEdges.count(id) > 0) { |
| 280 | SmallVector<Edge, 2> oldInEdges = inEdges[id]; |
| 281 | for (auto &inEdge : oldInEdges) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 282 | removeEdge(inEdge.id, id, inEdge.value); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 283 | } |
| 284 | } |
| 285 | // Remove each edge in 'outEdges[id]'. |
| 286 | if (outEdges.count(id) > 0) { |
| 287 | SmallVector<Edge, 2> oldOutEdges = outEdges[id]; |
| 288 | for (auto &outEdge : oldOutEdges) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 289 | removeEdge(id, outEdge.id, outEdge.value); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 290 | } |
| 291 | } |
| 292 | // Erase remaining node state. |
| 293 | inEdges.erase(id); |
| 294 | outEdges.erase(id); |
| 295 | nodes.erase(id); |
| 296 | } |
| 297 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 298 | // Returns true if node 'id' writes to any memref which escapes (or is an |
| 299 | // argument to) the function/block. Returns false otherwise. |
| 300 | bool writesToLiveInOrEscapingMemrefs(unsigned id) { |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 301 | Node *node = getNode(id); |
| 302 | for (auto *storeOpInst : node->stores) { |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 303 | auto memref = cast<AffineStoreOp>(storeOpInst).getMemRef(); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 304 | auto *op = memref->getDefiningOp(); |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 305 | // Return true if 'memref' is a block argument. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 306 | if (!op) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 307 | return true; |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 308 | // Return true if any use of 'memref' escapes the function. |
River Riddle | 8780d8d | 2019-05-18 18:09:07 | [diff] [blame] | 309 | for (auto *user : memref->getUsers()) |
| 310 | if (!isMemRefDereferencingOp(*user)) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 311 | return true; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 312 | } |
| 313 | return false; |
| 314 | } |
| 315 | |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 316 | // Returns the unique AffineStoreOp in `node` that meets all the following: |
| 317 | // *) store is the only one that writes to a function-local memref live out |
| 318 | // of `node`, |
| 319 | // *) store is not the source of a self-dependence on `node`. |
| 320 | // Otherwise, returns a null AffineStoreOp. |
| 321 | AffineStoreOp getUniqueOutgoingStore(Node *node) { |
| 322 | AffineStoreOp uniqueStore; |
| 323 | |
| 324 | // Return null if `node` doesn't have any outgoing edges. |
| 325 | auto outEdgeIt = outEdges.find(node->id); |
| 326 | if (outEdgeIt == outEdges.end()) |
| 327 | return nullptr; |
| 328 | |
| 329 | const auto &nodeOutEdges = outEdgeIt->second; |
| 330 | for (auto *op : node->stores) { |
| 331 | auto storeOp = cast<AffineStoreOp>(op); |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 332 | auto memref = storeOp.getMemRef(); |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 333 | // Skip this store if there are no dependences on its memref. This means |
| 334 | // that store either: |
| 335 | // *) writes to a memref that is only read within the same loop nest |
| 336 | // (self-dependence edges are not represented in graph at the moment), |
| 337 | // *) writes to a function live out memref (function parameter), or |
| 338 | // *) is dead. |
| 339 | if (llvm::all_of(nodeOutEdges, [=](const Edge &edge) { |
| 340 | return (edge.value != memref); |
| 341 | })) |
| 342 | continue; |
| 343 | |
| 344 | if (uniqueStore) |
| 345 | // Found multiple stores to function-local live-out memrefs. |
| 346 | return nullptr; |
| 347 | // Found first store to function-local live-out memref. |
| 348 | uniqueStore = storeOp; |
| 349 | } |
| 350 | |
| 351 | return uniqueStore; |
| 352 | } |
| 353 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 354 | // Returns true if node 'id' can be removed from the graph. Returns false |
| 355 | // otherwise. A node can be removed from the graph iff the following |
| 356 | // conditions are met: |
| 357 | // *) The node does not write to any memref which escapes (or is a |
| 358 | // function/block argument). |
| 359 | // *) The node has no successors in the dependence graph. |
| 360 | bool canRemoveNode(unsigned id) { |
| 361 | if (writesToLiveInOrEscapingMemrefs(id)) |
| 362 | return false; |
| 363 | Node *node = getNode(id); |
| 364 | for (auto *storeOpInst : node->stores) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 365 | // Return false if there exist out edges from 'id' on 'memref'. |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 366 | if (getOutEdgeCount(id, cast<AffineStoreOp>(storeOpInst).getMemRef()) > 0) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 367 | return false; |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 368 | } |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 369 | return true; |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 370 | } |
| 371 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 372 | // Returns true iff there is an edge from node 'srcId' to node 'dstId' which |
| 373 | // is for 'value' if non-null, or for any value otherwise. Returns false |
| 374 | // otherwise. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 375 | bool hasEdge(unsigned srcId, unsigned dstId, ValuePtr value = nullptr) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 376 | if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) { |
| 377 | return false; |
| 378 | } |
| 379 | bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 380 | return edge.id == dstId && (!value || edge.value == value); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 381 | }); |
| 382 | bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 383 | return edge.id == srcId && (!value || edge.value == value); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 384 | }); |
| 385 | return hasOutEdge && hasInEdge; |
| 386 | } |
| 387 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 388 | // Adds an edge from node 'srcId' to node 'dstId' for 'value'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 389 | void addEdge(unsigned srcId, unsigned dstId, ValuePtr value) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 390 | if (!hasEdge(srcId, dstId, value)) { |
| 391 | outEdges[srcId].push_back({dstId, value}); |
| 392 | inEdges[dstId].push_back({srcId, value}); |
| 393 | if (value->getType().isa<MemRefType>()) |
| 394 | memrefEdgeCount[value]++; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 395 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 396 | } |
| 397 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 398 | // Removes an edge from node 'srcId' to node 'dstId' for 'value'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 399 | void removeEdge(unsigned srcId, unsigned dstId, ValuePtr value) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 400 | assert(inEdges.count(dstId) > 0); |
| 401 | assert(outEdges.count(srcId) > 0); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 402 | if (value->getType().isa<MemRefType>()) { |
| 403 | assert(memrefEdgeCount.count(value) > 0); |
| 404 | memrefEdgeCount[value]--; |
| 405 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 406 | // Remove 'srcId' from 'inEdges[dstId]'. |
| 407 | for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 408 | if ((*it).id == srcId && (*it).value == value) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 409 | inEdges[dstId].erase(it); |
| 410 | break; |
| 411 | } |
| 412 | } |
| 413 | // Remove 'dstId' from 'outEdges[srcId]'. |
| 414 | for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 415 | if ((*it).id == dstId && (*it).value == value) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 416 | outEdges[srcId].erase(it); |
| 417 | break; |
| 418 | } |
| 419 | } |
| 420 | } |
| 421 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 422 | // Returns true if there is a path in the dependence graph from node 'srcId' |
| 423 | // to node 'dstId'. Returns false otherwise. |
| 424 | bool hasDependencePath(unsigned srcId, unsigned dstId) { |
| 425 | // Worklist state is: <node-id, next-output-edge-index-to-visit> |
| 426 | SmallVector<std::pair<unsigned, unsigned>, 4> worklist; |
| 427 | worklist.push_back({srcId, 0}); |
| 428 | // Run DFS traversal to see if 'dstId' is reachable from 'srcId'. |
| 429 | while (!worklist.empty()) { |
| 430 | auto &idAndIndex = worklist.back(); |
| 431 | // Return true if we have reached 'dstId'. |
| 432 | if (idAndIndex.first == dstId) |
| 433 | return true; |
| 434 | // Pop and continue if node has no out edges, or if all out edges have |
| 435 | // already been visited. |
| 436 | if (outEdges.count(idAndIndex.first) == 0 || |
| 437 | idAndIndex.second == outEdges[idAndIndex.first].size()) { |
| 438 | worklist.pop_back(); |
| 439 | continue; |
| 440 | } |
| 441 | // Get graph edge to traverse. |
| 442 | Edge edge = outEdges[idAndIndex.first][idAndIndex.second]; |
| 443 | // Increment next output edge index for 'idAndIndex'. |
| 444 | ++idAndIndex.second; |
| 445 | // Add node at 'edge.id' to worklist. |
| 446 | worklist.push_back({edge.id, 0}); |
| 447 | } |
| 448 | return false; |
| 449 | } |
| 450 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 451 | // Returns the input edge count for node 'id' and 'memref' from src nodes |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 452 | // which access 'memref' with a store operation. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 453 | unsigned getIncomingMemRefAccesses(unsigned id, ValuePtr memref) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 454 | unsigned inEdgeCount = 0; |
| 455 | if (inEdges.count(id) > 0) |
| 456 | for (auto &inEdge : inEdges[id]) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 457 | if (inEdge.value == memref) { |
| 458 | Node *srcNode = getNode(inEdge.id); |
| 459 | // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref' |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 460 | if (srcNode->getStoreOpCount(memref) > 0) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 461 | ++inEdgeCount; |
| 462 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 463 | return inEdgeCount; |
| 464 | } |
| 465 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 466 | // Returns the output edge count for node 'id' and 'memref' (if non-null), |
| 467 | // otherwise returns the total output edge count from node 'id'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 468 | unsigned getOutEdgeCount(unsigned id, ValuePtr memref = nullptr) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 469 | unsigned outEdgeCount = 0; |
| 470 | if (outEdges.count(id) > 0) |
| 471 | for (auto &outEdge : outEdges[id]) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 472 | if (!memref || outEdge.value == memref) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 473 | ++outEdgeCount; |
| 474 | return outEdgeCount; |
| 475 | } |
| 476 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 477 | // Computes and returns an insertion point operation, before which the |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 478 | // the fused <srcId, dstId> loop nest can be inserted while preserving |
| 479 | // dependences. Returns nullptr if no such insertion point is found. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 480 | Operation *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) { |
MLIR Team | 5c5739d | 2019-01-25 06:27:40 | [diff] [blame] | 481 | if (outEdges.count(srcId) == 0) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 482 | return getNode(dstId)->op; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 483 | |
| 484 | // Build set of insts in range (srcId, dstId) which depend on 'srcId'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 485 | SmallPtrSet<Operation *, 2> srcDepInsts; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 486 | for (auto &outEdge : outEdges[srcId]) |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 487 | if (outEdge.id != dstId) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 488 | srcDepInsts.insert(getNode(outEdge.id)->op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 489 | |
| 490 | // Build set of insts in range (srcId, dstId) on which 'dstId' depends. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 491 | SmallPtrSet<Operation *, 2> dstDepInsts; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 492 | for (auto &inEdge : inEdges[dstId]) |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 493 | if (inEdge.id != srcId) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 494 | dstDepInsts.insert(getNode(inEdge.id)->op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 495 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 496 | Operation *srcNodeInst = getNode(srcId)->op; |
| 497 | Operation *dstNodeInst = getNode(dstId)->op; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 498 | |
| 499 | // Computing insertion point: |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 500 | // *) Walk all operation positions in Block operation list in the |
| 501 | // range (src, dst). For each operation 'op' visited in this search: |
| 502 | // *) Store in 'firstSrcDepPos' the first position where 'op' has a |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 503 | // dependence edge from 'srcNode'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 504 | // *) Store in 'lastDstDepPost' the last position where 'op' has a |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 505 | // dependence edge to 'dstNode'. |
| 506 | // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 507 | // operation insertion point (or return null pointer if no such |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 508 | // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos'). |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 509 | SmallVector<Operation *, 2> depInsts; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 510 | Optional<unsigned> firstSrcDepPos; |
| 511 | Optional<unsigned> lastDstDepPos; |
| 512 | unsigned pos = 0; |
| 513 | for (Block::iterator it = std::next(Block::iterator(srcNodeInst)); |
| 514 | it != Block::iterator(dstNodeInst); ++it) { |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 515 | Operation *op = &(*it); |
| 516 | if (srcDepInsts.count(op) > 0 && firstSrcDepPos == None) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 517 | firstSrcDepPos = pos; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 518 | if (dstDepInsts.count(op) > 0) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 519 | lastDstDepPos = pos; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 520 | depInsts.push_back(op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 521 | ++pos; |
MLIR Team | 5c5739d | 2019-01-25 06:27:40 | [diff] [blame] | 522 | } |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 523 | |
| 524 | if (firstSrcDepPos.hasValue()) { |
| 525 | if (lastDstDepPos.hasValue()) { |
| 526 | if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) { |
| 527 | // No valid insertion point exists which preserves dependences. |
| 528 | return nullptr; |
| 529 | } |
| 530 | } |
| 531 | // Return the insertion point at 'firstSrcDepPos'. |
| 532 | return depInsts[firstSrcDepPos.getValue()]; |
| 533 | } |
| 534 | // No dependence targets in range (or only dst deps in range), return |
| 535 | // 'dstNodInst' insertion point. |
| 536 | return dstNodeInst; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 537 | } |
| 538 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 539 | // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef' |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 540 | // has been replaced in node at 'dstId' by a private memref depending |
| 541 | // on the value of 'createPrivateMemRef'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 542 | void updateEdges(unsigned srcId, unsigned dstId, ValuePtr oldMemRef, |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 543 | bool createPrivateMemRef) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 544 | // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'. |
| 545 | if (inEdges.count(srcId) > 0) { |
| 546 | SmallVector<Edge, 2> oldInEdges = inEdges[srcId]; |
| 547 | for (auto &inEdge : oldInEdges) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 548 | // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'. |
| 549 | if (inEdge.value != oldMemRef) |
| 550 | addEdge(inEdge.id, dstId, inEdge.value); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 551 | } |
| 552 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 553 | // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 554 | if (outEdges.count(srcId) > 0) { |
| 555 | SmallVector<Edge, 2> oldOutEdges = outEdges[srcId]; |
| 556 | for (auto &outEdge : oldOutEdges) { |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 557 | // Remove any out edges from 'srcId' to 'dstId' across memrefs. |
| 558 | if (outEdge.id == dstId) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 559 | removeEdge(srcId, outEdge.id, outEdge.value); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 560 | } |
| 561 | } |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 562 | // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being |
| 563 | // replaced by a private memref). These edges could come from nodes |
| 564 | // other than 'srcId' which were removed in the previous step. |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 565 | if (inEdges.count(dstId) > 0 && createPrivateMemRef) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 566 | SmallVector<Edge, 2> oldInEdges = inEdges[dstId]; |
| 567 | for (auto &inEdge : oldInEdges) |
| 568 | if (inEdge.value == oldMemRef) |
| 569 | removeEdge(inEdge.id, dstId, inEdge.value); |
| 570 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 571 | } |
| 572 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 573 | // Update edge mappings for nodes 'sibId' and 'dstId' to reflect fusion |
| 574 | // of sibling node 'sidId' into node 'dstId'. |
| 575 | void updateEdges(unsigned sibId, unsigned dstId) { |
| 576 | // For each edge in 'inEdges[sibId]': |
| 577 | // *) Add new edge from source node 'inEdge.id' to 'dstNode'. |
| 578 | // *) Remove edge from source node 'inEdge.id' to 'sibNode'. |
| 579 | if (inEdges.count(sibId) > 0) { |
| 580 | SmallVector<Edge, 2> oldInEdges = inEdges[sibId]; |
| 581 | for (auto &inEdge : oldInEdges) { |
| 582 | addEdge(inEdge.id, dstId, inEdge.value); |
| 583 | removeEdge(inEdge.id, sibId, inEdge.value); |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | // For each edge in 'outEdges[sibId]' to node 'id' |
| 588 | // *) Add new edge from 'dstId' to 'outEdge.id'. |
| 589 | // *) Remove edge from 'sibId' to 'outEdge.id'. |
| 590 | if (outEdges.count(sibId) > 0) { |
| 591 | SmallVector<Edge, 2> oldOutEdges = outEdges[sibId]; |
| 592 | for (auto &outEdge : oldOutEdges) { |
| 593 | addEdge(dstId, outEdge.id, outEdge.value); |
| 594 | removeEdge(sibId, outEdge.id, outEdge.value); |
| 595 | } |
| 596 | } |
| 597 | } |
| 598 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 599 | // Adds ops in 'loads' and 'stores' to node at 'id'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 600 | void addToNode(unsigned id, const SmallVectorImpl<Operation *> &loads, |
| 601 | const SmallVectorImpl<Operation *> &stores) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 602 | Node *node = getNode(id); |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 603 | for (auto *loadOpInst : loads) |
| 604 | node->loads.push_back(loadOpInst); |
| 605 | for (auto *storeOpInst : stores) |
| 606 | node->stores.push_back(storeOpInst); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 607 | } |
| 608 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 609 | void clearNodeLoadAndStores(unsigned id) { |
| 610 | Node *node = getNode(id); |
| 611 | node->loads.clear(); |
| 612 | node->stores.clear(); |
| 613 | } |
| 614 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 615 | // Calls 'callback' for each input edge incident to node 'id' which carries a |
| 616 | // memref dependence. |
| 617 | void forEachMemRefInputEdge(unsigned id, |
| 618 | const std::function<void(Edge)> &callback) { |
| 619 | if (inEdges.count(id) > 0) |
| 620 | forEachMemRefEdge(inEdges[id], callback); |
| 621 | } |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 622 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 623 | // Calls 'callback' for each output edge from node 'id' which carries a |
| 624 | // memref dependence. |
| 625 | void forEachMemRefOutputEdge(unsigned id, |
| 626 | const std::function<void(Edge)> &callback) { |
| 627 | if (outEdges.count(id) > 0) |
| 628 | forEachMemRefEdge(outEdges[id], callback); |
| 629 | } |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 630 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 631 | // Calls 'callback' for each edge in 'edges' which carries a memref |
| 632 | // dependence. |
| 633 | void forEachMemRefEdge(ArrayRef<Edge> edges, |
| 634 | const std::function<void(Edge)> &callback) { |
| 635 | for (auto &edge : edges) { |
| 636 | // Skip if 'edge' is not a memref dependence edge. |
| 637 | if (!edge.value->getType().isa<MemRefType>()) |
| 638 | continue; |
| 639 | assert(nodes.count(edge.id) > 0); |
| 640 | // Skip if 'edge.id' is not a loop nest. |
River Riddle | d5b60ee8 | 2019-05-12 01:59:54 | [diff] [blame] | 641 | if (!isa<AffineForOp>(getNode(edge.id)->op)) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 642 | continue; |
| 643 | // Visit current input edge 'edge'. |
| 644 | callback(edge); |
| 645 | } |
| 646 | } |
| 647 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 648 | void print(raw_ostream &os) const { |
| 649 | os << "\nMemRefDependenceGraph\n"; |
| 650 | os << "\nNodes:\n"; |
| 651 | for (auto &idAndNode : nodes) { |
| 652 | os << "Node: " << idAndNode.first << "\n"; |
| 653 | auto it = inEdges.find(idAndNode.first); |
| 654 | if (it != inEdges.end()) { |
| 655 | for (const auto &e : it->second) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 656 | os << " InEdge: " << e.id << " " << e.value << "\n"; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 657 | } |
| 658 | it = outEdges.find(idAndNode.first); |
| 659 | if (it != outEdges.end()) { |
| 660 | for (const auto &e : it->second) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 661 | os << " OutEdge: " << e.id << " " << e.value << "\n"; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 662 | } |
| 663 | } |
| 664 | } |
| 665 | void dump() const { print(llvm::errs()); } |
| 666 | }; |
| 667 | |
River Riddle | 2666b97 | 2019-12-18 18:46:16 | [diff] [blame] | 668 | } // end anonymous namespace |
| 669 | |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 670 | // Initializes the data dependence graph by walking operations in 'f'. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 671 | // Assigns each node in the graph a node id based on program order in 'f'. |
Chris Lattner | 315a466 | 2018-12-28 21:07:39 | [diff] [blame] | 672 | // TODO(andydavis) Add support for taking a Block arg to construct the |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 673 | // dependence graph at a different depth. |
River Riddle | 8c44367 | 2019-07-09 23:17:55 | [diff] [blame] | 674 | bool MemRefDependenceGraph::init(FuncOp f) { |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 675 | DenseMap<ValuePtr, SetVector<unsigned>> memrefAccesses; |
Chris Lattner | dffc589 | 2018-12-29 23:33:43 | [diff] [blame] | 676 | |
| 677 | // TODO: support multi-block functions. |
Chris Lattner | 46ade28 | 2019-03-26 01:02:49 | [diff] [blame] | 678 | if (f.getBlocks().size() != 1) |
Chris Lattner | dffc589 | 2018-12-29 23:33:43 | [diff] [blame] | 679 | return false; |
| 680 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 681 | DenseMap<Operation *, unsigned> forToNodeMap; |
| 682 | for (auto &op : f.front()) { |
River Riddle | c5ecf99 | 2019-05-11 22:56:50 | [diff] [blame] | 683 | if (auto forOp = dyn_cast<AffineForOp>(op)) { |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 684 | // Create graph node 'id' to represent top-level 'forOp' and record |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 685 | // all loads and store accesses it contains. |
| 686 | LoopNestStateCollector collector; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 687 | collector.collect(&op); |
River Riddle | 832567b | 2019-03-25 17:14:34 | [diff] [blame] | 688 | // Return false if a non 'affine.for' region was found (not currently |
| 689 | // supported). |
River Riddle | 7555383 | 2019-01-29 05:23:53 | [diff] [blame] | 690 | if (collector.hasNonForRegion) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 691 | return false; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 692 | Node node(nextNodeId++, &op); |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 693 | for (auto *opInst : collector.loadOpInsts) { |
| 694 | node.loads.push_back(opInst); |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 695 | auto memref = cast<AffineLoadOp>(opInst).getMemRef(); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 696 | memrefAccesses[memref].insert(node.id); |
| 697 | } |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 698 | for (auto *opInst : collector.storeOpInsts) { |
| 699 | node.stores.push_back(opInst); |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 700 | auto memref = cast<AffineStoreOp>(opInst).getMemRef(); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 701 | memrefAccesses[memref].insert(node.id); |
| 702 | } |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 703 | forToNodeMap[&op] = node.id; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 704 | nodes.insert({node.id, node}); |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 705 | } else if (auto loadOp = dyn_cast<AffineLoadOp>(op)) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 706 | // Create graph node for top-level load op. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 707 | Node node(nextNodeId++, &op); |
| 708 | node.loads.push_back(&op); |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 709 | auto memref = cast<AffineLoadOp>(op).getMemRef(); |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 710 | memrefAccesses[memref].insert(node.id); |
| 711 | nodes.insert({node.id, node}); |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 712 | } else if (auto storeOp = dyn_cast<AffineStoreOp>(op)) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 713 | // Create graph node for top-level store op. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 714 | Node node(nextNodeId++, &op); |
| 715 | node.stores.push_back(&op); |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 716 | auto memref = cast<AffineStoreOp>(op).getMemRef(); |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 717 | memrefAccesses[memref].insert(node.id); |
| 718 | nodes.insert({node.id, node}); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 719 | } else if (op.getNumRegions() != 0) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 720 | // Return false if another region is found (not currently supported). |
| 721 | return false; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 722 | } else if (op.getNumResults() > 0 && !op.use_empty()) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 723 | // Create graph node for top-level producer of SSA values, which |
| 724 | // could be used by loop nest nodes. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 725 | Node node(nextNodeId++, &op); |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 726 | nodes.insert({node.id, node}); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 727 | } |
| 728 | } |
| 729 | |
| 730 | // Add dependence edges between nodes which produce SSA values and their |
| 731 | // users. |
| 732 | for (auto &idAndNode : nodes) { |
| 733 | const Node &node = idAndNode.second; |
| 734 | if (!node.loads.empty() || !node.stores.empty()) |
| 735 | continue; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 736 | auto *opInst = node.op; |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 737 | for (auto value : opInst->getResults()) { |
River Riddle | 8780d8d | 2019-05-18 18:09:07 | [diff] [blame] | 738 | for (auto *user : value->getUsers()) { |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 739 | SmallVector<AffineForOp, 4> loops; |
River Riddle | 8780d8d | 2019-05-18 18:09:07 | [diff] [blame] | 740 | getLoopIVs(*user, &loops); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 741 | if (loops.empty()) |
| 742 | continue; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 743 | assert(forToNodeMap.count(loops[0].getOperation()) > 0); |
| 744 | unsigned userLoopNestId = forToNodeMap[loops[0].getOperation()]; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 745 | addEdge(node.id, userLoopNestId, value); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 746 | } |
| 747 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 748 | } |
| 749 | |
| 750 | // Walk memref access lists and add graph edges between dependent nodes. |
| 751 | for (auto &memrefAndList : memrefAccesses) { |
| 752 | unsigned n = memrefAndList.second.size(); |
| 753 | for (unsigned i = 0; i < n; ++i) { |
| 754 | unsigned srcId = memrefAndList.second[i]; |
| 755 | bool srcHasStore = |
| 756 | getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0; |
| 757 | for (unsigned j = i + 1; j < n; ++j) { |
| 758 | unsigned dstId = memrefAndList.second[j]; |
| 759 | bool dstHasStore = |
| 760 | getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0; |
| 761 | if (srcHasStore || dstHasStore) |
| 762 | addEdge(srcId, dstId, memrefAndList.first); |
| 763 | } |
| 764 | } |
| 765 | } |
| 766 | return true; |
| 767 | } |
| 768 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 769 | // Removes load operations from 'srcLoads' which operate on 'memref', and |
| 770 | // adds them to 'dstLoads'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 771 | static void moveLoadsAccessingMemrefTo(ValuePtr memref, |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 772 | SmallVectorImpl<Operation *> *srcLoads, |
| 773 | SmallVectorImpl<Operation *> *dstLoads) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 774 | dstLoads->clear(); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 775 | SmallVector<Operation *, 4> srcLoadsToKeep; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 776 | for (auto *load : *srcLoads) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 777 | if (cast<AffineLoadOp>(load).getMemRef() == memref) |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 778 | dstLoads->push_back(load); |
| 779 | else |
| 780 | srcLoadsToKeep.push_back(load); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 781 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 782 | srcLoads->swap(srcLoadsToKeep); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 783 | } |
| 784 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 785 | // Returns the innermost common loop depth for the set of operations in 'ops'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 786 | static unsigned getInnermostCommonLoopDepth(ArrayRef<Operation *> ops) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 787 | unsigned numOps = ops.size(); |
| 788 | assert(numOps > 0); |
| 789 | |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 790 | std::vector<SmallVector<AffineForOp, 4>> loops(numOps); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 791 | unsigned loopDepthLimit = std::numeric_limits<unsigned>::max(); |
| 792 | for (unsigned i = 0; i < numOps; ++i) { |
| 793 | getLoopIVs(*ops[i], &loops[i]); |
| 794 | loopDepthLimit = |
| 795 | std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size())); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 796 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 797 | |
| 798 | unsigned loopDepth = 0; |
| 799 | for (unsigned d = 0; d < loopDepthLimit; ++d) { |
| 800 | unsigned i; |
| 801 | for (i = 1; i < numOps; ++i) { |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 802 | if (loops[i - 1][d] != loops[i][d]) |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 803 | break; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 804 | } |
| 805 | if (i != numOps) |
| 806 | break; |
| 807 | ++loopDepth; |
| 808 | } |
| 809 | return loopDepth; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 810 | } |
| 811 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 812 | // Returns the maximum loop depth at which no dependences between 'loadOpInsts' |
| 813 | // and 'storeOpInsts' are satisfied. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 814 | static unsigned getMaxLoopDepth(ArrayRef<Operation *> loadOpInsts, |
| 815 | ArrayRef<Operation *> storeOpInsts) { |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 816 | // Merge loads and stores into the same array. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 817 | SmallVector<Operation *, 2> ops(loadOpInsts.begin(), loadOpInsts.end()); |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 818 | ops.append(storeOpInsts.begin(), storeOpInsts.end()); |
| 819 | |
| 820 | // Compute the innermost common loop depth for loads and stores. |
| 821 | unsigned loopDepth = getInnermostCommonLoopDepth(ops); |
| 822 | |
| 823 | // Return common loop depth for loads if there are no store ops. |
| 824 | if (storeOpInsts.empty()) |
| 825 | return loopDepth; |
| 826 | |
| 827 | // Check dependences on all pairs of ops in 'ops' and store the minimum |
| 828 | // loop depth at which a dependence is satisfied. |
| 829 | for (unsigned i = 0, e = ops.size(); i < e; ++i) { |
| 830 | auto *srcOpInst = ops[i]; |
| 831 | MemRefAccess srcAccess(srcOpInst); |
| 832 | for (unsigned j = 0; j < e; ++j) { |
| 833 | auto *dstOpInst = ops[j]; |
| 834 | MemRefAccess dstAccess(dstOpInst); |
| 835 | |
| 836 | unsigned numCommonLoops = |
| 837 | getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst); |
| 838 | for (unsigned d = 1; d <= numCommonLoops + 1; ++d) { |
| 839 | FlatAffineConstraints dependenceConstraints; |
| 840 | // TODO(andydavis) Cache dependence analysis results, check cache here. |
Andy Davis | e33e36f | 2019-06-10 17:50:08 | [diff] [blame] | 841 | DependenceResult result = checkMemrefAccessDependence( |
| 842 | srcAccess, dstAccess, d, &dependenceConstraints, |
| 843 | /*dependenceComponents=*/nullptr); |
| 844 | if (hasDependence(result)) { |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 845 | // Store minimum loop depth and break because we want the min 'd' at |
| 846 | // which there is a dependence. |
| 847 | loopDepth = std::min(loopDepth, d - 1); |
| 848 | break; |
| 849 | } |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | return loopDepth; |
| 854 | } |
| 855 | |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 856 | // Sinks all sequential loops to the innermost levels (while preserving |
| 857 | // relative order among them) and moves all parallel loops to the |
| 858 | // outermost (while again preserving relative order among them). |
| 859 | // This can increase the loop depth at which we can fuse a slice, since we are |
| 860 | // pushing loop carried dependence to a greater depth in the loop nest. |
| 861 | static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) { |
River Riddle | d5b60ee8 | 2019-05-12 01:59:54 | [diff] [blame] | 862 | assert(isa<AffineForOp>(node->op)); |
Andy Davis | 90d4023 | 2019-05-13 13:57:56 | [diff] [blame] | 863 | AffineForOp newRootForOp = sinkSequentialLoops(cast<AffineForOp>(node->op)); |
| 864 | node->op = newRootForOp.getOperation(); |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 865 | } |
| 866 | |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 867 | // TODO(mlir-team): improve/complete this when we have target data. |
River Riddle | 2666b97 | 2019-12-18 18:46:16 | [diff] [blame] | 868 | static unsigned getMemRefEltSizeInBytes(MemRefType memRefType) { |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 869 | auto elementType = memRefType.getElementType(); |
| 870 | |
| 871 | unsigned sizeInBits; |
| 872 | if (elementType.isIntOrFloat()) { |
| 873 | sizeInBits = elementType.getIntOrFloatBitWidth(); |
| 874 | } else { |
| 875 | auto vectorType = elementType.cast<VectorType>(); |
| 876 | sizeInBits = |
| 877 | vectorType.getElementTypeBitWidth() * vectorType.getNumElements(); |
| 878 | } |
| 879 | return llvm::divideCeil(sizeInBits, 8); |
| 880 | } |
| 881 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 882 | // Creates and returns a private (single-user) memref for fused loop rooted |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 883 | // at 'forOp', with (potentially reduced) memref size based on the |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 884 | // MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'. |
| 885 | // TODO(bondhugula): consider refactoring the common code from generateDma and |
| 886 | // this one. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 887 | static ValuePtr createPrivateMemRef(AffineForOp forOp, |
| 888 | Operation *srcStoreOpInst, |
| 889 | unsigned dstLoopDepth, |
| 890 | Optional<unsigned> fastMemorySpace, |
| 891 | uint64_t localBufSizeThreshold) { |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 892 | auto *forInst = forOp.getOperation(); |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 893 | |
| 894 | // Create builder to insert alloc op just before 'forOp'. |
River Riddle | f1b848e | 2019-06-05 02:18:23 | [diff] [blame] | 895 | OpBuilder b(forInst); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 896 | // Builder to create constants at the top level. |
River Riddle | ce502af | 2019-07-08 18:20:26 | [diff] [blame] | 897 | OpBuilder top(forInst->getParentOfType<FuncOp>().getBody()); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 898 | // Create new memref type based on slice bounds. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 899 | auto oldMemRef = cast<AffineStoreOp>(srcStoreOpInst).getMemRef(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 900 | auto oldMemRefType = oldMemRef->getType().cast<MemRefType>(); |
| 901 | unsigned rank = oldMemRefType.getRank(); |
| 902 | |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 903 | // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'. |
Uday Bondhugula | 0f50414 | 2019-02-04 21:48:44 | [diff] [blame] | 904 | MemRefRegion region(srcStoreOpInst->getLoc()); |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 905 | bool validRegion = succeeded(region.compute(srcStoreOpInst, dstLoopDepth)); |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 906 | (void)validRegion; |
| 907 | assert(validRegion && "unexpected memref region failure"); |
River Riddle | 6859f33 | 2019-01-23 22:39:45 | [diff] [blame] | 908 | SmallVector<int64_t, 4> newShape; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 909 | std::vector<SmallVector<int64_t, 4>> lbs; |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 910 | SmallVector<int64_t, 8> lbDivisors; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 911 | lbs.reserve(rank); |
| 912 | // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 913 | // by 'srcStoreOpInst' at depth 'dstLoopDepth'. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 914 | Optional<int64_t> numElements = |
Uday Bondhugula | 0f50414 | 2019-02-04 21:48:44 | [diff] [blame] | 915 | region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors); |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 916 | assert(numElements.hasValue() && |
| 917 | "non-constant number of elts in local buffer"); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 918 | |
Uday Bondhugula | 0f50414 | 2019-02-04 21:48:44 | [diff] [blame] | 919 | const FlatAffineConstraints *cst = region.getConstraints(); |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 920 | // 'outerIVs' holds the values that this memory region is symbolic/parametric |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 921 | // on; this would correspond to loop IVs surrounding the level at which the |
| 922 | // slice is being materialized. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 923 | SmallVector<ValuePtr, 8> outerIVs; |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 924 | cst->getIdValues(rank, cst->getNumIds(), &outerIVs); |
| 925 | |
| 926 | // Build 'rank' AffineExprs from MemRefRegion 'lbs' |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 927 | SmallVector<AffineExpr, 4> offsets; |
| 928 | offsets.reserve(rank); |
| 929 | for (unsigned d = 0; d < rank; ++d) { |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 930 | assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size"); |
| 931 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 932 | AffineExpr offset = top.getAffineConstantExpr(0); |
| 933 | for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) { |
| 934 | offset = offset + lbs[d][j] * top.getAffineDimExpr(j); |
| 935 | } |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 936 | assert(lbDivisors[d] > 0); |
| 937 | offset = |
| 938 | (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 939 | offsets.push_back(offset); |
| 940 | } |
| 941 | |
| 942 | // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed |
| 943 | // by 'srcStoreOpInst'. |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 944 | uint64_t bufSize = |
| 945 | getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue(); |
| 946 | unsigned newMemSpace; |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 947 | if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) { |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 948 | newMemSpace = fastMemorySpace.getValue(); |
| 949 | } else { |
| 950 | newMemSpace = oldMemRefType.getMemorySpace(); |
| 951 | } |
River Riddle | 2acc220 | 2019-10-18 03:08:01 | [diff] [blame] | 952 | auto newMemRefType = MemRefType::get(newShape, oldMemRefType.getElementType(), |
| 953 | {}, newMemSpace); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 954 | // Gather alloc operands for the dynamic dimensions of the memref. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 955 | SmallVector<ValuePtr, 4> allocOperands; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 956 | unsigned dynamicDimCount = 0; |
| 957 | for (auto dimSize : oldMemRefType.getShape()) { |
| 958 | if (dimSize == -1) |
| 959 | allocOperands.push_back( |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 960 | top.create<DimOp>(forOp.getLoc(), oldMemRef, dynamicDimCount++)); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 961 | } |
| 962 | |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 963 | // Create new private memref for fused loop 'forOp'. |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 964 | // TODO(andydavis) Create/move alloc ops for private memrefs closer to their |
| 965 | // consumer loop nests to reduce their live range. Currently they are added |
| 966 | // at the beginning of the function, because loop nests can be reordered |
| 967 | // during the fusion pass. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 968 | ValuePtr newMemRef = |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 969 | top.create<AllocOp>(forOp.getLoc(), newMemRefType, allocOperands); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 970 | |
| 971 | // Build an AffineMap to remap access functions based on lower bound offsets. |
| 972 | SmallVector<AffineExpr, 4> remapExprs; |
| 973 | remapExprs.reserve(rank); |
| 974 | unsigned zeroOffsetCount = 0; |
| 975 | for (unsigned i = 0; i < rank; i++) { |
| 976 | if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>()) |
| 977 | if (constExpr.getValue() == 0) |
| 978 | ++zeroOffsetCount; |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 979 | auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i); |
| 980 | |
| 981 | auto remapExpr = |
| 982 | simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0); |
| 983 | remapExprs.push_back(remapExpr); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 984 | } |
MLIR Team | 5a91b98 | 2019-05-29 21:56:41 | [diff] [blame] | 985 | auto indexRemap = zeroOffsetCount == rank |
| 986 | ? AffineMap() |
River Riddle | 2acc220 | 2019-10-18 03:08:01 | [diff] [blame] | 987 | : AffineMap::get(outerIVs.size() + rank, 0, remapExprs); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 988 | // Replace all users of 'oldMemRef' with 'newMemRef'. |
Uday Bondhugula | aa2cee9 | 2019-08-28 00:56:25 | [diff] [blame] | 989 | LogicalResult res = |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 990 | replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap, |
| 991 | /*extraOperands=*/outerIVs, |
Uday Bondhugula | 727a50a | 2019-09-18 18:25:33 | [diff] [blame] | 992 | /*symbolOperands=*/{}, |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 993 | /*domInstFilter=*/&*forOp.getBody()->begin()); |
Uday Bondhugula | aa2cee9 | 2019-08-28 00:56:25 | [diff] [blame] | 994 | assert(succeeded(res) && |
| 995 | "replaceAllMemrefUsesWith should always succeed here"); |
| 996 | (void)res; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 997 | return newMemRef; |
| 998 | } |
| 999 | |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1000 | // Checks if node 'srcId' can be safely fused into node 'dstId'. Node 'srcId' |
| 1001 | // may write to multiple memrefs but it is required that only one of them, |
Diego Caballero | 330d1ff | 2019-12-03 14:09:21 | [diff] [blame] | 1002 | // 'srcLiveOutStoreOp', has output edges. |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1003 | // Returns true if 'dstNode's read/write region to 'memref' is a super set of |
Diego Caballero | 330d1ff | 2019-12-03 14:09:21 | [diff] [blame] | 1004 | // 'srcNode's write region to 'memref' and 'srcId' has only one output edge. |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1005 | // TODO(andydavis) Generalize this to handle more live in/out cases. |
| 1006 | static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId, |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1007 | AffineStoreOp srcLiveOutStoreOp, |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1008 | MemRefDependenceGraph *mdg) { |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1009 | assert(srcLiveOutStoreOp && "Expected a valid store op"); |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1010 | auto *dstNode = mdg->getNode(dstId); |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1011 | ValuePtr memref = srcLiveOutStoreOp.getMemRef(); |
Diego Caballero | 330d1ff | 2019-12-03 14:09:21 | [diff] [blame] | 1012 | // Return false if 'srcNode' has more than one output edge on 'memref'. |
| 1013 | if (mdg->getOutEdgeCount(srcId, memref) > 1) |
| 1014 | return false; |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1015 | |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1016 | // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOp' on 'memref'. |
| 1017 | MemRefRegion srcWriteRegion(srcLiveOutStoreOp.getLoc()); |
| 1018 | if (failed(srcWriteRegion.compute(srcLiveOutStoreOp, /*loopDepth=*/0))) { |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1019 | LLVM_DEBUG(llvm::dbgs() |
| 1020 | << "Unable to compute MemRefRegion for source operation\n."); |
| 1021 | return false; |
| 1022 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1023 | SmallVector<int64_t, 4> srcShape; |
| 1024 | // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'. |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1025 | // by 'srcStoreOp' at depth 'dstLoopDepth'. |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1026 | Optional<int64_t> srcNumElements = |
| 1027 | srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape); |
| 1028 | if (!srcNumElements.hasValue()) |
| 1029 | return false; |
| 1030 | |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1031 | // Compute MemRefRegion 'dstRegion' for 'dstStore/LoadOpInst' on 'memref'. |
MLIR Team | 9d9675f | 2019-03-28 21:54:49 | [diff] [blame] | 1032 | // TODO(andydavis) Compute 'unionboundingbox' of all write regions (one for |
| 1033 | // each store op in 'dstStoreOps'). |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1034 | SmallVector<Operation *, 2> dstStoreOps; |
| 1035 | dstNode->getStoreOpsForMemref(memref, &dstStoreOps); |
| 1036 | SmallVector<Operation *, 2> dstLoadOps; |
| 1037 | dstNode->getLoadOpsForMemref(memref, &dstLoadOps); |
| 1038 | |
| 1039 | auto *dstOpInst = dstStoreOps.empty() ? dstLoadOps[0] : dstStoreOps[0]; |
| 1040 | MemRefRegion dstRegion(dstOpInst->getLoc()); |
| 1041 | if (failed(dstRegion.compute(dstOpInst, /*loopDepth=*/0))) { |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1042 | LLVM_DEBUG(llvm::dbgs() |
| 1043 | << "Unable to compute MemRefRegion for dest operation\n."); |
| 1044 | return false; |
| 1045 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1046 | SmallVector<int64_t, 4> dstShape; |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1047 | // Query 'dstRegion' for 'dstShape' and 'dstNumElements'. |
| 1048 | // by 'dstOpInst' at depth 'dstLoopDepth'. |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1049 | Optional<int64_t> dstNumElements = |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1050 | dstRegion.getConstantBoundingSizeAndShape(&dstShape); |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1051 | if (!dstNumElements.hasValue()) |
| 1052 | return false; |
| 1053 | |
| 1054 | // Return false if write region is not a superset of 'srcNodes' write |
| 1055 | // region to 'memref'. |
| 1056 | // TODO(andydavis) Check the shape and lower bounds here too. |
| 1057 | if (srcNumElements != dstNumElements) |
| 1058 | return false; |
| 1059 | return true; |
| 1060 | } |
| 1061 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1062 | // Checks the profitability of fusing a backwards slice of the loop nest |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1063 | // surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1064 | // The argument 'srcStoreOpInst' is used to calculate the storage reduction on |
| 1065 | // the memref being produced and consumed, which is an input to the cost model. |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 1066 | // For producer-consumer fusion, 'srcStoreOpInst' will be the same as |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1067 | // 'srcOpInst', as we are slicing w.r.t to that producer. |
| 1068 | // For input-reuse fusion, 'srcOpInst' will be the src loop nest LoadOp which |
| 1069 | // reads from the same memref as dst loop nest load ops, and 'srcStoreOpInst' |
| 1070 | // will be the unique store op in the src node, which will be used to check |
| 1071 | // that the write region is the same after input-reuse fusion. |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1072 | // Returns true if it is profitable to fuse the candidate loop nests. Returns |
| 1073 | // false otherwise. `dstLoopDepth` is set to the most profitable depth at which |
| 1074 | // to materialize the source loop nest slice. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1075 | // The profitability model executes the following steps: |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1076 | // *) Computes the backward computation slice at 'srcOpInst'. This |
| 1077 | // computation slice of the loop nest surrounding 'srcOpInst' is |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1078 | // represented by modified src loop bounds in 'sliceState', which are |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1079 | // functions of loop IVs in the loop nest surrounding 'srcOpInst'. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1080 | // *) Computes the cost of unfused src/dst loop nests (currently the cost of a |
| 1081 | // loop nest is the total number of dynamic operation instances in the loop |
| 1082 | // nest). |
| 1083 | // *) Computes the cost of fusing a slice of the src loop nest into the dst |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1084 | // loop nest at various values of dst loop depth, attempting to fuse |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 1085 | // the largest computation slice at the maximal dst loop depth (closest to |
| 1086 | // the load) to minimize reuse distance and potentially enable subsequent |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1087 | // load/store forwarding. |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1088 | // NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1089 | // the same memref as is written by 'srcOpInst', then the union of slice |
| 1090 | // loop bounds is used to compute the slice and associated slice cost. |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1091 | // NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1092 | // nest, at which the src computation slice is inserted/fused. |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1093 | // NOTE: We attempt to maximize the dst loop depth, but there are cases |
| 1094 | // where a particular setting for 'dstLoopNest' might fuse an unsliced |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1095 | // loop (within the src computation slice) at a depth which results in |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 1096 | // excessive recomputation (see unit tests for examples). |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1097 | // *) Compares the total cost of the unfused loop nests to the min cost fused |
| 1098 | // loop nest computed in the previous step, and returns true if the latter |
| 1099 | // is lower. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1100 | static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst, |
| 1101 | ArrayRef<Operation *> dstLoadOpInsts, |
| 1102 | ArrayRef<Operation *> dstStoreOpInsts, |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1103 | ComputationSliceState *sliceState, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1104 | unsigned *dstLoopDepth, bool maximalFusion) { |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1105 | LLVM_DEBUG({ |
| 1106 | llvm::dbgs() << "Checking whether fusion is profitable between:\n"; |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1107 | llvm::dbgs() << " " << *srcOpInst << " and \n"; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1108 | for (auto dstOpInst : dstLoadOpInsts) { |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1109 | llvm::dbgs() << " " << *dstOpInst << "\n"; |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1110 | }; |
| 1111 | }); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1112 | |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1113 | // Compute cost of sliced and unsliced src loop nest. |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1114 | SmallVector<AffineForOp, 4> srcLoopIVs; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1115 | getLoopIVs(*srcOpInst, &srcLoopIVs); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1116 | unsigned numSrcLoopIVs = srcLoopIVs.size(); |
| 1117 | |
| 1118 | // Walk src loop nest and collect stats. |
| 1119 | LoopNestStats srcLoopNestStats; |
Andy Davis | 59b6814 | 2019-06-18 15:52:09 | [diff] [blame] | 1120 | if (!getLoopNestStats(srcLoopIVs[0], &srcLoopNestStats)) |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1121 | return false; |
Andy Davis | 59b6814 | 2019-06-18 15:52:09 | [diff] [blame] | 1122 | |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1123 | // Compute cost of dst loop nest. |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1124 | SmallVector<AffineForOp, 4> dstLoopIVs; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1125 | getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1126 | |
| 1127 | LoopNestStats dstLoopNestStats; |
Andy Davis | 59b6814 | 2019-06-18 15:52:09 | [diff] [blame] | 1128 | if (!getLoopNestStats(dstLoopIVs[0], &dstLoopNestStats)) |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1129 | return false; |
| 1130 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1131 | // Compute the maximum loop depth at which we can can insert the src slice |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1132 | // and still satisfy dest loop nest dependences, for producer-consumer fusion. |
| 1133 | unsigned maxDstLoopDepth = |
| 1134 | (srcOpInst == srcStoreOpInst) |
| 1135 | ? getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts) |
| 1136 | : dstLoopIVs.size(); |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1137 | if (maxDstLoopDepth == 0) { |
| 1138 | LLVM_DEBUG(llvm::dbgs() << "Can't fuse: maxDstLoopDepth == 0 .\n"); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1139 | return false; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1140 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1141 | |
| 1142 | // Search for min cost value for 'dstLoopDepth'. At each value of |
| 1143 | // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice |
| 1144 | // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union |
| 1145 | // of these bounds). Next the union slice bounds are used to calculate |
| 1146 | // the cost of the slice and the cost of the slice inserted into the dst |
| 1147 | // loop nest at 'dstLoopDepth'. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1148 | uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max(); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1149 | double maxStorageReduction = 0.0; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1150 | Optional<uint64_t> sliceMemEstimate = None; |
| 1151 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1152 | SmallVector<ComputationSliceState, 4> sliceStates; |
| 1153 | sliceStates.resize(maxDstLoopDepth); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1154 | // The best loop depth at which to materialize the slice. |
| 1155 | Optional<unsigned> bestDstLoopDepth = None; |
| 1156 | |
| 1157 | // Compute op instance count for the src loop nest without iteration slicing. |
Andy Davis | 59b6814 | 2019-06-18 15:52:09 | [diff] [blame] | 1158 | uint64_t srcLoopNestCost = getComputeCost(srcLoopIVs[0], srcLoopNestStats); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1159 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1160 | // Compute src loop nest write region size. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1161 | MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc()); |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1162 | if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) { |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1163 | LLVM_DEBUG(llvm::dbgs() |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1164 | << "Unable to compute MemRefRegion for source operation\n."); |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1165 | return false; |
| 1166 | } |
| 1167 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1168 | Optional<int64_t> maybeSrcWriteRegionSizeBytes = |
| 1169 | srcWriteRegion.getRegionSize(); |
| 1170 | if (!maybeSrcWriteRegionSizeBytes.hasValue()) |
| 1171 | return false; |
| 1172 | int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue(); |
| 1173 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1174 | // Compute op instance count for the src loop nest. |
Andy Davis | 59b6814 | 2019-06-18 15:52:09 | [diff] [blame] | 1175 | uint64_t dstLoopNestCost = getComputeCost(dstLoopIVs[0], dstLoopNestStats); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1176 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1177 | // Evaluate all depth choices for materializing the slice in the destination |
| 1178 | // loop nest. |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1179 | for (unsigned i = maxDstLoopDepth; i >= 1; --i) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1180 | // Compute the union of slice bounds of all ops in 'dstLoadOpInsts'. |
Andy Davis | 1de0f97 | 2019-05-29 21:02:14 | [diff] [blame] | 1181 | if (failed(mlir::computeSliceUnion({srcOpInst}, dstLoadOpInsts, |
Andy Davis | 898cf0e | 2019-06-17 16:59:35 | [diff] [blame] | 1182 | /*loopDepth=*/i, |
| 1183 | /*numCommonLoops=*/0, |
| 1184 | /*isBackwardSlice=*/true, |
Andy Davis | 1de0f97 | 2019-05-29 21:02:14 | [diff] [blame] | 1185 | &sliceStates[i - 1]))) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1186 | LLVM_DEBUG(llvm::dbgs() |
Andy Davis | 1de0f97 | 2019-05-29 21:02:14 | [diff] [blame] | 1187 | << "computeSliceUnion failed for loopDepth: " << i << "\n"); |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1188 | continue; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1189 | } |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1190 | |
Andy Davis | 59b6814 | 2019-06-18 15:52:09 | [diff] [blame] | 1191 | int64_t fusedLoopNestComputeCost; |
| 1192 | if (!getFusionComputeCost(srcLoopIVs[0], srcLoopNestStats, dstLoopIVs[0], |
| 1193 | dstLoopNestStats, &sliceStates[i - 1], |
| 1194 | &fusedLoopNestComputeCost)) { |
| 1195 | LLVM_DEBUG(llvm::dbgs() << "Unable to compute fusion compute cost.\n."); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1196 | continue; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1197 | } |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1198 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1199 | double additionalComputeFraction = |
| 1200 | fusedLoopNestComputeCost / |
| 1201 | (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) - |
| 1202 | 1; |
| 1203 | |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1204 | // Determine what the slice write MemRefRegion would be, if the src loop |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1205 | // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop |
| 1206 | // nest at loop depth 'i' |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1207 | MemRefRegion sliceWriteRegion(srcStoreOpInst->getLoc()); |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1208 | if (failed(sliceWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0, |
| 1209 | &sliceStates[i - 1]))) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1210 | LLVM_DEBUG(llvm::dbgs() |
| 1211 | << "Failed to compute slice write region at loopDepth: " << i |
| 1212 | << "\n"); |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1213 | continue; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1214 | } |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1215 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1216 | Optional<int64_t> maybeSliceWriteRegionSizeBytes = |
| 1217 | sliceWriteRegion.getRegionSize(); |
| 1218 | if (!maybeSliceWriteRegionSizeBytes.hasValue() || |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1219 | maybeSliceWriteRegionSizeBytes.getValue() == 0) { |
| 1220 | LLVM_DEBUG(llvm::dbgs() |
| 1221 | << "Failed to get slice write region size at loopDepth: " << i |
| 1222 | << "\n"); |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1223 | continue; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1224 | } |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1225 | int64_t sliceWriteRegionSizeBytes = |
| 1226 | maybeSliceWriteRegionSizeBytes.getValue(); |
| 1227 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1228 | // If we are fusing for reuse, check that write regions remain the same. |
| 1229 | // TODO(andydavis) Write region check should check sizes and offsets in |
| 1230 | // each dimension, so that we are sure they are covering the same memref |
| 1231 | // region. Also, move this out to a isMemRefRegionSuperSet helper function. |
| 1232 | if (srcOpInst != srcStoreOpInst && |
| 1233 | sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes) |
| 1234 | continue; |
| 1235 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1236 | double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) / |
| 1237 | static_cast<double>(sliceWriteRegionSizeBytes); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1238 | |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1239 | LLVM_DEBUG({ |
| 1240 | std::stringstream msg; |
| 1241 | msg << " evaluating fusion profitability at depth : " << i << "\n" |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 1242 | << std::fixed << std::setprecision(2) |
| 1243 | << " additional compute fraction: " |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1244 | << 100.0 * additionalComputeFraction << "%\n" |
| 1245 | << " storage reduction factor: " << storageReduction << "x\n" |
| 1246 | << " fused nest cost: " << fusedLoopNestComputeCost << "\n" |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1247 | << " src write region size: " << srcWriteRegionSizeBytes << "\n" |
| 1248 | << " slice write region size: " << sliceWriteRegionSizeBytes |
| 1249 | << "\n"; |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1250 | llvm::dbgs() << msg.str(); |
| 1251 | }); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1252 | |
| 1253 | double computeToleranceThreshold = |
| 1254 | clFusionAddlComputeTolerance.getNumOccurrences() > 0 |
| 1255 | ? clFusionAddlComputeTolerance |
| 1256 | : LoopFusion::kComputeToleranceThreshold; |
| 1257 | |
| 1258 | // TODO(b/123247369): This is a placeholder cost model. |
| 1259 | // Among all choices that add an acceptable amount of redundant computation |
| 1260 | // (as per computeToleranceThreshold), we will simply pick the one that |
| 1261 | // reduces the intermediary size the most. |
| 1262 | if ((storageReduction > maxStorageReduction) && |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1263 | (maximalFusion || |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1264 | (additionalComputeFraction < computeToleranceThreshold))) { |
| 1265 | maxStorageReduction = storageReduction; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1266 | bestDstLoopDepth = i; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1267 | minFusedLoopNestComputeCost = fusedLoopNestComputeCost; |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1268 | sliceMemEstimate = sliceWriteRegionSizeBytes; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1269 | } |
| 1270 | } |
| 1271 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1272 | // A simple cost model: fuse if it reduces the memory footprint. If |
| 1273 | // -maximal-fusion is set, fuse nevertheless. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1274 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1275 | if (!maximalFusion && !bestDstLoopDepth.hasValue()) { |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1276 | LLVM_DEBUG( |
| 1277 | llvm::dbgs() |
| 1278 | << "All fusion choices involve more than the threshold amount of " |
| 1279 | "redundant computation; NOT fusing.\n"); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1280 | return false; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1281 | } |
| 1282 | |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1283 | if (!bestDstLoopDepth.hasValue()) { |
| 1284 | LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n"); |
| 1285 | return false; |
| 1286 | } |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1287 | |
| 1288 | // Set dstLoopDepth based on best values from search. |
| 1289 | *dstLoopDepth = bestDstLoopDepth.getValue(); |
| 1290 | |
| 1291 | LLVM_DEBUG( |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1292 | llvm::dbgs() << " LoopFusion fusion stats:" |
| 1293 | << "\n best loop depth: " << bestDstLoopDepth |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1294 | << "\n src loop nest compute cost: " << srcLoopNestCost |
| 1295 | << "\n dst loop nest compute cost: " << dstLoopNestCost |
| 1296 | << "\n fused loop nest compute cost: " |
| 1297 | << minFusedLoopNestComputeCost << "\n"); |
| 1298 | |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1299 | auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]); |
| 1300 | auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1301 | |
| 1302 | Optional<double> storageReduction = None; |
| 1303 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1304 | if (!maximalFusion) { |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1305 | if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) { |
| 1306 | LLVM_DEBUG( |
| 1307 | llvm::dbgs() |
| 1308 | << " fusion memory benefit cannot be evaluated; NOT fusing.\n"); |
| 1309 | return false; |
| 1310 | } |
| 1311 | |
| 1312 | auto srcMemSizeVal = srcMemSize.getValue(); |
| 1313 | auto dstMemSizeVal = dstMemSize.getValue(); |
| 1314 | |
| 1315 | assert(sliceMemEstimate.hasValue() && "expected value"); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1316 | auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue(); |
| 1317 | |
| 1318 | LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n" |
| 1319 | << " dst mem: " << dstMemSizeVal << "\n" |
| 1320 | << " fused mem: " << fusedMem << "\n" |
| 1321 | << " slice mem: " << sliceMemEstimate << "\n"); |
| 1322 | |
Jacques Pienaar | 2fe8ae4 | 2019-05-04 02:48:57 | [diff] [blame] | 1323 | if (static_cast<long>(fusedMem) > srcMemSizeVal + dstMemSizeVal) { |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1324 | LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n"); |
| 1325 | return false; |
| 1326 | } |
| 1327 | storageReduction = |
| 1328 | 100.0 * |
| 1329 | (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal)); |
| 1330 | } |
| 1331 | |
| 1332 | double additionalComputeFraction = |
| 1333 | 100.0 * (minFusedLoopNestComputeCost / |
| 1334 | (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) - |
| 1335 | 1); |
MLIR Team | 5c5739d | 2019-01-25 06:27:40 | [diff] [blame] | 1336 | (void)additionalComputeFraction; |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1337 | LLVM_DEBUG({ |
| 1338 | std::stringstream msg; |
| 1339 | msg << " fusion is most profitable at depth " << *dstLoopDepth << " with " |
MLIR Team | 8564b27 | 2019-02-22 15:48:59 | [diff] [blame] | 1340 | << std::setprecision(2) << additionalComputeFraction |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1341 | << "% redundant computation and a "; |
| 1342 | msg << (storageReduction.hasValue() |
| 1343 | ? std::to_string(storageReduction.getValue()) |
| 1344 | : "<unknown>"); |
| 1345 | msg << "% storage reduction.\n"; |
| 1346 | llvm::dbgs() << msg.str(); |
| 1347 | }); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1348 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1349 | // Update return parameter 'sliceState' with 'bestSliceState'. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1350 | ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1]; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1351 | sliceState->lbs = bestSliceState->lbs; |
| 1352 | sliceState->ubs = bestSliceState->ubs; |
| 1353 | sliceState->lbOperands = bestSliceState->lbOperands; |
| 1354 | sliceState->ubOperands = bestSliceState->ubOperands; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1355 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1356 | // Canonicalize slice bound affine maps. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1357 | for (unsigned i = 0; i < numSrcLoopIVs; ++i) { |
Nicolas Vasilache | 0e7a8a9 | 2019-01-26 18:41:17 | [diff] [blame] | 1358 | if (sliceState->lbs[i] != AffineMap()) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1359 | canonicalizeMapAndOperands(&sliceState->lbs[i], |
| 1360 | &sliceState->lbOperands[i]); |
| 1361 | } |
Nicolas Vasilache | 0e7a8a9 | 2019-01-26 18:41:17 | [diff] [blame] | 1362 | if (sliceState->ubs[i] != AffineMap()) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1363 | canonicalizeMapAndOperands(&sliceState->ubs[i], |
| 1364 | &sliceState->ubOperands[i]); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1365 | } |
| 1366 | } |
| 1367 | return true; |
| 1368 | } |
| 1369 | |
River Riddle | 2666b97 | 2019-12-18 18:46:16 | [diff] [blame] | 1370 | namespace { |
| 1371 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1372 | // GreedyFusion greedily fuses loop nests which have a producer/consumer or |
| 1373 | // input-reuse relationship on a memref, with the goal of improving locality. |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1374 | // |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1375 | // The steps of the producer-consumer fusion algorithm are as follows: |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1376 | // |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1377 | // *) A worklist is initialized with node ids from the dependence graph. |
| 1378 | // *) For each node id in the worklist: |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1379 | // *) Pop an AffineForOp of the worklist. This 'dstAffineForOp' will be a |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1380 | // candidate destination AffineForOp into which fusion will be attempted. |
| 1381 | // *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'. |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1382 | // *) For each LoadOp in 'dstLoadOps' do: |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1383 | // *) Look up dependent loop nests which have a single store op to the same |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1384 | // memref. |
| 1385 | // *) Check if dependences would be violated by the fusion. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1386 | // *) Get a computation slice of 'srcLoopNest', which adjusts its loop |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1387 | // bounds to be functions of 'dstLoopNest' IVs and symbols. |
| 1388 | // *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest', |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1389 | // at a loop depth determined by the cost model in 'isFusionProfitable'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1390 | // *) Add the newly fused load/store operations to the state, |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1391 | // and also add newly fused load ops to 'dstLoopOps' to be considered |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1392 | // as fusion dst load ops in another iteration. |
| 1393 | // *) Remove old src loop nest and its associated state. |
| 1394 | // |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1395 | // The steps of the input-reuse fusion algorithm are as follows: |
| 1396 | // |
| 1397 | // *) Initialize 'worklist' with node ids from the dependence graph. |
| 1398 | // *) For each 'dstNode' in the worklist: |
| 1399 | // *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which |
| 1400 | // loads from the same memref, but which has no dependence paths to/from. |
| 1401 | // *) Get a computation slice of 'sibLoopNest', which adjusts its loop |
| 1402 | // bounds to be functions of 'dstLoopNest' IVs and symbols. |
| 1403 | // *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest', |
| 1404 | // at a loop depth determined by the cost model in 'isFusionProfitable'. |
| 1405 | // This function also checks that the memref write region of 'sibLoopNest', |
| 1406 | // is preserved in the fused loop nest. |
| 1407 | // *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'. |
| 1408 | // |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1409 | // Given a graph where top-level operations are vertices in the set 'V' and |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1410 | // edges in the set 'E' are dependences between vertices, this algorithm |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1411 | // takes O(V) time for initialization, and has runtime O(V + E). |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1412 | // |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1413 | // This greedy algorithm is not 'maximal' due to the current restriction of |
| 1414 | // fusing along single producer consumer edges, but there is a TODO to fix this. |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1415 | // |
| 1416 | // TODO(andydavis) Experiment with other fusion policies. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1417 | struct GreedyFusion { |
| 1418 | public: |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1419 | // The data dependence graph to traverse during fusion. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1420 | MemRefDependenceGraph *mdg; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1421 | // Worklist of graph nodes visited during the fusion pass. |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1422 | SmallVector<unsigned, 8> worklist; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1423 | // Set of graph nodes which are present on the worklist. |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1424 | llvm::SmallDenseSet<unsigned, 16> worklistSet; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1425 | // Parameter for local buffer size threshold. |
| 1426 | unsigned localBufSizeThreshold; |
| 1427 | // Parameter for fast memory space. |
| 1428 | Optional<unsigned> fastMemorySpace; |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1429 | // If true, ignore any additional (redundant) computation tolerance threshold |
| 1430 | // that would have prevented fusion. |
| 1431 | bool maximalFusion; |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1432 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1433 | using Node = MemRefDependenceGraph::Node; |
| 1434 | |
| 1435 | GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1436 | Optional<unsigned> fastMemorySpace, bool maximalFusion) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1437 | : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold), |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1438 | fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {} |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1439 | |
| 1440 | // Initializes 'worklist' with nodes from 'mdg' |
| 1441 | void init() { |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1442 | // TODO(andydavis) Add a priority queue for prioritizing nodes by different |
| 1443 | // metrics (e.g. arithmetic intensity/flops-to-bytes ratio). |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1444 | worklist.clear(); |
| 1445 | worklistSet.clear(); |
| 1446 | for (auto &idAndNode : mdg->nodes) { |
| 1447 | const Node &node = idAndNode.second; |
| 1448 | worklist.push_back(node.id); |
| 1449 | worklistSet.insert(node.id); |
| 1450 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1451 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1452 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1453 | // Run the GreedyFusion pass. |
| 1454 | // *) First pass through the nodes fuses single-use producer nodes into their |
| 1455 | // unique consumer. |
| 1456 | // *) Second pass fuses sibling nodes which share no dependence edges. |
| 1457 | // *) Third pass fuses any remaining producer nodes into their users. |
| 1458 | void run() { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1459 | // TODO(andydavis) Run this repeatedly until a fixed-point is reached. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1460 | fuseProducerConsumerNodes(/*maxSrcUserCount=*/1); |
| 1461 | fuseSiblingNodes(); |
| 1462 | fuseProducerConsumerNodes( |
| 1463 | /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max()); |
| 1464 | eraseUnusedMemRefAllocations(); |
| 1465 | } |
| 1466 | |
| 1467 | void fuseProducerConsumerNodes(unsigned maxSrcUserCount) { |
| 1468 | init(); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1469 | while (!worklist.empty()) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1470 | unsigned dstId = worklist.back(); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1471 | worklist.pop_back(); |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1472 | worklistSet.erase(dstId); |
| 1473 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1474 | // Skip if this node was removed (fused into another node). |
| 1475 | if (mdg->nodes.count(dstId) == 0) |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1476 | continue; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1477 | // Get 'dstNode' into which to attempt fusion. |
| 1478 | auto *dstNode = mdg->getNode(dstId); |
| 1479 | // Skip if 'dstNode' is not a loop nest. |
River Riddle | d5b60ee8 | 2019-05-12 01:59:54 | [diff] [blame] | 1480 | if (!isa<AffineForOp>(dstNode->op)) |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1481 | continue; |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 1482 | // Sink sequential loops in 'dstNode' (and thus raise parallel loops) |
| 1483 | // while preserving relative order. This can increase the maximum loop |
| 1484 | // depth at which we can fuse a slice of a producer loop nest into a |
| 1485 | // consumer loop nest. |
| 1486 | sinkSequentialLoops(dstNode); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1487 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1488 | SmallVector<Operation *, 4> loads = dstNode->loads; |
| 1489 | SmallVector<Operation *, 4> dstLoadOpInsts; |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1490 | DenseSet<ValuePtr> visitedMemrefs; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1491 | while (!loads.empty()) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1492 | // Get memref of load on top of the stack. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1493 | auto memref = cast<AffineLoadOp>(loads.back()).getMemRef(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1494 | if (visitedMemrefs.count(memref) > 0) |
| 1495 | continue; |
| 1496 | visitedMemrefs.insert(memref); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1497 | // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'. |
| 1498 | moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1499 | // Skip if no input edges along which to fuse. |
| 1500 | if (mdg->inEdges.count(dstId) == 0) |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1501 | continue; |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1502 | // Iterate through in-edges for 'dstId' and src node id for any |
MLIR Team | 1e85191 | 2019-01-31 00:01:46 | [diff] [blame] | 1503 | // edges on 'memref'. |
| 1504 | SmallVector<unsigned, 2> srcNodeIds; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1505 | for (auto &srcEdge : mdg->inEdges[dstId]) { |
| 1506 | // Skip 'srcEdge' if not for 'memref'. |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1507 | if (srcEdge.value != memref) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1508 | continue; |
MLIR Team | 1e85191 | 2019-01-31 00:01:46 | [diff] [blame] | 1509 | srcNodeIds.push_back(srcEdge.id); |
| 1510 | } |
| 1511 | for (unsigned srcId : srcNodeIds) { |
| 1512 | // Skip if this node was removed (fused into another node). |
| 1513 | if (mdg->nodes.count(srcId) == 0) |
| 1514 | continue; |
| 1515 | // Get 'srcNode' from which to attempt fusion into 'dstNode'. |
| 1516 | auto *srcNode = mdg->getNode(srcId); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1517 | // Skip if 'srcNode' is not a loop nest. |
River Riddle | d5b60ee8 | 2019-05-12 01:59:54 | [diff] [blame] | 1518 | if (!isa<AffineForOp>(srcNode->op)) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1519 | continue; |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1520 | // Skip if 'srcNode' has more than one live-out store to a |
| 1521 | // function-local memref. |
| 1522 | // TODO(andydavis) Support more generic multi-output src loop nests |
| 1523 | // fusion. |
| 1524 | auto srcStoreOp = mdg->getUniqueOutgoingStore(srcNode); |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1525 | if (!srcStoreOp) { |
| 1526 | // Get the src store op at the deepest loop depth. |
| 1527 | // We will use 'LoopFusionUtils::canFuseLoops' to check fusion |
| 1528 | // feasibility for loops with multiple stores. |
| 1529 | unsigned maxLoopDepth = 0; |
| 1530 | for (auto *op : srcNode->stores) { |
| 1531 | auto storeOp = cast<AffineStoreOp>(op); |
| 1532 | if (storeOp.getMemRef() != memref) { |
| 1533 | srcStoreOp = nullptr; |
| 1534 | break; |
| 1535 | } |
| 1536 | unsigned loopDepth = getNestingDepth(*storeOp); |
| 1537 | if (loopDepth > maxLoopDepth) { |
| 1538 | maxLoopDepth = loopDepth; |
| 1539 | srcStoreOp = storeOp; |
| 1540 | } |
| 1541 | } |
| 1542 | if (!srcStoreOp) |
| 1543 | continue; |
| 1544 | } |
| 1545 | |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1546 | // Unique outgoing store found must write to 'memref' since 'memref' |
| 1547 | // is the one that established the producer-consumer relationship |
| 1548 | // between 'srcNode' and 'dstNode'. |
| 1549 | assert(srcStoreOp.getMemRef() == memref && |
| 1550 | "Found store to unexpected memref"); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1551 | |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1552 | // Skip if 'srcNode' writes to any live in or escaping memrefs, |
| 1553 | // and cannot be fused. |
| 1554 | bool writesToLiveInOrOut = |
| 1555 | mdg->writesToLiveInOrEscapingMemrefs(srcNode->id); |
| 1556 | if (writesToLiveInOrOut && |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1557 | !canFuseSrcWhichWritesToLiveOut(srcId, dstId, srcStoreOp, mdg)) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1558 | continue; |
| 1559 | |
Kazuaki Ishizaki | 84a6182 | 2019-12-06 13:58:59 | [diff] [blame] | 1560 | // Don't create a private memref if 'writesToLiveInOrOut'. |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1561 | bool createPrivateMemref = !writesToLiveInOrOut; |
Kazuaki Ishizaki | 84a6182 | 2019-12-06 13:58:59 | [diff] [blame] | 1562 | // Don't create a private memref if 'srcNode' has in edges on |
| 1563 | // 'memref', or if 'dstNode' has out edges on 'memref'. |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1564 | if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) > 0 || |
| 1565 | mdg->getOutEdgeCount(dstNode->id, memref) > 0) { |
| 1566 | createPrivateMemref = false; |
| 1567 | } |
| 1568 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1569 | // Skip if 'srcNode' out edge count on 'memref' > 'maxSrcUserCount'. |
| 1570 | if (mdg->getOutEdgeCount(srcNode->id, memref) > maxSrcUserCount) |
| 1571 | continue; |
| 1572 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1573 | // Compute an operation list insertion point for the fused loop |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1574 | // nest which preserves dependences. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1575 | Operation *insertPointInst = |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1576 | mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1577 | if (insertPointInst == nullptr) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1578 | continue; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1579 | |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1580 | // Compute the innermost common loop depth for dstNode loads/stores. |
| 1581 | SmallVector<Operation *, 2> dstOps(dstNode->loads.begin(), |
| 1582 | dstNode->loads.end()); |
| 1583 | dstOps.append(dstNode->stores.begin(), dstNode->stores.end()); |
| 1584 | unsigned dstLoopDepthTest = getInnermostCommonLoopDepth(dstOps); |
| 1585 | // Check the feasibility of fusing src loop nest into dst loop nest |
| 1586 | // at loop depths in range [1, dstLoopDepthTest]. |
| 1587 | // TODO(andydavis) Use slice union computation and union of memref |
| 1588 | // read/write regions to cost model and fusion. |
| 1589 | bool canFuse = false; |
| 1590 | for (unsigned i = 1; i <= dstLoopDepthTest; ++i) { |
| 1591 | ComputationSliceState sliceUnion; |
| 1592 | FusionResult result = mlir::canFuseLoops( |
| 1593 | cast<AffineForOp>(srcNode->op), cast<AffineForOp>(dstNode->op), |
| 1594 | /*dstLoopDepth=*/i, &sliceUnion); |
| 1595 | if (result.value == FusionResult::Success) |
| 1596 | canFuse = true; |
| 1597 | } |
| 1598 | |
| 1599 | // Skip if fusion is not feasible at all loop depths. |
| 1600 | if (!canFuse) |
| 1601 | continue; |
| 1602 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1603 | // Gather 'dstNode' store ops to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1604 | SmallVector<Operation *, 2> dstStoreOpInsts; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1605 | for (auto *storeOpInst : dstNode->stores) |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 1606 | if (cast<AffineStoreOp>(storeOpInst).getMemRef() == memref) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1607 | dstStoreOpInsts.push_back(storeOpInst); |
| 1608 | |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1609 | unsigned bestDstLoopDepth; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1610 | mlir::ComputationSliceState sliceState; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1611 | // Check if fusion would be profitable. |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1612 | if (!isFusionProfitable(srcStoreOp, srcStoreOp, dstLoadOpInsts, |
| 1613 | dstStoreOpInsts, &sliceState, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1614 | &bestDstLoopDepth, maximalFusion)) |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1615 | continue; |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1616 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1617 | // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'. |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1618 | auto sliceLoopNest = mlir::insertBackwardComputationSlice( |
Diego Caballero | 3451055 | 2019-10-09 17:36:54 | [diff] [blame] | 1619 | srcStoreOp, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState); |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1620 | if (sliceLoopNest) { |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 1621 | LLVM_DEBUG(llvm::dbgs() << "\tslice loop nest:\n" |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1622 | << *sliceLoopNest.getOperation() << "\n"); |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1623 | // Move 'dstAffineForOp' before 'insertPointInst' if needed. |
River Riddle | adca3c2 | 2019-05-12 00:57:32 | [diff] [blame] | 1624 | auto dstAffineForOp = cast<AffineForOp>(dstNode->op); |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1625 | if (insertPointInst != dstAffineForOp.getOperation()) { |
| 1626 | dstAffineForOp.getOperation()->moveBefore(insertPointInst); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1627 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1628 | // Update edges between 'srcNode' and 'dstNode'. |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1629 | mdg->updateEdges(srcNode->id, dstNode->id, memref, |
| 1630 | createPrivateMemref); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1631 | |
| 1632 | // Collect slice loop stats. |
| 1633 | LoopNestStateCollector sliceCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1634 | sliceCollector.collect(sliceLoopNest.getOperation()); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1635 | // Promote single iteration slice loops to single IV value. |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1636 | for (auto forOp : sliceCollector.forOps) { |
| 1637 | promoteIfSingleIteration(forOp); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1638 | } |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1639 | if (createPrivateMemref) { |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1640 | // Create private memref for 'memref' in 'dstAffineForOp'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1641 | SmallVector<Operation *, 4> storesForMemref; |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1642 | for (auto *storeOpInst : sliceCollector.storeOpInsts) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 1643 | if (cast<AffineStoreOp>(storeOpInst).getMemRef() == memref) |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1644 | storesForMemref.push_back(storeOpInst); |
| 1645 | } |
Andy Davis | 68a8da4 | 2019-11-18 19:20:03 | [diff] [blame] | 1646 | // TODO(andydavis) Use union of memref write regions to compute |
| 1647 | // private memref footprint. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1648 | auto newMemRef = createPrivateMemRef( |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1649 | dstAffineForOp, storesForMemref[0], bestDstLoopDepth, |
| 1650 | fastMemorySpace, localBufSizeThreshold); |
| 1651 | visitedMemrefs.insert(newMemRef); |
| 1652 | // Create new node in dependence graph for 'newMemRef' alloc op. |
| 1653 | unsigned newMemRefNodeId = |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1654 | mdg->addNode(newMemRef->getDefiningOp()); |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1655 | // Add edge from 'newMemRef' node to dstNode. |
| 1656 | mdg->addEdge(newMemRefNodeId, dstId, newMemRef); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1657 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1658 | |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 1659 | // Collect dst loop stats after memref privatization transformation. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1660 | LoopNestStateCollector dstLoopCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1661 | dstLoopCollector.collect(dstAffineForOp.getOperation()); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1662 | |
| 1663 | // Add new load ops to current Node load op list 'loads' to |
| 1664 | // continue fusing based on new operands. |
| 1665 | for (auto *loadOpInst : dstLoopCollector.loadOpInsts) { |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1666 | auto loadMemRef = cast<AffineLoadOp>(loadOpInst).getMemRef(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1667 | if (visitedMemrefs.count(loadMemRef) == 0) |
| 1668 | loads.push_back(loadOpInst); |
| 1669 | } |
| 1670 | |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1671 | // Clear and add back loads and stores. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1672 | mdg->clearNodeLoadAndStores(dstNode->id); |
| 1673 | mdg->addToNode(dstId, dstLoopCollector.loadOpInsts, |
| 1674 | dstLoopCollector.storeOpInsts); |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 1675 | // Remove old src loop nest if it no longer has outgoing dependence |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1676 | // edges, and if it does not write to a memref which escapes the |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1677 | // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has |
| 1678 | // been fused into 'dstNode' and write region of 'dstNode' covers |
| 1679 | // the write region of 'srcNode', and 'srcNode' has no other users |
| 1680 | // so it is safe to remove. |
| 1681 | if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) { |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1682 | mdg->removeNode(srcNode->id); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1683 | srcNode->op->erase(); |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1684 | } else { |
| 1685 | // Add remaining users of 'oldMemRef' back on the worklist (if not |
| 1686 | // already there), as its replacement with a local/private memref |
| 1687 | // has reduced dependences on 'oldMemRef' which may have created |
| 1688 | // new fusion opportunities. |
| 1689 | if (mdg->outEdges.count(srcNode->id) > 0) { |
| 1690 | SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges = |
| 1691 | mdg->outEdges[srcNode->id]; |
| 1692 | for (auto &outEdge : oldOutEdges) { |
| 1693 | if (outEdge.value == memref && |
| 1694 | worklistSet.count(outEdge.id) == 0) { |
| 1695 | worklist.push_back(outEdge.id); |
| 1696 | worklistSet.insert(outEdge.id); |
| 1697 | } |
| 1698 | } |
| 1699 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1700 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1701 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1702 | } |
| 1703 | } |
| 1704 | } |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1705 | } |
| 1706 | |
| 1707 | // Visits each node in the graph, and for each node, attempts to fuse it with |
| 1708 | // its sibling nodes (nodes which share a parent, but no dependence edges). |
| 1709 | void fuseSiblingNodes() { |
| 1710 | init(); |
| 1711 | while (!worklist.empty()) { |
| 1712 | unsigned dstId = worklist.back(); |
| 1713 | worklist.pop_back(); |
| 1714 | worklistSet.erase(dstId); |
| 1715 | |
| 1716 | // Skip if this node was removed (fused into another node). |
| 1717 | if (mdg->nodes.count(dstId) == 0) |
| 1718 | continue; |
| 1719 | // Get 'dstNode' into which to attempt fusion. |
| 1720 | auto *dstNode = mdg->getNode(dstId); |
| 1721 | // Skip if 'dstNode' is not a loop nest. |
River Riddle | d5b60ee8 | 2019-05-12 01:59:54 | [diff] [blame] | 1722 | if (!isa<AffineForOp>(dstNode->op)) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1723 | continue; |
| 1724 | // Attempt to fuse 'dstNode' with its sibling nodes in the graph. |
| 1725 | fuseWithSiblingNodes(dstNode); |
| 1726 | } |
| 1727 | } |
| 1728 | |
| 1729 | // Attempt to fuse 'dstNode' with sibling nodes in the graph. |
| 1730 | void fuseWithSiblingNodes(Node *dstNode) { |
| 1731 | DenseSet<unsigned> visitedSibNodeIds; |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1732 | std::pair<unsigned, ValuePtr> idAndMemref; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1733 | while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) { |
| 1734 | unsigned sibId = idAndMemref.first; |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1735 | ValuePtr memref = idAndMemref.second; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1736 | // TODO(andydavis) Check that 'sibStoreOpInst' post-dominates all other |
| 1737 | // stores to the same memref in 'sibNode' loop nest. |
| 1738 | auto *sibNode = mdg->getNode(sibId); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1739 | // Compute an operation list insertion point for the fused loop |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1740 | // nest which preserves dependences. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1741 | assert(sibNode->op->getBlock() == dstNode->op->getBlock()); |
| 1742 | Operation *insertPointInst = |
| 1743 | sibNode->op->isBeforeInBlock(dstNode->op) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1744 | ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id) |
| 1745 | : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id); |
| 1746 | if (insertPointInst == nullptr) |
| 1747 | continue; |
| 1748 | |
| 1749 | // Check if fusion would be profitable and at what depth. |
| 1750 | |
| 1751 | // Get unique 'sibNode' load op to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1752 | SmallVector<Operation *, 2> sibLoadOpInsts; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1753 | sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts); |
| 1754 | // Currently findSiblingNodeToFuse searches for siblings with one load. |
| 1755 | assert(sibLoadOpInsts.size() == 1); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1756 | Operation *sibLoadOpInst = sibLoadOpInsts[0]; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1757 | assert(!sibNode->stores.empty()); |
| 1758 | // TODO(andydavis) Choose the store which postdominates all other stores. |
| 1759 | auto *sibStoreOpInst = sibNode->stores.back(); |
| 1760 | |
| 1761 | // Gather 'dstNode' load ops to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1762 | SmallVector<Operation *, 2> dstLoadOpInsts; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1763 | dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts); |
| 1764 | |
| 1765 | // Gather 'dstNode' store ops to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1766 | SmallVector<Operation *, 2> dstStoreOpInsts; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1767 | dstNode->getStoreOpsForMemref(memref, &dstStoreOpInsts); |
| 1768 | |
| 1769 | unsigned bestDstLoopDepth; |
| 1770 | mlir::ComputationSliceState sliceState; |
| 1771 | |
| 1772 | // Check if fusion would be profitable. |
| 1773 | if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstLoadOpInsts, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1774 | dstStoreOpInsts, &sliceState, &bestDstLoopDepth, |
| 1775 | maximalFusion)) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1776 | continue; |
| 1777 | |
| 1778 | // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'. |
| 1779 | auto sliceLoopNest = mlir::insertBackwardComputationSlice( |
| 1780 | sibLoadOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState); |
| 1781 | if (sliceLoopNest != nullptr) { |
River Riddle | adca3c2 | 2019-05-12 00:57:32 | [diff] [blame] | 1782 | auto dstForInst = cast<AffineForOp>(dstNode->op); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1783 | // Update operation position of fused loop nest (if needed). |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1784 | if (insertPointInst != dstForInst.getOperation()) { |
| 1785 | dstForInst.getOperation()->moveBefore(insertPointInst); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1786 | } |
| 1787 | // Update data dependence graph state post fusion. |
| 1788 | updateStateAfterSiblingFusion(sliceLoopNest, sibNode, dstNode); |
| 1789 | } |
| 1790 | } |
| 1791 | } |
| 1792 | |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1793 | // Searches function argument uses and the graph from 'dstNode' looking for a |
| 1794 | // fusion candidate sibling node which shares no dependences with 'dstNode' |
| 1795 | // but which loads from the same memref. Returns true and sets |
| 1796 | // 'idAndMemrefToFuse' on success. Returns false otherwise. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1797 | bool findSiblingNodeToFuse(Node *dstNode, |
| 1798 | DenseSet<unsigned> *visitedSibNodeIds, |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1799 | std::pair<unsigned, ValuePtr> *idAndMemrefToFuse) { |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1800 | // Returns true if 'sibNode' can be fused with 'dstNode' for input reuse |
| 1801 | // on 'memref'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1802 | auto canFuseWithSibNode = [&](Node *sibNode, ValuePtr memref) { |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1803 | // Skip if 'outEdge' is not a read-after-write dependence. |
| 1804 | // TODO(andydavis) Remove restrict to single load op restriction. |
| 1805 | if (sibNode->getLoadOpCount(memref) != 1) |
| 1806 | return false; |
| 1807 | // Skip if there exists a path of dependent edges between |
| 1808 | // 'sibNode' and 'dstNode'. |
| 1809 | if (mdg->hasDependencePath(sibNode->id, dstNode->id) || |
| 1810 | mdg->hasDependencePath(dstNode->id, sibNode->id)) |
| 1811 | return false; |
| 1812 | // Skip sib node if it loads to (and stores from) the same memref on |
| 1813 | // which it also has an input dependence edge. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1814 | DenseSet<ValuePtr> loadAndStoreMemrefSet; |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1815 | sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet); |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1816 | if (llvm::any_of(loadAndStoreMemrefSet, [=](ValuePtr memref) { |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1817 | return mdg->getIncomingMemRefAccesses(sibNode->id, memref) > 0; |
| 1818 | })) |
| 1819 | return false; |
| 1820 | |
| 1821 | // Check that all stores are to the same memref. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1822 | DenseSet<ValuePtr> storeMemrefs; |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1823 | for (auto *storeOpInst : sibNode->stores) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 1824 | storeMemrefs.insert(cast<AffineStoreOp>(storeOpInst).getMemRef()); |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1825 | } |
| 1826 | if (storeMemrefs.size() != 1) |
| 1827 | return false; |
| 1828 | return true; |
| 1829 | }; |
| 1830 | |
| 1831 | // Search for siblings which load the same memref function argument. |
River Riddle | ce502af | 2019-07-08 18:20:26 | [diff] [blame] | 1832 | auto fn = dstNode->op->getParentOfType<FuncOp>(); |
River Riddle | 54cd6a7 | 2019-07-01 17:29:09 | [diff] [blame] | 1833 | for (unsigned i = 0, e = fn.getNumArguments(); i != e; ++i) { |
| 1834 | for (auto *user : fn.getArgument(i)->getUsers()) { |
Andy Davis | 2e1187d | 2019-07-03 17:35:03 | [diff] [blame] | 1835 | if (auto loadOp = dyn_cast<AffineLoadOp>(user)) { |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1836 | // Gather loops surrounding 'use'. |
| 1837 | SmallVector<AffineForOp, 4> loops; |
River Riddle | 8780d8d | 2019-05-18 18:09:07 | [diff] [blame] | 1838 | getLoopIVs(*user, &loops); |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1839 | // Skip 'use' if it is not within a loop nest. |
| 1840 | if (loops.empty()) |
| 1841 | continue; |
| 1842 | Node *sibNode = mdg->getForOpNode(loops[0]); |
| 1843 | assert(sibNode != nullptr); |
| 1844 | // Skip 'use' if it not a sibling to 'dstNode'. |
| 1845 | if (sibNode->id == dstNode->id) |
| 1846 | continue; |
| 1847 | // Skip 'use' if it has been visited. |
| 1848 | if (visitedSibNodeIds->count(sibNode->id) > 0) |
| 1849 | continue; |
| 1850 | // Skip 'use' if it does not load from the same memref as 'dstNode'. |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1851 | auto memref = loadOp.getMemRef(); |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1852 | if (dstNode->getLoadOpCount(memref) == 0) |
| 1853 | continue; |
| 1854 | // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'. |
| 1855 | if (canFuseWithSibNode(sibNode, memref)) { |
| 1856 | visitedSibNodeIds->insert(sibNode->id); |
| 1857 | idAndMemrefToFuse->first = sibNode->id; |
| 1858 | idAndMemrefToFuse->second = memref; |
| 1859 | return true; |
| 1860 | } |
| 1861 | } |
| 1862 | } |
| 1863 | } |
| 1864 | |
| 1865 | // Search for siblings by following edges through an intermediate src node. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1866 | // Collect candidate 'dstNode' input edges in 'inEdges'. |
| 1867 | SmallVector<MemRefDependenceGraph::Edge, 2> inEdges; |
| 1868 | mdg->forEachMemRefInputEdge( |
| 1869 | dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) { |
| 1870 | // Add 'inEdge' if it is a read-after-write dependence. |
| 1871 | if (dstNode->getLoadOpCount(inEdge.value) > 0 && |
| 1872 | mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0) |
| 1873 | inEdges.push_back(inEdge); |
| 1874 | }); |
| 1875 | |
| 1876 | // Search for sibling nodes to fuse by visiting output edges from each input |
| 1877 | // edge in 'inEdges'. |
| 1878 | for (auto &inEdge : inEdges) { |
| 1879 | // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'. |
| 1880 | SmallVector<MemRefDependenceGraph::Edge, 2> outEdges; |
| 1881 | mdg->forEachMemRefOutputEdge( |
| 1882 | inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) { |
| 1883 | unsigned sibNodeId = outEdge.id; |
| 1884 | if (visitedSibNodeIds->count(sibNodeId) > 0) |
| 1885 | return; |
| 1886 | // Skip output edge if not a sibling using the same memref. |
| 1887 | if (outEdge.id == dstNode->id || outEdge.value != inEdge.value) |
| 1888 | return; |
| 1889 | auto *sibNode = mdg->getNode(sibNodeId); |
River Riddle | d5b60ee8 | 2019-05-12 01:59:54 | [diff] [blame] | 1890 | if (!isa<AffineForOp>(sibNode->op)) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1891 | return; |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 1892 | // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'. |
| 1893 | if (canFuseWithSibNode(sibNode, outEdge.value)) { |
| 1894 | // Add candidate 'outEdge' to sibling node. |
| 1895 | outEdges.push_back(outEdge); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1896 | } |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1897 | }); |
| 1898 | |
| 1899 | // Add first candidate if any were returned. |
| 1900 | if (!outEdges.empty()) { |
| 1901 | visitedSibNodeIds->insert(outEdges[0].id); |
| 1902 | idAndMemrefToFuse->first = outEdges[0].id; |
| 1903 | idAndMemrefToFuse->second = outEdges[0].value; |
| 1904 | return true; |
| 1905 | } |
| 1906 | } |
| 1907 | return false; |
| 1908 | } |
| 1909 | |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1910 | void updateStateAfterSiblingFusion(AffineForOp sliceLoopNest, Node *sibNode, |
| 1911 | Node *dstNode) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1912 | // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion. |
| 1913 | mdg->updateEdges(sibNode->id, dstNode->id); |
| 1914 | |
| 1915 | // Collect slice loop stats. |
| 1916 | LoopNestStateCollector sliceCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1917 | sliceCollector.collect(sliceLoopNest.getOperation()); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1918 | // Promote single iteration slice loops to single IV value. |
| 1919 | for (auto forOp : sliceCollector.forOps) { |
| 1920 | promoteIfSingleIteration(forOp); |
| 1921 | } |
| 1922 | |
Kazuaki Ishizaki | 8bfedb3 | 2019-10-20 07:11:03 | [diff] [blame] | 1923 | // Collect dst loop stats after memref privatization transformation. |
River Riddle | adca3c2 | 2019-05-12 00:57:32 | [diff] [blame] | 1924 | auto dstForInst = cast<AffineForOp>(dstNode->op); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1925 | LoopNestStateCollector dstLoopCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1926 | dstLoopCollector.collect(dstForInst.getOperation()); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1927 | // Clear and add back loads and stores |
| 1928 | mdg->clearNodeLoadAndStores(dstNode->id); |
| 1929 | mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts, |
| 1930 | dstLoopCollector.storeOpInsts); |
| 1931 | // Remove old sibling loop nest if it no longer has outgoing dependence |
| 1932 | // edges, and it does not write to a memref which escapes the |
| 1933 | // function. |
| 1934 | if (mdg->getOutEdgeCount(sibNode->id) == 0) { |
| 1935 | mdg->removeNode(sibNode->id); |
River Riddle | adca3c2 | 2019-05-12 00:57:32 | [diff] [blame] | 1936 | sibNode->op->erase(); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1937 | } |
| 1938 | } |
| 1939 | |
| 1940 | // Clean up any allocs with no users. |
| 1941 | void eraseUnusedMemRefAllocations() { |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1942 | for (auto &pair : mdg->memrefEdgeCount) { |
| 1943 | if (pair.second > 0) |
| 1944 | continue; |
River Riddle | 35807bc | 2019-12-23 05:59:55 | [diff] [blame] | 1945 | auto memref = pair.first; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1946 | // Skip if there exist other uses (return operation or function calls). |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 1947 | if (!memref->use_empty()) |
| 1948 | continue; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1949 | // Use list expected to match the dep graph info. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1950 | auto *op = memref->getDefiningOp(); |
River Riddle | 1423acc | 2019-04-23 21:38:26 | [diff] [blame] | 1951 | if (isa_and_nonnull<AllocOp>(op)) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1952 | op->erase(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1953 | } |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1954 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1955 | }; |
| 1956 | |
| 1957 | } // end anonymous namespace |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1958 | |
River Riddle | ed5fe20 | 2019-02-28 22:50:42 | [diff] [blame] | 1959 | void LoopFusion::runOnFunction() { |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 1960 | // Override if a command line argument was provided. |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 1961 | if (clFusionFastMemorySpace.getNumOccurrences() > 0) { |
| 1962 | fastMemorySpace = clFusionFastMemorySpace.getValue(); |
| 1963 | } |
| 1964 | |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 1965 | // Override if a command line argument was provided. |
| 1966 | if (clFusionLocalBufThreshold.getNumOccurrences() > 0) { |
| 1967 | localBufSizeThreshold = clFusionLocalBufThreshold * 1024; |
| 1968 | } |
| 1969 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1970 | if (clMaximalLoopFusion.getNumOccurrences() > 0) |
| 1971 | maximalFusion = clMaximalLoopFusion; |
| 1972 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1973 | MemRefDependenceGraph g; |
Uday Bondhugula | 02af8c2 | 2019-03-05 23:05:34 | [diff] [blame] | 1974 | if (g.init(getFunction())) |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1975 | GreedyFusion(&g, localBufSizeThreshold, fastMemorySpace, maximalFusion) |
| 1976 | .run(); |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1977 | } |
Jacques Pienaar | 6f0fb22 | 2018-11-07 02:34:18 | [diff] [blame] | 1978 | |
Nicolas Vasilache | 258e8d9 | 2019-05-03 18:07:37 | [diff] [blame] | 1979 | static PassRegistration<LoopFusion> pass("affine-loop-fusion", |
| 1980 | "Fuse loop nests"); |