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