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) { 445 if (lastDstDepPos) { 446 if (firstSrcDepPos.value() <= lastDstDepPos.value()) { 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.value()]; 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) { 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.value(); 946 unsigned newMemSpace; 947 if (bufSize <= localBufSizeThreshold && fastMemorySpace.has_value()) { 948 newMemSpace = fastMemorySpace.value(); 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.has_value()) 1145 return false; 1146 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.value(); 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.has_value() || 1187 *maybeSliceWriteRegionSizeBytes == 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 = maybeSliceWriteRegionSizeBytes.value(); 1194 1195 // If we are fusing for reuse, check that write regions remain the same. 1196 // TODO: Write region check should check sizes and offsets in 1197 // each dimension, so that we are sure they are covering the same memref 1198 // region. Also, move this out to a isMemRefRegionSuperSet helper function. 1199 if (srcOpInst != srcStoreOpInst && 1200 sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes) 1201 continue; 1202 1203 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) / 1204 static_cast<double>(sliceWriteRegionSizeBytes); 1205 1206 LLVM_DEBUG({ 1207 std::stringstream msg; 1208 msg << " evaluating fusion profitability at depth : " << i << "\n" 1209 << std::fixed << std::setprecision(2) 1210 << " additional compute fraction: " 1211 << 100.0 * additionalComputeFraction << "%\n" 1212 << " storage reduction factor: " << storageReduction << "x\n" 1213 << " fused nest cost: " << fusedLoopNestComputeCost << "\n" 1214 << " src write region size: " << srcWriteRegionSizeBytes << "\n" 1215 << " slice write region size: " << sliceWriteRegionSizeBytes 1216 << "\n"; 1217 llvm::dbgs() << msg.str(); 1218 }); 1219 1220 // TODO: This is a placeholder cost model. 1221 // Among all choices that add an acceptable amount of redundant computation 1222 // (as per computeToleranceThreshold), we will simply pick the one that 1223 // reduces the intermediary size the most. 1224 if ((storageReduction > maxStorageReduction) && 1225 (additionalComputeFraction < computeToleranceThreshold)) { 1226 maxStorageReduction = storageReduction; 1227 bestDstLoopDepth = i; 1228 minFusedLoopNestComputeCost = fusedLoopNestComputeCost; 1229 sliceMemEstimate = sliceWriteRegionSizeBytes; 1230 } 1231 } 1232 1233 // A simple cost model: fuse if it reduces the memory footprint. 1234 1235 if (!bestDstLoopDepth) { 1236 LLVM_DEBUG( 1237 llvm::dbgs() 1238 << "All fusion choices involve more than the threshold amount of " 1239 "redundant computation; NOT fusing.\n"); 1240 return false; 1241 } 1242 1243 if (!bestDstLoopDepth) { 1244 LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n"); 1245 return false; 1246 } 1247 1248 // Set dstLoopDepth based on best values from search. 1249 *dstLoopDepth = *bestDstLoopDepth; 1250 1251 LLVM_DEBUG( 1252 llvm::dbgs() << " LoopFusion fusion stats:" 1253 << "\n best loop depth: " << bestDstLoopDepth 1254 << "\n src loop nest compute cost: " << srcLoopNestCost 1255 << "\n dst loop nest compute cost: " << dstLoopNestCost 1256 << "\n fused loop nest compute cost: " 1257 << minFusedLoopNestComputeCost << "\n"); 1258 1259 auto dstMemSize = getMemoryFootprintBytes(dstForOp); 1260 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]); 1261 1262 Optional<double> storageReduction = None; 1263 1264 if (!dstMemSize || !srcMemSize) { 1265 LLVM_DEBUG(llvm::dbgs() 1266 << " fusion memory benefit cannot be evaluated; NOT fusing.\n"); 1267 return false; 1268 } 1269 1270 auto srcMemSizeVal = srcMemSize.value(); 1271 auto dstMemSizeVal = dstMemSize.value(); 1272 1273 assert(sliceMemEstimate && "expected value"); 1274 auto fusedMem = dstMemSizeVal + sliceMemEstimate.value(); 1275 1276 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n" 1277 << " dst mem: " << dstMemSizeVal << "\n" 1278 << " fused mem: " << fusedMem << "\n" 1279 << " slice mem: " << sliceMemEstimate << "\n"); 1280 1281 if (static_cast<long>(fusedMem) > srcMemSizeVal + dstMemSizeVal) { 1282 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n"); 1283 return false; 1284 } 1285 storageReduction = 1286 100.0 * 1287 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal)); 1288 1289 double additionalComputeFraction = 1290 100.0 * (minFusedLoopNestComputeCost / 1291 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) - 1292 1); 1293 (void)additionalComputeFraction; 1294 LLVM_DEBUG({ 1295 std::stringstream msg; 1296 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with " 1297 << std::setprecision(2) << additionalComputeFraction 1298 << "% redundant computation and a "; 1299 msg << (storageReduction ? std::to_string(*storageReduction) : "<unknown>"); 1300 msg << "% storage reduction.\n"; 1301 llvm::dbgs() << msg.str(); 1302 }); 1303 1304 return true; 1305 } 1306 1307 namespace { 1308 1309 // GreedyFusion greedily fuses loop nests which have a producer/consumer or 1310 // input-reuse relationship on a memref, with the goal of improving locality. 1311 // 1312 // The steps of the producer-consumer fusion algorithm are as follows: 1313 // 1314 // *) A worklist is initialized with node ids from the dependence graph. 1315 // *) For each node id in the worklist: 1316 // *) Pop an AffineForOp of the worklist. This 'dstAffineForOp' will be a 1317 // candidate destination AffineForOp into which fusion will be attempted. 1318 // *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'. 1319 // *) For each LoadOp in 'dstLoadOps' do: 1320 // *) Look up dependent loop nests which have a single store op to the same 1321 // memref. 1322 // *) Check if dependences would be violated by the fusion. 1323 // *) Get a computation slice of 'srcLoopNest', which adjusts its loop 1324 // bounds to be functions of 'dstLoopNest' IVs and symbols. 1325 // *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest', 1326 // at a loop depth determined by the cost model in 'isFusionProfitable'. 1327 // *) Add the newly fused load/store operations to the state, 1328 // and also add newly fused load ops to 'dstLoopOps' to be considered 1329 // as fusion dst load ops in another iteration. 1330 // *) Remove old src loop nest and its associated state. 1331 // 1332 // The steps of the input-reuse fusion algorithm are as follows: 1333 // 1334 // *) Initialize 'worklist' with node ids from the dependence graph. 1335 // *) For each 'dstNode' in the worklist: 1336 // *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which 1337 // loads from the same memref, but which has no dependence paths to/from. 1338 // *) Get a computation slice of 'sibLoopNest', which adjusts its loop 1339 // bounds to be functions of 'dstLoopNest' IVs and symbols. 1340 // *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest', 1341 // at a loop depth determined by the cost model in 'isFusionProfitable'. 1342 // This function also checks that the memref write region of 'sibLoopNest', 1343 // is preserved in the fused loop nest. 1344 // *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'. 1345 // 1346 // Given a graph where top-level operations are vertices in the set 'V' and 1347 // edges in the set 'E' are dependences between vertices, this algorithm 1348 // takes O(V) time for initialization, and has runtime O(V + E). 1349 // 1350 // This greedy algorithm is not 'maximal' due to the current restriction of 1351 // fusing along single producer consumer edges, but there is a TODO: to fix 1352 // this. 1353 // 1354 // TODO: Experiment with other fusion policies. 1355 struct GreedyFusion { 1356 public: 1357 // The data dependence graph to traverse during fusion. 1358 MemRefDependenceGraph *mdg; 1359 // Worklist of graph nodes visited during the fusion pass. 1360 SmallVector<unsigned, 8> worklist; 1361 // Parameter for local buffer size threshold. 1362 unsigned localBufSizeThreshold; 1363 // Parameter for fast memory space. 1364 Optional<unsigned> fastMemorySpace; 1365 // If true, ignore any additional (redundant) computation tolerance threshold 1366 // that would have prevented fusion. 1367 bool maximalFusion; 1368 // The amount of additional computation that is tolerated while fusing 1369 // pair-wise as a fraction of the total computation. 1370 double computeToleranceThreshold; 1371 1372 using Node = MemRefDependenceGraph::Node; 1373 1374 GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold, 1375 Optional<unsigned> fastMemorySpace, bool maximalFusion, 1376 double computeToleranceThreshold) 1377 : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold), 1378 fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion), 1379 computeToleranceThreshold(computeToleranceThreshold) {} 1380 1381 /// Initializes 'worklist' with nodes from 'mdg'. 1382 void init() { 1383 // TODO: Add a priority queue for prioritizing nodes by different 1384 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio). 1385 worklist.clear(); 1386 for (auto &idAndNode : mdg->nodes) { 1387 const Node &node = idAndNode.second; 1388 worklist.push_back(node.id); 1389 } 1390 } 1391 /// Run only sibling fusion on the `mdg`. 1392 void runSiblingFusionOnly() { 1393 fuseSiblingNodes(); 1394 eraseUnusedMemRefAllocations(); 1395 } 1396 1397 /// Run only producer/consumer fusion on the `mdg`. 1398 void runProducerConsumerFusionOnly() { 1399 fuseProducerConsumerNodes( 1400 /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max()); 1401 eraseUnusedMemRefAllocations(); 1402 } 1403 1404 // Run the GreedyFusion pass. 1405 // *) First pass through the nodes fuses single-use producer nodes into their 1406 // unique consumer. 1407 // *) Second pass fuses sibling nodes which share no dependence edges. 1408 // *) Third pass fuses any remaining producer nodes into their users. 1409 void runGreedyFusion() { 1410 // TODO: Run this repeatedly until a fixed-point is reached. 1411 fuseProducerConsumerNodes(/*maxSrcUserCount=*/1); 1412 fuseSiblingNodes(); 1413 fuseProducerConsumerNodes( 1414 /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max()); 1415 eraseUnusedMemRefAllocations(); 1416 } 1417 1418 void fuseProducerConsumerNodes(unsigned maxSrcUserCount) { 1419 LLVM_DEBUG(llvm::dbgs() << "--- Producer/Consumer Fusion ---\n"); 1420 init(); 1421 while (!worklist.empty()) { 1422 unsigned dstId = worklist.back(); 1423 worklist.pop_back(); 1424 1425 // Skip if this node was removed (fused into another node). 1426 if (mdg->nodes.count(dstId) == 0) 1427 continue; 1428 // Get 'dstNode' into which to attempt fusion. 1429 auto *dstNode = mdg->getNode(dstId); 1430 // Skip if 'dstNode' is not a loop nest. 1431 if (!isa<AffineForOp>(dstNode->op)) 1432 continue; 1433 // Skip if 'dstNode' is a loop nest returning values. 1434 // TODO: support loop nests that return values. 1435 if (dstNode->op->getNumResults() > 0) 1436 continue; 1437 1438 LLVM_DEBUG(llvm::dbgs() << "Evaluating dst loop " << dstId << "\n"); 1439 1440 // Sink sequential loops in 'dstNode' (and thus raise parallel loops) 1441 // while preserving relative order. This can increase the maximum loop 1442 // depth at which we can fuse a slice of a producer loop nest into a 1443 // consumer loop nest. 1444 sinkSequentialLoops(dstNode); 1445 auto dstAffineForOp = cast<AffineForOp>(dstNode->op); 1446 1447 // Try to fuse 'dstNode' with candidate producer loops until a fixed point 1448 // is reached. Fusing two loops may expose new fusion opportunities. 1449 bool dstNodeChanged; 1450 do { 1451 // Gather src loop candidates for 'dstNode' and visit them in "quasi" 1452 // reverse program order to minimize the number of iterations needed to 1453 // reach the fixed point. Note that this is a best effort approach since 1454 // 'getProducerCandidates' does not always guarantee that program order 1455 // in 'srcIdCandidates'. 1456 dstNodeChanged = false; 1457 SmallVector<unsigned, 16> srcIdCandidates; 1458 getProducerCandidates(dstId, mdg, srcIdCandidates); 1459 1460 for (unsigned srcId : llvm::reverse(srcIdCandidates)) { 1461 // Get 'srcNode' from which to attempt fusion into 'dstNode'. 1462 auto *srcNode = mdg->getNode(srcId); 1463 auto srcAffineForOp = cast<AffineForOp>(srcNode->op); 1464 LLVM_DEBUG(llvm::dbgs() << "Evaluating src loop " << srcId 1465 << " for dst loop " << dstId << "\n"); 1466 1467 // Skip if 'srcNode' is a loop nest returning values. 1468 // TODO: support loop nests that return values. 1469 if (isa<AffineForOp>(srcNode->op) && srcNode->op->getNumResults() > 0) 1470 continue; 1471 1472 DenseSet<Value> producerConsumerMemrefs; 1473 gatherProducerConsumerMemrefs(srcId, dstId, mdg, 1474 producerConsumerMemrefs); 1475 1476 // Skip if 'srcNode' out edge count on any memref is greater than 1477 // 'maxSrcUserCount'. 1478 if (any_of(producerConsumerMemrefs, [&](Value memref) { 1479 return mdg->getOutEdgeCount(srcNode->id, memref) > 1480 maxSrcUserCount; 1481 })) 1482 continue; 1483 1484 // Gather memrefs in 'srcNode' that are written and escape to the 1485 // function (e.g., memref function arguments, returned memrefs, 1486 // memrefs passed to function calls, etc.). 1487 DenseSet<Value> srcEscapingMemRefs; 1488 gatherEscapingMemrefs(srcNode->id, mdg, srcEscapingMemRefs); 1489 1490 // Skip if there are non-affine operations in between the 'srcNode' 1491 // and 'dstNode' using their memrefs. If so, we wouldn't be able to 1492 // compute a legal insertion point for now. 'srcNode' and 'dstNode' 1493 // memrefs with non-affine operation users would be considered 1494 // escaping memrefs so we can limit this check to only scenarios with 1495 // escaping memrefs. 1496 if (!srcEscapingMemRefs.empty() && 1497 hasNonAffineUsersOnThePath(srcId, dstId, mdg)) { 1498 LLVM_DEBUG( 1499 llvm::dbgs() 1500 << "Can't fuse: non-affine users in between the loops\n."); 1501 continue; 1502 } 1503 1504 // Compute an operation list insertion point for the fused loop 1505 // nest which preserves dependences. 1506 Operation *fusedLoopInsPoint = 1507 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id); 1508 if (fusedLoopInsPoint == nullptr) 1509 continue; 1510 1511 // Compute the innermost common loop depth for dstNode 1512 // producer-consumer loads/stores. 1513 SmallVector<Operation *, 2> dstMemrefOps; 1514 for (Operation *op : dstNode->loads) 1515 if (producerConsumerMemrefs.count( 1516 cast<AffineReadOpInterface>(op).getMemRef()) > 0) 1517 dstMemrefOps.push_back(op); 1518 for (Operation *op : dstNode->stores) 1519 if (producerConsumerMemrefs.count( 1520 cast<AffineWriteOpInterface>(op).getMemRef())) 1521 dstMemrefOps.push_back(op); 1522 unsigned dstLoopDepthTest = getInnermostCommonLoopDepth(dstMemrefOps); 1523 1524 // Check the feasibility of fusing src loop nest into dst loop nest 1525 // at loop depths in range [1, dstLoopDepthTest]. 1526 unsigned maxLegalFusionDepth = 0; 1527 SmallVector<ComputationSliceState, 8> depthSliceUnions; 1528 depthSliceUnions.resize(dstLoopDepthTest); 1529 FusionStrategy strategy(FusionStrategy::ProducerConsumer); 1530 for (unsigned i = 1; i <= dstLoopDepthTest; ++i) { 1531 FusionResult result = mlir::canFuseLoops( 1532 srcAffineForOp, dstAffineForOp, 1533 /*dstLoopDepth=*/i, &depthSliceUnions[i - 1], strategy); 1534 1535 if (result.value == FusionResult::Success) 1536 maxLegalFusionDepth = i; 1537 } 1538 1539 if (maxLegalFusionDepth == 0) { 1540 LLVM_DEBUG(llvm::dbgs() 1541 << "Can't fuse: fusion is not legal at any depth\n"); 1542 continue; 1543 } 1544 1545 // Check if fusion would be profitable. We skip profitability analysis 1546 // for maximal fusion since we already know the maximal legal depth to 1547 // fuse. 1548 unsigned bestDstLoopDepth = maxLegalFusionDepth; 1549 if (!maximalFusion) { 1550 // Retrieve producer stores from the src loop. 1551 SmallVector<Operation *, 2> producerStores; 1552 for (Operation *op : srcNode->stores) 1553 if (producerConsumerMemrefs.count( 1554 cast<AffineWriteOpInterface>(op).getMemRef())) 1555 producerStores.push_back(op); 1556 1557 // TODO: Suppport multiple producer stores in profitability 1558 // analysis. We limit profitability analysis to only scenarios with 1559 // a single producer store for now. Note that some multi-store 1560 // producer scenarios will still go through profitability analysis 1561 // if only one of the stores is involved the producer-consumer 1562 // relationship of the candidate loops. 1563 assert(!producerStores.empty() && "Expected producer store"); 1564 if (producerStores.size() > 1) 1565 LLVM_DEBUG(llvm::dbgs() << "Skipping profitability analysis. Not " 1566 "supported for this case\n"); 1567 else if (!isFusionProfitable(producerStores[0], producerStores[0], 1568 dstAffineForOp, depthSliceUnions, 1569 maxLegalFusionDepth, &bestDstLoopDepth, 1570 computeToleranceThreshold)) 1571 continue; 1572 } 1573 1574 assert(bestDstLoopDepth > 0 && "Unexpected loop fusion depth"); 1575 ComputationSliceState &bestSlice = 1576 depthSliceUnions[bestDstLoopDepth - 1]; 1577 assert(!bestSlice.isEmpty() && "Missing slice union for depth"); 1578 1579 // Determine if 'srcId' can be removed after fusion, taking into 1580 // account remaining dependences, escaping memrefs and the fusion 1581 // insertion point. 1582 bool removeSrcNode = canRemoveSrcNodeAfterFusion( 1583 srcId, dstId, bestSlice, fusedLoopInsPoint, srcEscapingMemRefs, 1584 mdg); 1585 1586 DenseSet<Value> privateMemrefs; 1587 for (Value memref : producerConsumerMemrefs) { 1588 // If `memref` is an escaping one, do not create a private memref 1589 // for the below scenarios, since doing so will leave the escaping 1590 // memref unmodified as all the writes originally meant for the 1591 // escaping memref would be performed on the private memref: 1592 // 1. The source is to be removed after fusion, 1593 // OR 1594 // 2. The destination writes to `memref`. 1595 if (srcEscapingMemRefs.count(memref) > 0 && 1596 (removeSrcNode || dstNode->getStoreOpCount(memref) > 0)) 1597 continue; 1598 1599 // Don't create a private memref if 'srcNode' has in edges on 1600 // 'memref' or 'dstNode' has out edges on 'memref'. 1601 if (mdg->getIncomingMemRefAccesses(srcId, memref) > 0 || 1602 mdg->getOutEdgeCount(dstId, memref) > 0) 1603 continue; 1604 1605 // If 'srcNode' will be removed but it has out edges on 'memref' to 1606 // nodes other than 'dstNode', we have to preserve dependences and 1607 // cannot create a private memref. 1608 if (removeSrcNode && 1609 any_of(mdg->outEdges[srcId], [&](const auto &edge) { 1610 return edge.value == memref && edge.id != dstId; 1611 })) 1612 continue; 1613 1614 // Create a private version of this memref. 1615 privateMemrefs.insert(memref); 1616 } 1617 1618 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'. 1619 fuseLoops(srcAffineForOp, dstAffineForOp, bestSlice); 1620 dstNodeChanged = true; 1621 1622 LLVM_DEBUG(llvm::dbgs() 1623 << "Fused src loop " << srcId << " into dst loop " << dstId 1624 << " at depth " << bestDstLoopDepth << ":\n" 1625 << dstAffineForOp << "\n"); 1626 1627 // Move 'dstAffineForOp' before 'insertPointInst' if needed. 1628 if (fusedLoopInsPoint != dstAffineForOp.getOperation()) 1629 dstAffineForOp.getOperation()->moveBefore(fusedLoopInsPoint); 1630 1631 // Update edges between 'srcNode' and 'dstNode'. 1632 mdg->updateEdges(srcNode->id, dstNode->id, privateMemrefs, 1633 removeSrcNode); 1634 1635 // Create private memrefs. 1636 if (!privateMemrefs.empty()) { 1637 // Gather stores for all the private-to-be memrefs. 1638 DenseMap<Value, SmallVector<Operation *, 4>> privateMemRefToStores; 1639 dstAffineForOp.walk([&](AffineWriteOpInterface storeOp) { 1640 Value storeMemRef = storeOp.getMemRef(); 1641 if (privateMemrefs.count(storeMemRef) > 0) 1642 privateMemRefToStores[storeMemRef].push_back( 1643 storeOp.getOperation()); 1644 }); 1645 1646 // Replace original memrefs with private memrefs. Note that all the 1647 // loads and stores on these memrefs will be replaced with a new 1648 // loads and stores. Any reference to the original ones becomes 1649 // invalid after this point. 1650 for (auto &memrefToStoresPair : privateMemRefToStores) { 1651 // TODO: Use union of memref write regions to compute 1652 // private memref footprint. 1653 SmallVector<Operation *, 4> &storesForMemref = 1654 memrefToStoresPair.second; 1655 Value newMemRef = createPrivateMemRef( 1656 dstAffineForOp, storesForMemref[0], bestDstLoopDepth, 1657 fastMemorySpace, localBufSizeThreshold); 1658 // Create new node in dependence graph for 'newMemRef' alloc op. 1659 unsigned newMemRefNodeId = 1660 mdg->addNode(newMemRef.getDefiningOp()); 1661 // Add edge from 'newMemRef' node to dstNode. 1662 mdg->addEdge(newMemRefNodeId, dstId, newMemRef); 1663 } 1664 // One or more entries for 'newMemRef' alloc op are inserted into 1665 // the DenseMap mdg->nodes. Since an insertion may cause DenseMap to 1666 // reallocate, update dstNode. 1667 dstNode = mdg->getNode(dstId); 1668 } 1669 1670 // Collect dst loop stats after memref privatization transformation. 1671 LoopNestStateCollector dstLoopCollector; 1672 dstLoopCollector.collect(dstAffineForOp.getOperation()); 1673 1674 // Clear and add back loads and stores. 1675 mdg->clearNodeLoadAndStores(dstNode->id); 1676 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts, 1677 dstLoopCollector.storeOpInsts); 1678 1679 if (removeSrcNode) { 1680 LLVM_DEBUG(llvm::dbgs() 1681 << "Removing src loop " << srcId << " after fusion\n"); 1682 // srcNode is no longer valid after it is removed from mdg. 1683 srcAffineForOp.erase(); 1684 mdg->removeNode(srcId); 1685 srcNode = nullptr; 1686 } 1687 } 1688 } while (dstNodeChanged); 1689 } 1690 } 1691 1692 // Visits each node in the graph, and for each node, attempts to fuse it with 1693 // its sibling nodes (nodes which share a parent, but no dependence edges). 1694 void fuseSiblingNodes() { 1695 LLVM_DEBUG(llvm::dbgs() << "--- Sibling Fusion ---\n"); 1696 init(); 1697 while (!worklist.empty()) { 1698 unsigned dstId = worklist.back(); 1699 worklist.pop_back(); 1700 1701 // Skip if this node was removed (fused into another node). 1702 if (mdg->nodes.count(dstId) == 0) 1703 continue; 1704 // Get 'dstNode' into which to attempt fusion. 1705 auto *dstNode = mdg->getNode(dstId); 1706 // Skip if 'dstNode' is not a loop nest. 1707 if (!isa<AffineForOp>(dstNode->op)) 1708 continue; 1709 // Attempt to fuse 'dstNode' with its sibling nodes in the graph. 1710 fuseWithSiblingNodes(dstNode); 1711 } 1712 } 1713 1714 // Attempt to fuse 'dstNode' with sibling nodes in the graph. 1715 void fuseWithSiblingNodes(Node *dstNode) { 1716 DenseSet<unsigned> visitedSibNodeIds; 1717 std::pair<unsigned, Value> idAndMemref; 1718 auto dstAffineForOp = cast<AffineForOp>(dstNode->op); 1719 1720 while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) { 1721 unsigned sibId = idAndMemref.first; 1722 Value memref = idAndMemref.second; 1723 // TODO: Check that 'sibStoreOpInst' post-dominates all other 1724 // stores to the same memref in 'sibNode' loop nest. 1725 auto *sibNode = mdg->getNode(sibId); 1726 // Compute an operation list insertion point for the fused loop 1727 // nest which preserves dependences. 1728 assert(sibNode->op->getBlock() == dstNode->op->getBlock()); 1729 Operation *insertPointInst = 1730 sibNode->op->isBeforeInBlock(dstNode->op) 1731 ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id) 1732 : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id); 1733 if (insertPointInst == nullptr) 1734 continue; 1735 1736 // Check if fusion would be profitable and at what depth. 1737 1738 // Get unique 'sibNode' load op to 'memref'. 1739 SmallVector<Operation *, 2> sibLoadOpInsts; 1740 sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts); 1741 // Currently findSiblingNodeToFuse searches for siblings with one load. 1742 assert(sibLoadOpInsts.size() == 1); 1743 Operation *sibLoadOpInst = sibLoadOpInsts[0]; 1744 assert(!sibNode->stores.empty()); 1745 // TODO: Choose the store which postdominates all other stores. 1746 auto *sibStoreOpInst = sibNode->stores.back(); 1747 1748 // Gather 'dstNode' load ops to 'memref'. 1749 SmallVector<Operation *, 2> dstLoadOpInsts; 1750 dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts); 1751 1752 SmallVector<AffineForOp, 4> dstLoopIVs; 1753 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs); 1754 unsigned dstLoopDepthTest = dstLoopIVs.size(); 1755 auto sibAffineForOp = cast<AffineForOp>(sibNode->op); 1756 1757 // Compute loop depth and slice union for fusion. 1758 SmallVector<ComputationSliceState, 8> depthSliceUnions; 1759 depthSliceUnions.resize(dstLoopDepthTest); 1760 unsigned maxLegalFusionDepth = 0; 1761 FusionStrategy strategy(memref); 1762 for (unsigned i = 1; i <= dstLoopDepthTest; ++i) { 1763 FusionResult result = mlir::canFuseLoops( 1764 sibAffineForOp, dstAffineForOp, 1765 /*dstLoopDepth=*/i, &depthSliceUnions[i - 1], strategy); 1766 1767 if (result.value == FusionResult::Success) 1768 maxLegalFusionDepth = i; 1769 } 1770 1771 // Skip if fusion is not feasible at any loop depths. 1772 if (maxLegalFusionDepth == 0) 1773 continue; 1774 1775 unsigned bestDstLoopDepth = maxLegalFusionDepth; 1776 if (!maximalFusion) { 1777 // Check if fusion would be profitable. 1778 if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstAffineForOp, 1779 depthSliceUnions, maxLegalFusionDepth, 1780 &bestDstLoopDepth, computeToleranceThreshold)) 1781 continue; 1782 } 1783 1784 assert(bestDstLoopDepth > 0 && "Unexpected loop fusion depth"); 1785 assert(!depthSliceUnions[bestDstLoopDepth - 1].isEmpty() && 1786 "Fusion depth has no computed slice union"); 1787 // Check if source loop is being inserted in the innermost 1788 // destination loop. Based on this, the fused loop may be optimized 1789 // further inside `fuseLoops`. 1790 bool isInnermostInsertion = (bestDstLoopDepth == dstLoopDepthTest); 1791 // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'. 1792 mlir::fuseLoops(sibAffineForOp, dstAffineForOp, 1793 depthSliceUnions[bestDstLoopDepth - 1], 1794 isInnermostInsertion); 1795 1796 auto dstForInst = cast<AffineForOp>(dstNode->op); 1797 // Update operation position of fused loop nest (if needed). 1798 if (insertPointInst != dstForInst.getOperation()) { 1799 dstForInst->moveBefore(insertPointInst); 1800 } 1801 // Update data dependence graph state post fusion. 1802 updateStateAfterSiblingFusion(sibNode, dstNode); 1803 } 1804 } 1805 1806 // Searches function argument uses and the graph from 'dstNode' looking for a 1807 // fusion candidate sibling node which shares no dependences with 'dstNode' 1808 // but which loads from the same memref. Returns true and sets 1809 // 'idAndMemrefToFuse' on success. Returns false otherwise. 1810 bool findSiblingNodeToFuse(Node *dstNode, 1811 DenseSet<unsigned> *visitedSibNodeIds, 1812 std::pair<unsigned, Value> *idAndMemrefToFuse) { 1813 // Returns true if 'sibNode' can be fused with 'dstNode' for input reuse 1814 // on 'memref'. 1815 auto canFuseWithSibNode = [&](Node *sibNode, Value memref) { 1816 // Skip if 'outEdge' is not a read-after-write dependence. 1817 // TODO: Remove restrict to single load op restriction. 1818 if (sibNode->getLoadOpCount(memref) != 1) 1819 return false; 1820 // Skip if there exists a path of dependent edges between 1821 // 'sibNode' and 'dstNode'. 1822 if (mdg->hasDependencePath(sibNode->id, dstNode->id) || 1823 mdg->hasDependencePath(dstNode->id, sibNode->id)) 1824 return false; 1825 // Skip sib node if it loads to (and stores from) the same memref on 1826 // which it also has an input dependence edge. 1827 DenseSet<Value> loadAndStoreMemrefSet; 1828 sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet); 1829 if (llvm::any_of(loadAndStoreMemrefSet, [=](Value memref) { 1830 return mdg->getIncomingMemRefAccesses(sibNode->id, memref) > 0; 1831 })) 1832 return false; 1833 1834 // Check that all stores are to the same memref. 1835 DenseSet<Value> storeMemrefs; 1836 for (auto *storeOpInst : sibNode->stores) { 1837 storeMemrefs.insert( 1838 cast<AffineWriteOpInterface>(storeOpInst).getMemRef()); 1839 } 1840 if (storeMemrefs.size() != 1) 1841 return false; 1842 1843 // Skip if a memref value in one node is used by a non-affine memref 1844 // access that lies between 'dstNode' and 'sibNode'. 1845 if (hasNonAffineUsersOnThePath(dstNode->id, sibNode->id, mdg) || 1846 hasNonAffineUsersOnThePath(sibNode->id, dstNode->id, mdg)) 1847 return false; 1848 return true; 1849 }; 1850 1851 // Search for siblings which load the same memref function argument. 1852 auto fn = dstNode->op->getParentOfType<func::FuncOp>(); 1853 for (unsigned i = 0, e = fn.getNumArguments(); i != e; ++i) { 1854 for (auto *user : fn.getArgument(i).getUsers()) { 1855 if (auto loadOp = dyn_cast<AffineReadOpInterface>(user)) { 1856 // Gather loops surrounding 'use'. 1857 SmallVector<AffineForOp, 4> loops; 1858 getLoopIVs(*user, &loops); 1859 // Skip 'use' if it is not within a loop nest. 1860 if (loops.empty()) 1861 continue; 1862 Node *sibNode = mdg->getForOpNode(loops[0]); 1863 assert(sibNode != nullptr); 1864 // Skip 'use' if it not a sibling to 'dstNode'. 1865 if (sibNode->id == dstNode->id) 1866 continue; 1867 // Skip 'use' if it has been visited. 1868 if (visitedSibNodeIds->count(sibNode->id) > 0) 1869 continue; 1870 // Skip 'use' if it does not load from the same memref as 'dstNode'. 1871 auto memref = loadOp.getMemRef(); 1872 if (dstNode->getLoadOpCount(memref) == 0) 1873 continue; 1874 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'. 1875 if (canFuseWithSibNode(sibNode, memref)) { 1876 visitedSibNodeIds->insert(sibNode->id); 1877 idAndMemrefToFuse->first = sibNode->id; 1878 idAndMemrefToFuse->second = memref; 1879 return true; 1880 } 1881 } 1882 } 1883 } 1884 1885 // Search for siblings by following edges through an intermediate src node. 1886 // Collect candidate 'dstNode' input edges in 'inEdges'. 1887 SmallVector<MemRefDependenceGraph::Edge, 2> inEdges; 1888 mdg->forEachMemRefInputEdge( 1889 dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) { 1890 // Add 'inEdge' if it is a read-after-write dependence. 1891 if (dstNode->getLoadOpCount(inEdge.value) > 0 && 1892 mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0) 1893 inEdges.push_back(inEdge); 1894 }); 1895 1896 // Search for sibling nodes to fuse by visiting output edges from each input 1897 // edge in 'inEdges'. 1898 for (auto &inEdge : inEdges) { 1899 // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'. 1900 SmallVector<MemRefDependenceGraph::Edge, 2> outEdges; 1901 mdg->forEachMemRefOutputEdge( 1902 inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) { 1903 unsigned sibNodeId = outEdge.id; 1904 if (visitedSibNodeIds->count(sibNodeId) > 0) 1905 return; 1906 // Skip output edge if not a sibling using the same memref. 1907 if (outEdge.id == dstNode->id || outEdge.value != inEdge.value) 1908 return; 1909 auto *sibNode = mdg->getNode(sibNodeId); 1910 if (!isa<AffineForOp>(sibNode->op)) 1911 return; 1912 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'. 1913 if (canFuseWithSibNode(sibNode, outEdge.value)) { 1914 // Add candidate 'outEdge' to sibling node. 1915 outEdges.push_back(outEdge); 1916 } 1917 }); 1918 1919 // Add first candidate if any were returned. 1920 if (!outEdges.empty()) { 1921 visitedSibNodeIds->insert(outEdges[0].id); 1922 idAndMemrefToFuse->first = outEdges[0].id; 1923 idAndMemrefToFuse->second = outEdges[0].value; 1924 return true; 1925 } 1926 } 1927 return false; 1928 } 1929 1930 /// Update data dependence graph state to reflect sibling fusion of 'sibNode' 1931 /// into 'dstNode'. 1932 void updateStateAfterSiblingFusion(Node *sibNode, Node *dstNode) { 1933 // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion. 1934 mdg->updateEdges(sibNode->id, dstNode->id); 1935 1936 // Collect dst loop stats after memref privatization transformation. 1937 auto dstForInst = cast<AffineForOp>(dstNode->op); 1938 LoopNestStateCollector dstLoopCollector; 1939 dstLoopCollector.collect(dstForInst.getOperation()); 1940 // Clear and add back loads and stores 1941 mdg->clearNodeLoadAndStores(dstNode->id); 1942 mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts, 1943 dstLoopCollector.storeOpInsts); 1944 // Remove old sibling loop nest if it no longer has outgoing dependence 1945 // edges, and it does not write to a memref which escapes the 1946 // function. 1947 if (mdg->getOutEdgeCount(sibNode->id) == 0) { 1948 Operation *op = sibNode->op; 1949 mdg->removeNode(sibNode->id); 1950 op->erase(); 1951 } 1952 } 1953 1954 // Clean up any allocs with no users. 1955 void eraseUnusedMemRefAllocations() { 1956 for (auto &pair : mdg->memrefEdgeCount) { 1957 if (pair.second > 0) 1958 continue; 1959 auto memref = pair.first; 1960 // Skip if there exist other uses (return operation or function calls). 1961 if (!memref.use_empty()) 1962 continue; 1963 // Use list expected to match the dep graph info. 1964 auto *op = memref.getDefiningOp(); 1965 if (isa_and_nonnull<memref::AllocOp>(op)) 1966 op->erase(); 1967 } 1968 } 1969 }; 1970 1971 } // namespace 1972 1973 void LoopFusion::runOnOperation() { 1974 MemRefDependenceGraph g; 1975 if (!g.init(getOperation())) 1976 return; 1977 1978 Optional<unsigned> fastMemorySpaceOpt; 1979 if (fastMemorySpace.hasValue()) 1980 fastMemorySpaceOpt = fastMemorySpace; 1981 unsigned localBufSizeThresholdBytes = localBufSizeThreshold * 1024; 1982 GreedyFusion fusion(&g, localBufSizeThresholdBytes, fastMemorySpaceOpt, 1983 maximalFusion, computeToleranceThreshold); 1984 1985 if (affineFusionMode == FusionMode::ProducerConsumer) 1986 fusion.runProducerConsumerFusionOnly(); 1987 else if (affineFusionMode == FusionMode::Sibling) 1988 fusion.runSiblingFusionOnly(); 1989 else 1990 fusion.runGreedyFusion(); 1991 } 1992