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