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