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