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