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