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