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