blob: ed79be02b81655b738729ace238b2bbab35d675e [file] [log] [blame]
MLIR Teamf28e4df2018-11-01 14:26:001//===- LoopFusion.cpp - Code to perform loop fusion -----------------------===//
2//
Mehdi Amini30857102020-01-26 03:58:303// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
Mehdi Amini56222a02019-12-23 17:35:364// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
MLIR Teamf28e4df2018-11-01 14:26:006//
Mehdi Amini56222a02019-12-23 17:35:367//===----------------------------------------------------------------------===//
MLIR Teamf28e4df2018-11-01 14:26:008//
9// This file implements loop fusion.
10//
11//===----------------------------------------------------------------------===//
12
River Riddle1834ad4a2020-04-07 20:58:1213#include "PassDetail.h"
MLIR Teamf28e4df2018-11-01 14:26:0014#include "mlir/Analysis/AffineAnalysis.h"
Uday Bondhuguladfe07b72019-02-23 00:51:0815#include "mlir/Analysis/AffineStructures.h"
MLIR Teamf28e4df2018-11-01 14:26:0016#include "mlir/Analysis/LoopAnalysis.h"
MLIR Team3b692302018-12-17 17:57:1417#include "mlir/Analysis/Utils.h"
Rob Sudermane7084712020-03-20 21:18:4718#include "mlir/Dialect/Affine/IR/AffineOps.h"
MLIR Teamf28e4df2018-11-01 14:26:0019#include "mlir/IR/AffineExpr.h"
20#include "mlir/IR/AffineMap.h"
21#include "mlir/IR/Builders.h"
Andy Davisa560f2c2019-05-24 17:54:2222#include "mlir/Transforms/LoopFusionUtils.h"
MLIR Teamf28e4df2018-11-01 14:26:0023#include "mlir/Transforms/LoopUtils.h"
24#include "mlir/Transforms/Passes.h"
MLIR Teamc4237ae2019-01-18 16:56:2725#include "mlir/Transforms/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0026#include "llvm/ADT/DenseMap.h"
MLIR Team3b692302018-12-17 17:57:1427#include "llvm/ADT/DenseSet.h"
28#include "llvm/ADT/SetVector.h"
MLIR Team4eef7952018-12-21 19:06:2329#include "llvm/Support/CommandLine.h"
MLIR Team38c2fe32019-01-14 19:26:2530#include "llvm/Support/Debug.h"
MLIR Team3b692302018-12-17 17:57:1431#include "llvm/Support/raw_ostream.h"
Uday Bondhugula864d9e02019-01-23 17:16:2432#include <iomanip>
Stella Laurenzo1a2ad062019-05-14 01:10:4833#include <sstream>
Nicolas Vasilache258e8d92019-05-03 18:07:3734#define DEBUG_TYPE "affine-loop-fusion"
MLIR Team38c2fe32019-01-14 19:26:2535
MLIR Team3b692302018-12-17 17:57:1436using llvm::SetVector;
MLIR Teamf28e4df2018-11-01 14:26:0037
38using namespace mlir;
39
40namespace {
MLIR Team3b692302018-12-17 17:57:1441/// Loop fusion pass. This pass currently supports a greedy fusion policy,
42/// which fuses loop nests with single-writer/single-reader memref dependences
43/// with the goal of improving locality.
44
River Riddle9db53a12020-07-07 08:35:2345// TODO: Support fusion of source loop nests which write to multiple
MLIR Team3b692302018-12-17 17:57:1446// memrefs, where each memref can have multiple users (if profitable).
River Riddle9db53a12020-07-07 08:35:2347// TODO: Extend this pass to check for fusion preventing dependences,
MLIR Teamf28e4df2018-11-01 14:26:0048// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1449
River Riddle1834ad4a2020-04-07 20:58:1250struct LoopFusion : public AffineLoopFusionBase<LoopFusion> {
River Riddle400ad6f2020-04-08 19:57:0251 LoopFusion() = default;
52 LoopFusion(unsigned fastMemorySpace, uint64_t localBufSizeThresholdBytes,
53 bool maximalFusion) {
54 this->fastMemorySpace = fastMemorySpace;
55 this->localBufSizeThreshold = localBufSizeThresholdBytes / 1024;
56 this->maximalFusion = maximalFusion;
57 }
MLIR Teamf28e4df2018-11-01 14:26:0058
River Riddleed5fe202019-02-28 22:50:4259 void runOnFunction() override;
MLIR Teamf28e4df2018-11-01 14:26:0060};
61
MLIR Teamf28e4df2018-11-01 14:26:0062} // end anonymous namespace
63
River Riddle80aca1e2020-04-07 20:56:1664std::unique_ptr<OperationPass<FuncOp>>
Mehdi Amini926fb682019-08-13 02:12:4265mlir::createLoopFusionPass(unsigned fastMemorySpace,
66 uint64_t localBufSizeThreshold, bool maximalFusion) {
Jacques Pienaar79f53b02019-08-17 18:05:3567 return std::make_unique<LoopFusion>(fastMemorySpace, localBufSizeThreshold,
68 maximalFusion);
Uday Bondhugulad4b3ff12019-02-27 00:10:1969}
MLIR Teamf28e4df2018-11-01 14:26:0070
River Riddle9db53a12020-07-07 08:35:2371// TODO: Replace when this is modeled through side-effects/op traits
River Riddle2666b972019-12-18 18:46:1672static bool isMemRefDereferencingOp(Operation &op) {
Rahul Joshid891d732020-06-24 18:49:3073 return isa<AffineReadOpInterface, AffineWriteOpInterface, AffineDmaStartOp,
74 AffineDmaWaitOp>(op);
River Riddle2666b972019-12-18 18:46:1675}
76
MLIR Team3b692302018-12-17 17:57:1477namespace {
MLIR Teamf28e4df2018-11-01 14:26:0078
MLIR Team3b692302018-12-17 17:57:1479// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:3580// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:4481struct LoopNestStateCollector {
Chris Lattnerd9b5bc82019-03-25 02:53:0582 SmallVector<AffineForOp, 4> forOps;
River Riddle99b87c92019-03-27 21:02:0283 SmallVector<Operation *, 4> loadOpInsts;
84 SmallVector<Operation *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:5385 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:1486
River Riddle99b87c92019-03-27 21:02:0287 void collect(Operation *opToWalk) {
88 opToWalk->walk([&](Operation *op) {
River Riddled5b60ee82019-05-12 01:59:5489 if (isa<AffineForOp>(op))
River Riddleadca3c22019-05-12 00:57:3290 forOps.push_back(cast<AffineForOp>(op));
River Riddle99b87c92019-03-27 21:02:0291 else if (op->getNumRegions() != 0)
River Riddlebf9c3812019-02-05 00:24:4492 hasNonForRegion = true;
Diego Caballeroa45fb192020-05-20 00:16:0493 else if (isa<AffineReadOpInterface>(op))
River Riddle99b87c92019-03-27 21:02:0294 loadOpInsts.push_back(op);
Diego Caballeroa45fb192020-05-20 00:16:0495 else if (isa<AffineWriteOpInterface>(op))
River Riddle99b87c92019-03-27 21:02:0296 storeOpInsts.push_back(op);
River Riddlebf9c3812019-02-05 00:24:4497 });
MLIR Team3b692302018-12-17 17:57:1498 }
99};
100
MLIR Team6892ffb2018-12-20 04:42:55101// MemRefDependenceGraph is a graph data structure where graph nodes are
River Riddle8c443672019-07-09 23:17:55102// top-level operations in a FuncOp which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55103// are memref dependences between the nodes.
River Riddle9db53a12020-07-07 08:35:23104// TODO: Add a more flexible dependence graph representation.
105// TODO: Add a depth parameter to dependence graph construction.
MLIR Team6892ffb2018-12-20 04:42:55106struct MemRefDependenceGraph {
107public:
108 // Node represents a node in the graph. A Node is either an entire loop nest
109 // rooted at the top level which contains loads/stores, or a top level
110 // load/store.
111 struct Node {
112 // The unique identifier of this node in the graph.
113 unsigned id;
Amit Sabne70a416d2019-04-09 16:17:40114 // The top-level statement which is (or contains) a load/store.
River Riddle99b87c92019-03-27 21:02:02115 Operation *op;
Chris Lattner5187cfc2018-12-28 05:21:41116 // List of load operations.
River Riddle99b87c92019-03-27 21:02:02117 SmallVector<Operation *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35118 // List of store op insts.
River Riddle99b87c92019-03-27 21:02:02119 SmallVector<Operation *, 4> stores;
120 Node(unsigned id, Operation *op) : id(id), op(op) {}
MLIR Team6892ffb2018-12-20 04:42:55121
122 // Returns the load op count for 'memref'.
River Riddlee62a6952019-12-23 22:45:01123 unsigned getLoadOpCount(Value memref) {
MLIR Team6892ffb2018-12-20 04:42:55124 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35125 for (auto *loadOpInst : loads) {
Diego Caballeroa45fb192020-05-20 00:16:04126 if (memref == cast<AffineReadOpInterface>(loadOpInst).getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55127 ++loadOpCount;
128 }
129 return loadOpCount;
130 }
131
132 // Returns the store op count for 'memref'.
River Riddlee62a6952019-12-23 22:45:01133 unsigned getStoreOpCount(Value memref) {
MLIR Team6892ffb2018-12-20 04:42:55134 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35135 for (auto *storeOpInst : stores) {
Diego Caballeroa45fb192020-05-20 00:16:04136 if (memref == cast<AffineWriteOpInterface>(storeOpInst).getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55137 ++storeOpCount;
138 }
139 return storeOpCount;
140 }
MLIR Team58aa3832019-02-16 01:12:19141
MLIR Teamd038e342019-03-01 19:50:25142 // Returns all store ops in 'storeOps' which access 'memref'.
River Riddlee62a6952019-12-23 22:45:01143 void getStoreOpsForMemref(Value memref,
River Riddle99b87c92019-03-27 21:02:02144 SmallVectorImpl<Operation *> *storeOps) {
MLIR Team58aa3832019-02-16 01:12:19145 for (auto *storeOpInst : stores) {
Diego Caballeroa45fb192020-05-20 00:16:04146 if (memref == cast<AffineWriteOpInterface>(storeOpInst).getMemRef())
MLIR Team58aa3832019-02-16 01:12:19147 storeOps->push_back(storeOpInst);
148 }
149 }
MLIR Teamd038e342019-03-01 19:50:25150
151 // Returns all load ops in 'loadOps' which access 'memref'.
River Riddlee62a6952019-12-23 22:45:01152 void getLoadOpsForMemref(Value memref,
River Riddle99b87c92019-03-27 21:02:02153 SmallVectorImpl<Operation *> *loadOps) {
MLIR Teamd038e342019-03-01 19:50:25154 for (auto *loadOpInst : loads) {
Diego Caballeroa45fb192020-05-20 00:16:04155 if (memref == cast<AffineReadOpInterface>(loadOpInst).getMemRef())
MLIR Teamd038e342019-03-01 19:50:25156 loadOps->push_back(loadOpInst);
157 }
158 }
159
160 // Returns all memrefs in 'loadAndStoreMemrefSet' for which this node
161 // has at least one load and store operation.
River Riddlee62a6952019-12-23 22:45:01162 void getLoadAndStoreMemrefSet(DenseSet<Value> *loadAndStoreMemrefSet) {
163 llvm::SmallDenseSet<Value, 2> loadMemrefs;
MLIR Teamd038e342019-03-01 19:50:25164 for (auto *loadOpInst : loads) {
Diego Caballeroa45fb192020-05-20 00:16:04165 loadMemrefs.insert(cast<AffineReadOpInterface>(loadOpInst).getMemRef());
MLIR Teamd038e342019-03-01 19:50:25166 }
167 for (auto *storeOpInst : stores) {
Diego Caballeroa45fb192020-05-20 00:16:04168 auto memref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
MLIR Teamd038e342019-03-01 19:50:25169 if (loadMemrefs.count(memref) > 0)
170 loadAndStoreMemrefSet->insert(memref);
171 }
172 }
MLIR Team6892ffb2018-12-20 04:42:55173 };
174
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03175 // Edge represents a data dependence between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55176 struct Edge {
177 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46178 // If this edge is stored in Edge = Node.inEdges[i], then
179 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
180 // If this edge is stored in Edge = Node.outEdges[i], then
181 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55182 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41183 // The SSA value on which this edge represents a dependence.
184 // If the value is a memref, then the dependence is between graph nodes
185 // which contain accesses to the same memref 'value'. If the value is a
186 // non-memref value, then the dependence is between a graph node which
187 // defines an SSA value and another graph node which uses the SSA value
River Riddle99b87c92019-03-27 21:02:02188 // (e.g. a constant operation defining a value which is used inside a loop
MLIR Teama0f3db402019-01-29 17:36:41189 // nest).
River Riddlee62a6952019-12-23 22:45:01190 Value value;
MLIR Team6892ffb2018-12-20 04:42:55191 };
192
193 // Map from node id to Node.
194 DenseMap<unsigned, Node> nodes;
195 // Map from node id to list of input edges.
196 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
197 // Map from node id to list of output edges.
198 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27199 // Map from memref to a count on the dependence edges associated with that
200 // memref.
River Riddlee62a6952019-12-23 22:45:01201 DenseMap<Value, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41202 // The next unique identifier to use for newly created graph nodes.
203 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55204
205 MemRefDependenceGraph() {}
206
207 // Initializes the dependence graph based on operations in 'f'.
208 // Returns true on success, false otherwise.
River Riddle8c443672019-07-09 23:17:55209 bool init(FuncOp f);
MLIR Team6892ffb2018-12-20 04:42:55210
211 // Returns the graph node for 'id'.
212 Node *getNode(unsigned id) {
213 auto it = nodes.find(id);
214 assert(it != nodes.end());
215 return &it->second;
216 }
217
MLIR Team9d30b362019-03-29 15:06:25218 // Returns the graph node for 'forOp'.
219 Node *getForOpNode(AffineForOp forOp) {
220 for (auto &idAndNode : nodes)
221 if (idAndNode.second.op == forOp.getOperation())
222 return &idAndNode.second;
223 return nullptr;
224 }
225
River Riddle99b87c92019-03-27 21:02:02226 // Adds a node with 'op' to the graph and returns its unique identifier.
227 unsigned addNode(Operation *op) {
228 Node node(nextNodeId++, op);
MLIR Teama0f3db402019-01-29 17:36:41229 nodes.insert({node.id, node});
230 return node.id;
231 }
232
MLIR Teamc4237ae2019-01-18 16:56:27233 // Remove node 'id' (and its associated edges) from graph.
234 void removeNode(unsigned id) {
235 // Remove each edge in 'inEdges[id]'.
236 if (inEdges.count(id) > 0) {
237 SmallVector<Edge, 2> oldInEdges = inEdges[id];
238 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41239 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27240 }
241 }
242 // Remove each edge in 'outEdges[id]'.
243 if (outEdges.count(id) > 0) {
244 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
245 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41246 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27247 }
248 }
249 // Erase remaining node state.
250 inEdges.erase(id);
251 outEdges.erase(id);
252 nodes.erase(id);
253 }
254
MLIR Teamd7c82442019-01-30 23:53:41255 // Returns true if node 'id' writes to any memref which escapes (or is an
256 // argument to) the function/block. Returns false otherwise.
257 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37258 Node *node = getNode(id);
259 for (auto *storeOpInst : node->stores) {
Diego Caballeroa45fb192020-05-20 00:16:04260 auto memref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
River Riddle2bdf33c2020-01-11 16:54:04261 auto *op = memref.getDefiningOp();
MLIR Team58aa3832019-02-16 01:12:19262 // Return true if 'memref' is a block argument.
River Riddle99b87c92019-03-27 21:02:02263 if (!op)
MLIR Teamd7c82442019-01-30 23:53:41264 return true;
MLIR Team58aa3832019-02-16 01:12:19265 // Return true if any use of 'memref' escapes the function.
River Riddle2bdf33c2020-01-11 16:54:04266 for (auto *user : memref.getUsers())
River Riddle8780d8d2019-05-18 18:09:07267 if (!isMemRefDereferencingOp(*user))
MLIR Teamd7c82442019-01-30 23:53:41268 return true;
MLIR Teamd7c82442019-01-30 23:53:41269 }
270 return false;
271 }
272
Diego Caballeroa45fb192020-05-20 00:16:04273 // Returns the unique AffineWriteOpInterface in `node` that meets all the
274 // following:
Diego Caballero34510552019-10-09 17:36:54275 // *) store is the only one that writes to a function-local memref live out
276 // of `node`,
277 // *) store is not the source of a self-dependence on `node`.
Diego Caballeroa45fb192020-05-20 00:16:04278 // Otherwise, returns a null AffineWriteOpInterface.
279 AffineWriteOpInterface getUniqueOutgoingStore(Node *node) {
280 AffineWriteOpInterface uniqueStore;
Diego Caballero34510552019-10-09 17:36:54281
282 // Return null if `node` doesn't have any outgoing edges.
283 auto outEdgeIt = outEdges.find(node->id);
284 if (outEdgeIt == outEdges.end())
285 return nullptr;
286
287 const auto &nodeOutEdges = outEdgeIt->second;
288 for (auto *op : node->stores) {
Diego Caballeroa45fb192020-05-20 00:16:04289 auto storeOp = cast<AffineWriteOpInterface>(op);
River Riddle35807bc2019-12-23 05:59:55290 auto memref = storeOp.getMemRef();
Diego Caballero34510552019-10-09 17:36:54291 // Skip this store if there are no dependences on its memref. This means
292 // that store either:
293 // *) writes to a memref that is only read within the same loop nest
294 // (self-dependence edges are not represented in graph at the moment),
295 // *) writes to a function live out memref (function parameter), or
296 // *) is dead.
297 if (llvm::all_of(nodeOutEdges, [=](const Edge &edge) {
298 return (edge.value != memref);
299 }))
300 continue;
301
302 if (uniqueStore)
303 // Found multiple stores to function-local live-out memrefs.
304 return nullptr;
305 // Found first store to function-local live-out memref.
306 uniqueStore = storeOp;
307 }
308
309 return uniqueStore;
310 }
311
MLIR Teamd7c82442019-01-30 23:53:41312 // Returns true if node 'id' can be removed from the graph. Returns false
313 // otherwise. A node can be removed from the graph iff the following
314 // conditions are met:
315 // *) The node does not write to any memref which escapes (or is a
316 // function/block argument).
317 // *) The node has no successors in the dependence graph.
318 bool canRemoveNode(unsigned id) {
319 if (writesToLiveInOrEscapingMemrefs(id))
320 return false;
321 Node *node = getNode(id);
322 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41323 // Return false if there exist out edges from 'id' on 'memref'.
Diego Caballeroa45fb192020-05-20 00:16:04324 auto storeMemref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
325 if (getOutEdgeCount(id, storeMemref) > 0)
MLIR Teama0f3db402019-01-29 17:36:41326 return false;
MLIR Team71495d52019-01-22 21:23:37327 }
MLIR Teama0f3db402019-01-29 17:36:41328 return true;
MLIR Team71495d52019-01-22 21:23:37329 }
330
MLIR Teamd038e342019-03-01 19:50:25331 // Returns true iff there is an edge from node 'srcId' to node 'dstId' which
332 // is for 'value' if non-null, or for any value otherwise. Returns false
333 // otherwise.
River Riddlee62a6952019-12-23 22:45:01334 bool hasEdge(unsigned srcId, unsigned dstId, Value value = nullptr) {
MLIR Team27d067e2019-01-16 17:55:02335 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
336 return false;
337 }
338 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25339 return edge.id == dstId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02340 });
341 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25342 return edge.id == srcId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02343 });
344 return hasOutEdge && hasInEdge;
345 }
346
MLIR Teama0f3db402019-01-29 17:36:41347 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
River Riddlee62a6952019-12-23 22:45:01348 void addEdge(unsigned srcId, unsigned dstId, Value value) {
MLIR Teama0f3db402019-01-29 17:36:41349 if (!hasEdge(srcId, dstId, value)) {
350 outEdges[srcId].push_back({dstId, value});
351 inEdges[dstId].push_back({srcId, value});
River Riddle2bdf33c2020-01-11 16:54:04352 if (value.getType().isa<MemRefType>())
MLIR Teama0f3db402019-01-29 17:36:41353 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02354 }
MLIR Team6892ffb2018-12-20 04:42:55355 }
356
MLIR Teama0f3db402019-01-29 17:36:41357 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
River Riddlee62a6952019-12-23 22:45:01358 void removeEdge(unsigned srcId, unsigned dstId, Value value) {
MLIR Team6892ffb2018-12-20 04:42:55359 assert(inEdges.count(dstId) > 0);
360 assert(outEdges.count(srcId) > 0);
River Riddle2bdf33c2020-01-11 16:54:04361 if (value.getType().isa<MemRefType>()) {
MLIR Teama0f3db402019-01-29 17:36:41362 assert(memrefEdgeCount.count(value) > 0);
363 memrefEdgeCount[value]--;
364 }
MLIR Team6892ffb2018-12-20 04:42:55365 // Remove 'srcId' from 'inEdges[dstId]'.
366 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41367 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55368 inEdges[dstId].erase(it);
369 break;
370 }
371 }
372 // Remove 'dstId' from 'outEdges[srcId]'.
373 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41374 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55375 outEdges[srcId].erase(it);
376 break;
377 }
378 }
379 }
380
MLIR Teamd038e342019-03-01 19:50:25381 // Returns true if there is a path in the dependence graph from node 'srcId'
382 // to node 'dstId'. Returns false otherwise.
383 bool hasDependencePath(unsigned srcId, unsigned dstId) {
384 // Worklist state is: <node-id, next-output-edge-index-to-visit>
385 SmallVector<std::pair<unsigned, unsigned>, 4> worklist;
386 worklist.push_back({srcId, 0});
387 // Run DFS traversal to see if 'dstId' is reachable from 'srcId'.
388 while (!worklist.empty()) {
389 auto &idAndIndex = worklist.back();
390 // Return true if we have reached 'dstId'.
391 if (idAndIndex.first == dstId)
392 return true;
393 // Pop and continue if node has no out edges, or if all out edges have
394 // already been visited.
395 if (outEdges.count(idAndIndex.first) == 0 ||
396 idAndIndex.second == outEdges[idAndIndex.first].size()) {
397 worklist.pop_back();
398 continue;
399 }
400 // Get graph edge to traverse.
401 Edge edge = outEdges[idAndIndex.first][idAndIndex.second];
402 // Increment next output edge index for 'idAndIndex'.
403 ++idAndIndex.second;
404 // Add node at 'edge.id' to worklist.
405 worklist.push_back({edge.id, 0});
406 }
407 return false;
408 }
409
MLIR Teama0f3db402019-01-29 17:36:41410 // Returns the input edge count for node 'id' and 'memref' from src nodes
MLIR Teamd038e342019-03-01 19:50:25411 // which access 'memref' with a store operation.
River Riddlee62a6952019-12-23 22:45:01412 unsigned getIncomingMemRefAccesses(unsigned id, Value memref) {
MLIR Team6892ffb2018-12-20 04:42:55413 unsigned inEdgeCount = 0;
414 if (inEdges.count(id) > 0)
415 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41416 if (inEdge.value == memref) {
417 Node *srcNode = getNode(inEdge.id);
418 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
MLIR Teamd038e342019-03-01 19:50:25419 if (srcNode->getStoreOpCount(memref) > 0)
MLIR Teama0f3db402019-01-29 17:36:41420 ++inEdgeCount;
421 }
MLIR Team6892ffb2018-12-20 04:42:55422 return inEdgeCount;
423 }
424
MLIR Teamd038e342019-03-01 19:50:25425 // Returns the output edge count for node 'id' and 'memref' (if non-null),
426 // otherwise returns the total output edge count from node 'id'.
River Riddlee62a6952019-12-23 22:45:01427 unsigned getOutEdgeCount(unsigned id, Value memref = nullptr) {
MLIR Team6892ffb2018-12-20 04:42:55428 unsigned outEdgeCount = 0;
429 if (outEdges.count(id) > 0)
430 for (auto &outEdge : outEdges[id])
MLIR Teamd038e342019-03-01 19:50:25431 if (!memref || outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55432 ++outEdgeCount;
433 return outEdgeCount;
434 }
435
River Riddle99b87c92019-03-27 21:02:02436 // Computes and returns an insertion point operation, before which the
MLIR Teama0f3db402019-01-29 17:36:41437 // the fused <srcId, dstId> loop nest can be inserted while preserving
438 // dependences. Returns nullptr if no such insertion point is found.
River Riddle99b87c92019-03-27 21:02:02439 Operation *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40440 if (outEdges.count(srcId) == 0)
River Riddle99b87c92019-03-27 21:02:02441 return getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41442
443 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
River Riddle99b87c92019-03-27 21:02:02444 SmallPtrSet<Operation *, 2> srcDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41445 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08446 if (outEdge.id != dstId)
River Riddle99b87c92019-03-27 21:02:02447 srcDepInsts.insert(getNode(outEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41448
449 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
River Riddle99b87c92019-03-27 21:02:02450 SmallPtrSet<Operation *, 2> dstDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41451 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08452 if (inEdge.id != srcId)
River Riddle99b87c92019-03-27 21:02:02453 dstDepInsts.insert(getNode(inEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41454
River Riddle99b87c92019-03-27 21:02:02455 Operation *srcNodeInst = getNode(srcId)->op;
456 Operation *dstNodeInst = getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41457
458 // Computing insertion point:
River Riddle99b87c92019-03-27 21:02:02459 // *) Walk all operation positions in Block operation list in the
460 // range (src, dst). For each operation 'op' visited in this search:
461 // *) Store in 'firstSrcDepPos' the first position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41462 // dependence edge from 'srcNode'.
River Riddle99b87c92019-03-27 21:02:02463 // *) Store in 'lastDstDepPost' the last position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41464 // dependence edge to 'dstNode'.
465 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
River Riddle99b87c92019-03-27 21:02:02466 // operation insertion point (or return null pointer if no such
MLIR Teama0f3db402019-01-29 17:36:41467 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
River Riddle99b87c92019-03-27 21:02:02468 SmallVector<Operation *, 2> depInsts;
MLIR Teama0f3db402019-01-29 17:36:41469 Optional<unsigned> firstSrcDepPos;
470 Optional<unsigned> lastDstDepPos;
471 unsigned pos = 0;
472 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
473 it != Block::iterator(dstNodeInst); ++it) {
River Riddle99b87c92019-03-27 21:02:02474 Operation *op = &(*it);
475 if (srcDepInsts.count(op) > 0 && firstSrcDepPos == None)
MLIR Teama0f3db402019-01-29 17:36:41476 firstSrcDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02477 if (dstDepInsts.count(op) > 0)
MLIR Teama0f3db402019-01-29 17:36:41478 lastDstDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02479 depInsts.push_back(op);
MLIR Teama0f3db402019-01-29 17:36:41480 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40481 }
MLIR Teama0f3db402019-01-29 17:36:41482
483 if (firstSrcDepPos.hasValue()) {
484 if (lastDstDepPos.hasValue()) {
485 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
486 // No valid insertion point exists which preserves dependences.
487 return nullptr;
488 }
489 }
490 // Return the insertion point at 'firstSrcDepPos'.
491 return depInsts[firstSrcDepPos.getValue()];
492 }
493 // No dependence targets in range (or only dst deps in range), return
494 // 'dstNodInst' insertion point.
495 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55496 }
497
MLIR Teama0f3db402019-01-29 17:36:41498 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
Andy Davis68a8da42019-11-18 19:20:03499 // has been replaced in node at 'dstId' by a private memref depending
500 // on the value of 'createPrivateMemRef'.
River Riddlee62a6952019-12-23 22:45:01501 void updateEdges(unsigned srcId, unsigned dstId, Value oldMemRef,
Andy Davis68a8da42019-11-18 19:20:03502 bool createPrivateMemRef) {
Kazuaki Ishizakifc817b02020-01-20 03:14:37503 // For each edge in 'inEdges[srcId]': add new edge remapping to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55504 if (inEdges.count(srcId) > 0) {
505 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
506 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41507 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
508 if (inEdge.value != oldMemRef)
509 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55510 }
511 }
MLIR Teamc4237ae2019-01-18 16:56:27512 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55513 if (outEdges.count(srcId) > 0) {
514 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
515 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27516 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
517 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41518 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55519 }
520 }
MLIR Teama0f3db402019-01-29 17:36:41521 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
522 // replaced by a private memref). These edges could come from nodes
523 // other than 'srcId' which were removed in the previous step.
Andy Davis68a8da42019-11-18 19:20:03524 if (inEdges.count(dstId) > 0 && createPrivateMemRef) {
MLIR Teama0f3db402019-01-29 17:36:41525 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
526 for (auto &inEdge : oldInEdges)
527 if (inEdge.value == oldMemRef)
528 removeEdge(inEdge.id, dstId, inEdge.value);
529 }
MLIR Team6892ffb2018-12-20 04:42:55530 }
531
MLIR Teamd038e342019-03-01 19:50:25532 // Update edge mappings for nodes 'sibId' and 'dstId' to reflect fusion
533 // of sibling node 'sidId' into node 'dstId'.
534 void updateEdges(unsigned sibId, unsigned dstId) {
535 // For each edge in 'inEdges[sibId]':
536 // *) Add new edge from source node 'inEdge.id' to 'dstNode'.
537 // *) Remove edge from source node 'inEdge.id' to 'sibNode'.
538 if (inEdges.count(sibId) > 0) {
539 SmallVector<Edge, 2> oldInEdges = inEdges[sibId];
540 for (auto &inEdge : oldInEdges) {
541 addEdge(inEdge.id, dstId, inEdge.value);
542 removeEdge(inEdge.id, sibId, inEdge.value);
543 }
544 }
545
546 // For each edge in 'outEdges[sibId]' to node 'id'
547 // *) Add new edge from 'dstId' to 'outEdge.id'.
548 // *) Remove edge from 'sibId' to 'outEdge.id'.
549 if (outEdges.count(sibId) > 0) {
550 SmallVector<Edge, 2> oldOutEdges = outEdges[sibId];
551 for (auto &outEdge : oldOutEdges) {
552 addEdge(dstId, outEdge.id, outEdge.value);
553 removeEdge(sibId, outEdge.id, outEdge.value);
554 }
555 }
556 }
557
MLIR Team6892ffb2018-12-20 04:42:55558 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddle99b87c92019-03-27 21:02:02559 void addToNode(unsigned id, const SmallVectorImpl<Operation *> &loads,
560 const SmallVectorImpl<Operation *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55561 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35562 for (auto *loadOpInst : loads)
563 node->loads.push_back(loadOpInst);
564 for (auto *storeOpInst : stores)
565 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55566 }
567
MLIR Teamc4237ae2019-01-18 16:56:27568 void clearNodeLoadAndStores(unsigned id) {
569 Node *node = getNode(id);
570 node->loads.clear();
571 node->stores.clear();
572 }
573
MLIR Teamd038e342019-03-01 19:50:25574 // Calls 'callback' for each input edge incident to node 'id' which carries a
575 // memref dependence.
576 void forEachMemRefInputEdge(unsigned id,
577 const std::function<void(Edge)> &callback) {
578 if (inEdges.count(id) > 0)
579 forEachMemRefEdge(inEdges[id], callback);
580 }
Amit Sabne70a416d2019-04-09 16:17:40581
MLIR Teamd038e342019-03-01 19:50:25582 // Calls 'callback' for each output edge from node 'id' which carries a
583 // memref dependence.
584 void forEachMemRefOutputEdge(unsigned id,
585 const std::function<void(Edge)> &callback) {
586 if (outEdges.count(id) > 0)
587 forEachMemRefEdge(outEdges[id], callback);
588 }
Amit Sabne70a416d2019-04-09 16:17:40589
MLIR Teamd038e342019-03-01 19:50:25590 // Calls 'callback' for each edge in 'edges' which carries a memref
591 // dependence.
592 void forEachMemRefEdge(ArrayRef<Edge> edges,
593 const std::function<void(Edge)> &callback) {
Uday Bondhugulaec85d7c2020-07-15 10:41:08594 for (const auto &edge : edges) {
MLIR Teamd038e342019-03-01 19:50:25595 // Skip if 'edge' is not a memref dependence edge.
River Riddle2bdf33c2020-01-11 16:54:04596 if (!edge.value.getType().isa<MemRefType>())
MLIR Teamd038e342019-03-01 19:50:25597 continue;
598 assert(nodes.count(edge.id) > 0);
599 // Skip if 'edge.id' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:54600 if (!isa<AffineForOp>(getNode(edge.id)->op))
MLIR Teamd038e342019-03-01 19:50:25601 continue;
602 // Visit current input edge 'edge'.
603 callback(edge);
604 }
605 }
606
MLIR Team6892ffb2018-12-20 04:42:55607 void print(raw_ostream &os) const {
608 os << "\nMemRefDependenceGraph\n";
609 os << "\nNodes:\n";
Uday Bondhugulaec85d7c2020-07-15 10:41:08610 for (const auto &idAndNode : nodes) {
MLIR Team6892ffb2018-12-20 04:42:55611 os << "Node: " << idAndNode.first << "\n";
612 auto it = inEdges.find(idAndNode.first);
613 if (it != inEdges.end()) {
614 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41615 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55616 }
617 it = outEdges.find(idAndNode.first);
618 if (it != outEdges.end()) {
619 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41620 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55621 }
622 }
623 }
624 void dump() const { print(llvm::errs()); }
625};
626
River Riddle2666b972019-12-18 18:46:16627} // end anonymous namespace
628
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03629// Initializes the data dependence graph by walking operations in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55630// Assigns each node in the graph a node id based on program order in 'f'.
River Riddle9db53a12020-07-07 08:35:23631// TODO: Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55632// dependence graph at a different depth.
River Riddle8c443672019-07-09 23:17:55633bool MemRefDependenceGraph::init(FuncOp f) {
River Riddlee62a6952019-12-23 22:45:01634 DenseMap<Value, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43635
636 // TODO: support multi-block functions.
Rahul Joshi2eaadfc2020-06-17 20:20:36637 if (!llvm::hasSingleElement(f))
Chris Lattnerdffc5892018-12-29 23:33:43638 return false;
639
River Riddle99b87c92019-03-27 21:02:02640 DenseMap<Operation *, unsigned> forToNodeMap;
641 for (auto &op : f.front()) {
River Riddlec5ecf992019-05-11 22:56:50642 if (auto forOp = dyn_cast<AffineForOp>(op)) {
River Riddle5052bd82019-02-02 00:42:18643 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55644 // all loads and store accesses it contains.
645 LoopNestStateCollector collector;
River Riddle99b87c92019-03-27 21:02:02646 collector.collect(&op);
River Riddle832567b2019-03-25 17:14:34647 // Return false if a non 'affine.for' region was found (not currently
648 // supported).
River Riddle75553832019-01-29 05:23:53649 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55650 return false;
River Riddle99b87c92019-03-27 21:02:02651 Node node(nextNodeId++, &op);
Chris Lattner456ad6a2018-12-29 00:05:35652 for (auto *opInst : collector.loadOpInsts) {
653 node.loads.push_back(opInst);
Diego Caballeroa45fb192020-05-20 00:16:04654 auto memref = cast<AffineReadOpInterface>(opInst).getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55655 memrefAccesses[memref].insert(node.id);
656 }
Chris Lattner456ad6a2018-12-29 00:05:35657 for (auto *opInst : collector.storeOpInsts) {
658 node.stores.push_back(opInst);
Diego Caballeroa45fb192020-05-20 00:16:04659 auto memref = cast<AffineWriteOpInterface>(opInst).getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55660 memrefAccesses[memref].insert(node.id);
661 }
River Riddle99b87c92019-03-27 21:02:02662 forToNodeMap[&op] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55663 nodes.insert({node.id, node});
Diego Caballeroa45fb192020-05-20 00:16:04664 } else if (auto loadOp = dyn_cast<AffineReadOpInterface>(op)) {
River Riddleb4992772019-02-04 18:38:47665 // Create graph node for top-level load op.
River Riddle99b87c92019-03-27 21:02:02666 Node node(nextNodeId++, &op);
667 node.loads.push_back(&op);
Diego Caballeroa45fb192020-05-20 00:16:04668 auto memref = cast<AffineReadOpInterface>(op).getMemRef();
River Riddleb4992772019-02-04 18:38:47669 memrefAccesses[memref].insert(node.id);
670 nodes.insert({node.id, node});
Diego Caballeroa45fb192020-05-20 00:16:04671 } else if (auto storeOp = dyn_cast<AffineWriteOpInterface>(op)) {
River Riddleb4992772019-02-04 18:38:47672 // Create graph node for top-level store op.
River Riddle99b87c92019-03-27 21:02:02673 Node node(nextNodeId++, &op);
674 node.stores.push_back(&op);
Diego Caballeroa45fb192020-05-20 00:16:04675 auto memref = cast<AffineWriteOpInterface>(op).getMemRef();
River Riddleb4992772019-02-04 18:38:47676 memrefAccesses[memref].insert(node.id);
677 nodes.insert({node.id, node});
River Riddle99b87c92019-03-27 21:02:02678 } else if (op.getNumRegions() != 0) {
River Riddleb4992772019-02-04 18:38:47679 // Return false if another region is found (not currently supported).
680 return false;
River Riddle99b87c92019-03-27 21:02:02681 } else if (op.getNumResults() > 0 && !op.use_empty()) {
River Riddleb4992772019-02-04 18:38:47682 // Create graph node for top-level producer of SSA values, which
683 // could be used by loop nest nodes.
River Riddle99b87c92019-03-27 21:02:02684 Node node(nextNodeId++, &op);
River Riddleb4992772019-02-04 18:38:47685 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41686 }
687 }
688
689 // Add dependence edges between nodes which produce SSA values and their
690 // users.
691 for (auto &idAndNode : nodes) {
692 const Node &node = idAndNode.second;
693 if (!node.loads.empty() || !node.stores.empty())
694 continue;
River Riddle99b87c92019-03-27 21:02:02695 auto *opInst = node.op;
River Riddle35807bc2019-12-23 05:59:55696 for (auto value : opInst->getResults()) {
River Riddle2bdf33c2020-01-11 16:54:04697 for (auto *user : value.getUsers()) {
Chris Lattnerd9b5bc82019-03-25 02:53:05698 SmallVector<AffineForOp, 4> loops;
River Riddle8780d8d2019-05-18 18:09:07699 getLoopIVs(*user, &loops);
MLIR Teama0f3db402019-01-29 17:36:41700 if (loops.empty())
701 continue;
River Riddlef9d91532019-03-27 00:05:09702 assert(forToNodeMap.count(loops[0].getOperation()) > 0);
703 unsigned userLoopNestId = forToNodeMap[loops[0].getOperation()];
MLIR Teama0f3db402019-01-29 17:36:41704 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55705 }
706 }
MLIR Team6892ffb2018-12-20 04:42:55707 }
708
709 // Walk memref access lists and add graph edges between dependent nodes.
710 for (auto &memrefAndList : memrefAccesses) {
711 unsigned n = memrefAndList.second.size();
712 for (unsigned i = 0; i < n; ++i) {
713 unsigned srcId = memrefAndList.second[i];
714 bool srcHasStore =
715 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
716 for (unsigned j = i + 1; j < n; ++j) {
717 unsigned dstId = memrefAndList.second[j];
718 bool dstHasStore =
719 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
720 if (srcHasStore || dstHasStore)
721 addEdge(srcId, dstId, memrefAndList.first);
722 }
723 }
724 }
725 return true;
726}
727
MLIR Team27d067e2019-01-16 17:55:02728// Removes load operations from 'srcLoads' which operate on 'memref', and
729// adds them to 'dstLoads'.
River Riddlee62a6952019-12-23 22:45:01730static void moveLoadsAccessingMemrefTo(Value memref,
River Riddle99b87c92019-03-27 21:02:02731 SmallVectorImpl<Operation *> *srcLoads,
732 SmallVectorImpl<Operation *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02733 dstLoads->clear();
River Riddle99b87c92019-03-27 21:02:02734 SmallVector<Operation *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02735 for (auto *load : *srcLoads) {
Diego Caballeroa45fb192020-05-20 00:16:04736 if (cast<AffineReadOpInterface>(load).getMemRef() == memref)
MLIR Team27d067e2019-01-16 17:55:02737 dstLoads->push_back(load);
738 else
739 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25740 }
MLIR Team27d067e2019-01-16 17:55:02741 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25742}
743
MLIR Team27d067e2019-01-16 17:55:02744// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddle99b87c92019-03-27 21:02:02745static unsigned getInnermostCommonLoopDepth(ArrayRef<Operation *> ops) {
MLIR Team27d067e2019-01-16 17:55:02746 unsigned numOps = ops.size();
747 assert(numOps > 0);
748
Chris Lattnerd9b5bc82019-03-25 02:53:05749 std::vector<SmallVector<AffineForOp, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02750 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
751 for (unsigned i = 0; i < numOps; ++i) {
752 getLoopIVs(*ops[i], &loops[i]);
753 loopDepthLimit =
754 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25755 }
MLIR Team27d067e2019-01-16 17:55:02756
757 unsigned loopDepth = 0;
758 for (unsigned d = 0; d < loopDepthLimit; ++d) {
759 unsigned i;
760 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18761 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02762 break;
MLIR Team27d067e2019-01-16 17:55:02763 }
764 if (i != numOps)
765 break;
766 ++loopDepth;
767 }
768 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25769}
770
MLIR Teamd7c82442019-01-30 23:53:41771// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
772// and 'storeOpInsts' are satisfied.
River Riddle99b87c92019-03-27 21:02:02773static unsigned getMaxLoopDepth(ArrayRef<Operation *> loadOpInsts,
774 ArrayRef<Operation *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41775 // Merge loads and stores into the same array.
River Riddle99b87c92019-03-27 21:02:02776 SmallVector<Operation *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41777 ops.append(storeOpInsts.begin(), storeOpInsts.end());
778
779 // Compute the innermost common loop depth for loads and stores.
780 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
781
782 // Return common loop depth for loads if there are no store ops.
783 if (storeOpInsts.empty())
784 return loopDepth;
785
786 // Check dependences on all pairs of ops in 'ops' and store the minimum
787 // loop depth at which a dependence is satisfied.
788 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
789 auto *srcOpInst = ops[i];
790 MemRefAccess srcAccess(srcOpInst);
791 for (unsigned j = 0; j < e; ++j) {
792 auto *dstOpInst = ops[j];
793 MemRefAccess dstAccess(dstOpInst);
794
795 unsigned numCommonLoops =
796 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
797 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
798 FlatAffineConstraints dependenceConstraints;
River Riddle9db53a12020-07-07 08:35:23799 // TODO: Cache dependence analysis results, check cache here.
Andy Davise33e36f2019-06-10 17:50:08800 DependenceResult result = checkMemrefAccessDependence(
801 srcAccess, dstAccess, d, &dependenceConstraints,
802 /*dependenceComponents=*/nullptr);
803 if (hasDependence(result)) {
MLIR Teamd7c82442019-01-30 23:53:41804 // Store minimum loop depth and break because we want the min 'd' at
805 // which there is a dependence.
806 loopDepth = std::min(loopDepth, d - 1);
807 break;
808 }
809 }
810 }
811 }
812 return loopDepth;
813}
814
MLIR Team8f5f2c72019-02-15 17:32:18815// Sinks all sequential loops to the innermost levels (while preserving
816// relative order among them) and moves all parallel loops to the
817// outermost (while again preserving relative order among them).
818// This can increase the loop depth at which we can fuse a slice, since we are
819// pushing loop carried dependence to a greater depth in the loop nest.
820static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
River Riddled5b60ee82019-05-12 01:59:54821 assert(isa<AffineForOp>(node->op));
Andy Davis90d40232019-05-13 13:57:56822 AffineForOp newRootForOp = sinkSequentialLoops(cast<AffineForOp>(node->op));
823 node->op = newRootForOp.getOperation();
MLIR Team8f5f2c72019-02-15 17:32:18824}
825
River Riddle9db53a12020-07-07 08:35:23826// TODO: improve/complete this when we have target data.
River Riddle2666b972019-12-18 18:46:16827static unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
Uday Bondhugula8be26272019-02-02 01:06:22828 auto elementType = memRefType.getElementType();
829
830 unsigned sizeInBits;
River Riddlede5a81b2020-03-02 17:18:45831 if (elementType.isIntOrFloat()) {
Uday Bondhugula8be26272019-02-02 01:06:22832 sizeInBits = elementType.getIntOrFloatBitWidth();
833 } else {
834 auto vectorType = elementType.cast<VectorType>();
835 sizeInBits =
836 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
837 }
838 return llvm::divideCeil(sizeInBits, 8);
839}
840
MLIR Teamc4237ae2019-01-18 16:56:27841// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:18842// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:52843// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
River Riddle9db53a12020-07-07 08:35:23844// TODO: consider refactoring the common code from generateDma and
Uday Bondhugula94a03f82019-01-22 21:58:52845// this one.
River Riddlee62a6952019-12-23 22:45:01846static Value createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst,
847 unsigned dstLoopDepth,
848 Optional<unsigned> fastMemorySpace,
849 uint64_t localBufSizeThreshold) {
River Riddlef9d91532019-03-27 00:05:09850 auto *forInst = forOp.getOperation();
River Riddle5052bd82019-02-02 00:42:18851
852 // Create builder to insert alloc op just before 'forOp'.
River Riddlef1b848e2019-06-05 02:18:23853 OpBuilder b(forInst);
MLIR Teamc4237ae2019-01-18 16:56:27854 // Builder to create constants at the top level.
River Riddlece502af2019-07-08 18:20:26855 OpBuilder top(forInst->getParentOfType<FuncOp>().getBody());
MLIR Teamc4237ae2019-01-18 16:56:27856 // Create new memref type based on slice bounds.
Diego Caballeroa45fb192020-05-20 00:16:04857 auto oldMemRef = cast<AffineWriteOpInterface>(srcStoreOpInst).getMemRef();
River Riddle2bdf33c2020-01-11 16:54:04858 auto oldMemRefType = oldMemRef.getType().cast<MemRefType>();
MLIR Teamc4237ae2019-01-18 16:56:27859 unsigned rank = oldMemRefType.getRank();
860
Uday Bondhugula94a03f82019-01-22 21:58:52861 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:44862 MemRefRegion region(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:47863 bool validRegion = succeeded(region.compute(srcStoreOpInst, dstLoopDepth));
MLIR Teamd42ef782019-03-04 19:01:25864 (void)validRegion;
865 assert(validRegion && "unexpected memref region failure");
River Riddle6859f332019-01-23 22:39:45866 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:27867 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:52868 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:27869 lbs.reserve(rank);
870 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:52871 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:27872 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:44873 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:22874 assert(numElements.hasValue() &&
875 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:27876
Uday Bondhugula0f504142019-02-04 21:48:44877 const FlatAffineConstraints *cst = region.getConstraints();
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03878 // 'outerIVs' holds the values that this memory region is symbolic/parametric
Uday Bondhugula94a03f82019-01-22 21:58:52879 // on; this would correspond to loop IVs surrounding the level at which the
880 // slice is being materialized.
River Riddlee62a6952019-12-23 22:45:01881 SmallVector<Value, 8> outerIVs;
Uday Bondhugula94a03f82019-01-22 21:58:52882 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
883
884 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:27885 SmallVector<AffineExpr, 4> offsets;
886 offsets.reserve(rank);
887 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:52888 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
889
MLIR Teamc4237ae2019-01-18 16:56:27890 AffineExpr offset = top.getAffineConstantExpr(0);
891 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
892 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
893 }
Uday Bondhugula94a03f82019-01-22 21:58:52894 assert(lbDivisors[d] > 0);
895 offset =
896 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:27897 offsets.push_back(offset);
898 }
899
900 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
901 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:22902 uint64_t bufSize =
903 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
904 unsigned newMemSpace;
Uday Bondhugulad4b3ff12019-02-27 00:10:19905 if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
Uday Bondhugula8be26272019-02-02 01:06:22906 newMemSpace = fastMemorySpace.getValue();
907 } else {
908 newMemSpace = oldMemRefType.getMemorySpace();
909 }
River Riddle2acc2202019-10-18 03:08:01910 auto newMemRefType = MemRefType::get(newShape, oldMemRefType.getElementType(),
911 {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:27912
Uday Bondhugulaaec53442020-06-23 20:52:03913 // Create new private memref for fused loop 'forOp'. 'newShape' is always
914 // a constant shape.
River Riddle9db53a12020-07-07 08:35:23915 // TODO: Create/move alloc ops for private memrefs closer to their
MLIR Teama0f3db402019-01-29 17:36:41916 // consumer loop nests to reduce their live range. Currently they are added
917 // at the beginning of the function, because loop nests can be reordered
918 // during the fusion pass.
Uday Bondhugulaaec53442020-06-23 20:52:03919 Value newMemRef = top.create<AllocOp>(forOp.getLoc(), newMemRefType);
MLIR Teamc4237ae2019-01-18 16:56:27920
921 // Build an AffineMap to remap access functions based on lower bound offsets.
922 SmallVector<AffineExpr, 4> remapExprs;
923 remapExprs.reserve(rank);
MLIR Teamc4237ae2019-01-18 16:56:27924 for (unsigned i = 0; i < rank; i++) {
Uday Bondhugula94a03f82019-01-22 21:58:52925 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
926
927 auto remapExpr =
928 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
929 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:27930 }
Diego Caballero3bfbc5d2020-08-04 18:22:19931
932 auto indexRemap =
933 AffineMap::get(outerIVs.size() + rank, 0, remapExprs, forOp.getContext());
934
MLIR Teamc4237ae2019-01-18 16:56:27935 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugulaaa2cee92019-08-28 00:56:25936 LogicalResult res =
Uday Bondhugula94a03f82019-01-22 21:58:52937 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
938 /*extraOperands=*/outerIVs,
Uday Bondhugula727a50a2019-09-18 18:25:33939 /*symbolOperands=*/{},
River Riddleaf1abcc2019-03-25 18:13:31940 /*domInstFilter=*/&*forOp.getBody()->begin());
Uday Bondhugulaaa2cee92019-08-28 00:56:25941 assert(succeeded(res) &&
942 "replaceAllMemrefUsesWith should always succeed here");
943 (void)res;
MLIR Teamc4237ae2019-01-18 16:56:27944 return newMemRef;
945}
946
Tung D. Le2b5d1772020-06-24 16:56:05947/// Walking from node 'srcId' to node 'dstId' (exclusive of 'srcId' and
948/// 'dstId'), if there is any non-affine operation accessing 'memref', return
949/// false. Otherwise, return true.
950static bool hasNonAffineUsersOnThePath(unsigned srcId, unsigned dstId,
951 Value memref,
952 MemRefDependenceGraph *mdg) {
953 auto *srcNode = mdg->getNode(srcId);
954 auto *dstNode = mdg->getNode(dstId);
955 Value::user_range users = memref.getUsers();
956 // For each MemRefDependenceGraph's node that is between 'srcNode' and
957 // 'dstNode' (exclusive of 'srcNodes' and 'dstNode'), check whether any
958 // non-affine operation in the node accesses the 'memref'.
959 for (auto &idAndNode : mdg->nodes) {
960 Operation *op = idAndNode.second.op;
961 // Take care of operations between 'srcNode' and 'dstNode'.
962 if (srcNode->op->isBeforeInBlock(op) && op->isBeforeInBlock(dstNode->op)) {
963 // Walk inside the operation to find any use of the memref.
964 // Interrupt the walk if found.
965 auto walkResult = op->walk([&](Operation *user) {
966 // Skip affine ops.
967 if (isMemRefDereferencingOp(*user))
968 return WalkResult::advance();
969 // Find a non-affine op that uses the memref.
970 if (llvm::is_contained(users, user))
971 return WalkResult::interrupt();
972 return WalkResult::advance();
973 });
974 if (walkResult.wasInterrupted())
975 return true;
976 }
977 }
978 return false;
979}
980
981/// Check whether a memref value in node 'srcId' has a non-affine that
982/// is between node 'srcId' and node 'dstId' (exclusive of 'srcNode' and
983/// 'dstNode').
984static bool hasNonAffineUsersOnThePath(unsigned srcId, unsigned dstId,
985 MemRefDependenceGraph *mdg) {
986 // Collect memref values in node 'srcId'.
987 auto *srcNode = mdg->getNode(srcId);
988 llvm::SmallDenseSet<Value, 2> memRefValues;
989 srcNode->op->walk([&](Operation *op) {
990 // Skip affine ops.
991 if (isa<AffineForOp>(op))
992 return WalkResult::advance();
993 for (Value v : op->getOperands())
994 // Collect memref values only.
995 if (v.getType().isa<MemRefType>())
996 memRefValues.insert(v);
997 return WalkResult::advance();
998 });
999 // Looking for users between node 'srcId' and node 'dstId'.
1000 for (Value memref : memRefValues)
1001 if (hasNonAffineUsersOnThePath(srcId, dstId, memref, mdg))
1002 return true;
1003 return false;
1004}
1005
Diego Caballero34510552019-10-09 17:36:541006// Checks if node 'srcId' can be safely fused into node 'dstId'. Node 'srcId'
1007// may write to multiple memrefs but it is required that only one of them,
Diego Caballero330d1ff2019-12-03 14:09:211008// 'srcLiveOutStoreOp', has output edges.
Diego Caballero34510552019-10-09 17:36:541009// Returns true if 'dstNode's read/write region to 'memref' is a super set of
Diego Caballero330d1ff2019-12-03 14:09:211010// 'srcNode's write region to 'memref' and 'srcId' has only one output edge.
River Riddle9db53a12020-07-07 08:35:231011// TODO: Generalize this to handle more live in/out cases.
Diego Caballeroa45fb192020-05-20 00:16:041012static bool
1013canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
1014 AffineWriteOpInterface srcLiveOutStoreOp,
1015 MemRefDependenceGraph *mdg) {
Diego Caballero34510552019-10-09 17:36:541016 assert(srcLiveOutStoreOp && "Expected a valid store op");
MLIR Team58aa3832019-02-16 01:12:191017 auto *dstNode = mdg->getNode(dstId);
River Riddlee62a6952019-12-23 22:45:011018 Value memref = srcLiveOutStoreOp.getMemRef();
Diego Caballero330d1ff2019-12-03 14:09:211019 // Return false if 'srcNode' has more than one output edge on 'memref'.
1020 if (mdg->getOutEdgeCount(srcId, memref) > 1)
1021 return false;
MLIR Team58aa3832019-02-16 01:12:191022
Diego Caballero34510552019-10-09 17:36:541023 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOp' on 'memref'.
1024 MemRefRegion srcWriteRegion(srcLiveOutStoreOp.getLoc());
1025 if (failed(srcWriteRegion.compute(srcLiveOutStoreOp, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251026 LLVM_DEBUG(llvm::dbgs()
1027 << "Unable to compute MemRefRegion for source operation\n.");
1028 return false;
1029 }
MLIR Team58aa3832019-02-16 01:12:191030 SmallVector<int64_t, 4> srcShape;
1031 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
Diego Caballero34510552019-10-09 17:36:541032 // by 'srcStoreOp' at depth 'dstLoopDepth'.
MLIR Team58aa3832019-02-16 01:12:191033 Optional<int64_t> srcNumElements =
1034 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1035 if (!srcNumElements.hasValue())
1036 return false;
1037
Andy Davis7c1fc9e2019-04-02 13:37:401038 // Compute MemRefRegion 'dstRegion' for 'dstStore/LoadOpInst' on 'memref'.
River Riddle9db53a12020-07-07 08:35:231039 // TODO: Compute 'unionboundingbox' of all write regions (one for
MLIR Team9d9675f2019-03-28 21:54:491040 // each store op in 'dstStoreOps').
Andy Davis7c1fc9e2019-04-02 13:37:401041 SmallVector<Operation *, 2> dstStoreOps;
1042 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1043 SmallVector<Operation *, 2> dstLoadOps;
1044 dstNode->getLoadOpsForMemref(memref, &dstLoadOps);
1045
1046 auto *dstOpInst = dstStoreOps.empty() ? dstLoadOps[0] : dstStoreOps[0];
1047 MemRefRegion dstRegion(dstOpInst->getLoc());
1048 if (failed(dstRegion.compute(dstOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251049 LLVM_DEBUG(llvm::dbgs()
1050 << "Unable to compute MemRefRegion for dest operation\n.");
1051 return false;
1052 }
MLIR Team58aa3832019-02-16 01:12:191053 SmallVector<int64_t, 4> dstShape;
Andy Davis7c1fc9e2019-04-02 13:37:401054 // Query 'dstRegion' for 'dstShape' and 'dstNumElements'.
1055 // by 'dstOpInst' at depth 'dstLoopDepth'.
MLIR Team58aa3832019-02-16 01:12:191056 Optional<int64_t> dstNumElements =
Andy Davis7c1fc9e2019-04-02 13:37:401057 dstRegion.getConstantBoundingSizeAndShape(&dstShape);
MLIR Team58aa3832019-02-16 01:12:191058 if (!dstNumElements.hasValue())
1059 return false;
1060
1061 // Return false if write region is not a superset of 'srcNodes' write
1062 // region to 'memref'.
River Riddle9db53a12020-07-07 08:35:231063 // TODO: Check the shape and lower bounds here too.
MLIR Team58aa3832019-02-16 01:12:191064 if (srcNumElements != dstNumElements)
1065 return false;
Tung D. Le2b5d1772020-06-24 16:56:051066
1067 // Return false if 'memref' is used by a non-affine operation that is
1068 // between node 'srcId' and node 'dstId'.
1069 if (hasNonAffineUsersOnThePath(srcId, dstId, mdg))
1070 return false;
1071
MLIR Team58aa3832019-02-16 01:12:191072 return true;
1073}
1074
MLIR Team27d067e2019-01-16 17:55:021075// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411076// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
MLIR Teamd038e342019-03-01 19:50:251077// The argument 'srcStoreOpInst' is used to calculate the storage reduction on
1078// the memref being produced and consumed, which is an input to the cost model.
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031079// For producer-consumer fusion, 'srcStoreOpInst' will be the same as
MLIR Teamd038e342019-03-01 19:50:251080// 'srcOpInst', as we are slicing w.r.t to that producer.
1081// For input-reuse fusion, 'srcOpInst' will be the src loop nest LoadOp which
1082// reads from the same memref as dst loop nest load ops, and 'srcStoreOpInst'
1083// will be the unique store op in the src node, which will be used to check
1084// that the write region is the same after input-reuse fusion.
Uday Bondhugulab4a14432019-01-26 00:00:501085// Returns true if it is profitable to fuse the candidate loop nests. Returns
1086// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1087// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251088// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021089// *) Computes the backward computation slice at 'srcOpInst'. This
1090// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251091// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021092// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251093// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1094// loop nest is the total number of dynamic operation instances in the loop
1095// nest).
1096// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021097// loop nest at various values of dst loop depth, attempting to fuse
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031098// the largest computation slice at the maximal dst loop depth (closest to
1099// the load) to minimize reuse distance and potentially enable subsequent
MLIR Team27d067e2019-01-16 17:55:021100// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411101// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021102// the same memref as is written by 'srcOpInst', then the union of slice
1103// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501104// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251105// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021106// NOTE: We attempt to maximize the dst loop depth, but there are cases
1107// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251108// loop (within the src computation slice) at a depth which results in
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031109// excessive recomputation (see unit tests for examples).
MLIR Team38c2fe32019-01-14 19:26:251110// *) Compares the total cost of the unfused loop nests to the min cost fused
1111// loop nest computed in the previous step, and returns true if the latter
1112// is lower.
River Riddle99b87c92019-03-27 21:02:021113static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
1114 ArrayRef<Operation *> dstLoadOpInsts,
1115 ArrayRef<Operation *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251116 ComputationSliceState *sliceState,
River Riddle400ad6f2020-04-08 19:57:021117 unsigned *dstLoopDepth, bool maximalFusion,
1118 double computeToleranceThreshold) {
Uday Bondhugula06d21d92019-01-25 01:01:491119 LLVM_DEBUG({
Uday Bondhugulaca09dab2020-05-06 06:17:161120 llvm::dbgs() << "Checking whether fusion is profitable between src op:\n";
1121 llvm::dbgs() << ' ' << *srcOpInst << " and destination op(s)\n";
MLIR Teamd7c82442019-01-30 23:53:411122 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191123 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491124 };
1125 });
Uday Bondhugula864d9e02019-01-23 17:16:241126
MLIR Team38c2fe32019-01-14 19:26:251127 // Compute cost of sliced and unsliced src loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051128 SmallVector<AffineForOp, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021129 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251130 unsigned numSrcLoopIVs = srcLoopIVs.size();
1131
1132 // Walk src loop nest and collect stats.
1133 LoopNestStats srcLoopNestStats;
Andy Davis59b68142019-06-18 15:52:091134 if (!getLoopNestStats(srcLoopIVs[0], &srcLoopNestStats))
MLIR Team38c2fe32019-01-14 19:26:251135 return false;
Andy Davis59b68142019-06-18 15:52:091136
MLIR Team38c2fe32019-01-14 19:26:251137 // Compute cost of dst loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051138 SmallVector<AffineForOp, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411139 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251140
1141 LoopNestStats dstLoopNestStats;
Andy Davis59b68142019-06-18 15:52:091142 if (!getLoopNestStats(dstLoopIVs[0], &dstLoopNestStats))
MLIR Team38c2fe32019-01-14 19:26:251143 return false;
1144
MLIR Teamd7c82442019-01-30 23:53:411145 // Compute the maximum loop depth at which we can can insert the src slice
MLIR Teamd038e342019-03-01 19:50:251146 // and still satisfy dest loop nest dependences, for producer-consumer fusion.
1147 unsigned maxDstLoopDepth =
1148 (srcOpInst == srcStoreOpInst)
1149 ? getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts)
1150 : dstLoopIVs.size();
MLIR Teamc1ff9e82019-03-06 04:33:301151 if (maxDstLoopDepth == 0) {
1152 LLVM_DEBUG(llvm::dbgs() << "Can't fuse: maxDstLoopDepth == 0 .\n");
MLIR Team27d067e2019-01-16 17:55:021153 return false;
MLIR Teamc1ff9e82019-03-06 04:33:301154 }
MLIR Team27d067e2019-01-16 17:55:021155
1156 // Search for min cost value for 'dstLoopDepth'. At each value of
1157 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1158 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1159 // of these bounds). Next the union slice bounds are used to calculate
1160 // the cost of the slice and the cost of the slice inserted into the dst
1161 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241162 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
MLIR Teamd038e342019-03-01 19:50:251163 double maxStorageReduction = 0.0;
Uday Bondhugula864d9e02019-01-23 17:16:241164 Optional<uint64_t> sliceMemEstimate = None;
1165
MLIR Team27d067e2019-01-16 17:55:021166 SmallVector<ComputationSliceState, 4> sliceStates;
1167 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241168 // The best loop depth at which to materialize the slice.
1169 Optional<unsigned> bestDstLoopDepth = None;
1170
1171 // Compute op instance count for the src loop nest without iteration slicing.
Andy Davis59b68142019-06-18 15:52:091172 uint64_t srcLoopNestCost = getComputeCost(srcLoopIVs[0], srcLoopNestStats);
Uday Bondhugula864d9e02019-01-23 17:16:241173
MLIR Teamb9dde912019-02-06 19:01:101174 // Compute src loop nest write region size.
MLIR Teamd038e342019-03-01 19:50:251175 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471176 if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251177 LLVM_DEBUG(llvm::dbgs()
River Riddle99b87c92019-03-27 21:02:021178 << "Unable to compute MemRefRegion for source operation\n.");
MLIR Teamd42ef782019-03-04 19:01:251179 return false;
1180 }
1181
MLIR Teamb9dde912019-02-06 19:01:101182 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1183 srcWriteRegion.getRegionSize();
1184 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1185 return false;
1186 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1187
Uday Bondhugula864d9e02019-01-23 17:16:241188 // Compute op instance count for the src loop nest.
Andy Davis59b68142019-06-18 15:52:091189 uint64_t dstLoopNestCost = getComputeCost(dstLoopIVs[0], dstLoopNestStats);
MLIR Team27d067e2019-01-16 17:55:021190
MLIR Teamb9dde912019-02-06 19:01:101191 // Evaluate all depth choices for materializing the slice in the destination
1192 // loop nest.
MLIR Team27d067e2019-01-16 17:55:021193 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
MLIR Teamc1ff9e82019-03-06 04:33:301194 // Compute the union of slice bounds of all ops in 'dstLoadOpInsts'.
Andy Davis1de0f972019-05-29 21:02:141195 if (failed(mlir::computeSliceUnion({srcOpInst}, dstLoadOpInsts,
Andy Davis898cf0e2019-06-17 16:59:351196 /*loopDepth=*/i,
1197 /*numCommonLoops=*/0,
1198 /*isBackwardSlice=*/true,
Andy Davis1de0f972019-05-29 21:02:141199 &sliceStates[i - 1]))) {
MLIR Teamc1ff9e82019-03-06 04:33:301200 LLVM_DEBUG(llvm::dbgs()
Andy Davis1de0f972019-05-29 21:02:141201 << "computeSliceUnion failed for loopDepth: " << i << "\n");
MLIR Teamc1ff9e82019-03-06 04:33:301202 continue;
MLIR Team38c2fe32019-01-14 19:26:251203 }
MLIR Teamc1ff9e82019-03-06 04:33:301204
Andy Davis59b68142019-06-18 15:52:091205 int64_t fusedLoopNestComputeCost;
1206 if (!getFusionComputeCost(srcLoopIVs[0], srcLoopNestStats, dstLoopIVs[0],
1207 dstLoopNestStats, &sliceStates[i - 1],
1208 &fusedLoopNestComputeCost)) {
1209 LLVM_DEBUG(llvm::dbgs() << "Unable to compute fusion compute cost.\n.");
Uday Bondhugula864d9e02019-01-23 17:16:241210 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301211 }
Uday Bondhugula864d9e02019-01-23 17:16:241212
Uday Bondhugula864d9e02019-01-23 17:16:241213 double additionalComputeFraction =
1214 fusedLoopNestComputeCost /
1215 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1216 1;
1217
Amit Sabne70a416d2019-04-09 16:17:401218 // Determine what the slice write MemRefRegion would be, if the src loop
MLIR Teamb9dde912019-02-06 19:01:101219 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1220 // nest at loop depth 'i'
MLIR Teamd038e342019-03-01 19:50:251221 MemRefRegion sliceWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471222 if (failed(sliceWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0,
1223 &sliceStates[i - 1]))) {
MLIR Teamc1ff9e82019-03-06 04:33:301224 LLVM_DEBUG(llvm::dbgs()
1225 << "Failed to compute slice write region at loopDepth: " << i
1226 << "\n");
MLIR Teamd42ef782019-03-04 19:01:251227 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301228 }
MLIR Teamd42ef782019-03-04 19:01:251229
MLIR Teamb9dde912019-02-06 19:01:101230 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1231 sliceWriteRegion.getRegionSize();
1232 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
MLIR Teamc1ff9e82019-03-06 04:33:301233 maybeSliceWriteRegionSizeBytes.getValue() == 0) {
1234 LLVM_DEBUG(llvm::dbgs()
1235 << "Failed to get slice write region size at loopDepth: " << i
1236 << "\n");
MLIR Teamb9dde912019-02-06 19:01:101237 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301238 }
MLIR Teamb9dde912019-02-06 19:01:101239 int64_t sliceWriteRegionSizeBytes =
1240 maybeSliceWriteRegionSizeBytes.getValue();
1241
MLIR Teamd038e342019-03-01 19:50:251242 // If we are fusing for reuse, check that write regions remain the same.
River Riddle9db53a12020-07-07 08:35:231243 // TODO: Write region check should check sizes and offsets in
MLIR Teamd038e342019-03-01 19:50:251244 // each dimension, so that we are sure they are covering the same memref
1245 // region. Also, move this out to a isMemRefRegionSuperSet helper function.
1246 if (srcOpInst != srcStoreOpInst &&
1247 sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes)
1248 continue;
1249
MLIR Teamb9dde912019-02-06 19:01:101250 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1251 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241252
Uday Bondhugula06d21d92019-01-25 01:01:491253 LLVM_DEBUG({
1254 std::stringstream msg;
1255 msg << " evaluating fusion profitability at depth : " << i << "\n"
Uday Bondhugulad4b3ff12019-02-27 00:10:191256 << std::fixed << std::setprecision(2)
1257 << " additional compute fraction: "
Uday Bondhugula06d21d92019-01-25 01:01:491258 << 100.0 * additionalComputeFraction << "%\n"
1259 << " storage reduction factor: " << storageReduction << "x\n"
1260 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191261 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1262 << " slice write region size: " << sliceWriteRegionSizeBytes
1263 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491264 llvm::dbgs() << msg.str();
1265 });
Uday Bondhugula864d9e02019-01-23 17:16:241266
River Riddle9db53a12020-07-07 08:35:231267 // TODO: This is a placeholder cost model.
Uday Bondhugula864d9e02019-01-23 17:16:241268 // Among all choices that add an acceptable amount of redundant computation
1269 // (as per computeToleranceThreshold), we will simply pick the one that
1270 // reduces the intermediary size the most.
1271 if ((storageReduction > maxStorageReduction) &&
Uday Bondhugulace7e59532019-03-08 17:21:521272 (maximalFusion ||
Uday Bondhugula864d9e02019-01-23 17:16:241273 (additionalComputeFraction < computeToleranceThreshold))) {
1274 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021275 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241276 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101277 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251278 }
1279 }
1280
Uday Bondhugula864d9e02019-01-23 17:16:241281 // A simple cost model: fuse if it reduces the memory footprint. If
1282 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251283
Uday Bondhugulace7e59532019-03-08 17:21:521284 if (!maximalFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191285 LLVM_DEBUG(
1286 llvm::dbgs()
1287 << "All fusion choices involve more than the threshold amount of "
1288 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251289 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241290 }
1291
MLIR Teamd42ef782019-03-04 19:01:251292 if (!bestDstLoopDepth.hasValue()) {
1293 LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n");
1294 return false;
1295 }
Uday Bondhugula864d9e02019-01-23 17:16:241296
1297 // Set dstLoopDepth based on best values from search.
1298 *dstLoopDepth = bestDstLoopDepth.getValue();
1299
1300 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491301 llvm::dbgs() << " LoopFusion fusion stats:"
1302 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241303 << "\n src loop nest compute cost: " << srcLoopNestCost
1304 << "\n dst loop nest compute cost: " << dstLoopNestCost
1305 << "\n fused loop nest compute cost: "
1306 << minFusedLoopNestComputeCost << "\n");
1307
River Riddle5052bd82019-02-02 00:42:181308 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1309 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241310
1311 Optional<double> storageReduction = None;
1312
Uday Bondhugulace7e59532019-03-08 17:21:521313 if (!maximalFusion) {
Uday Bondhugula864d9e02019-01-23 17:16:241314 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1315 LLVM_DEBUG(
1316 llvm::dbgs()
1317 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1318 return false;
1319 }
1320
1321 auto srcMemSizeVal = srcMemSize.getValue();
1322 auto dstMemSizeVal = dstMemSize.getValue();
1323
1324 assert(sliceMemEstimate.hasValue() && "expected value");
Uday Bondhugula864d9e02019-01-23 17:16:241325 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1326
1327 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1328 << " dst mem: " << dstMemSizeVal << "\n"
1329 << " fused mem: " << fusedMem << "\n"
1330 << " slice mem: " << sliceMemEstimate << "\n");
1331
Jacques Pienaar2fe8ae42019-05-04 02:48:571332 if (static_cast<long>(fusedMem) > srcMemSizeVal + dstMemSizeVal) {
Uday Bondhugula864d9e02019-01-23 17:16:241333 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1334 return false;
1335 }
1336 storageReduction =
1337 100.0 *
1338 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1339 }
1340
1341 double additionalComputeFraction =
1342 100.0 * (minFusedLoopNestComputeCost /
1343 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1344 1);
MLIR Team5c5739d2019-01-25 06:27:401345 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491346 LLVM_DEBUG({
1347 std::stringstream msg;
1348 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591349 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491350 << "% redundant computation and a ";
1351 msg << (storageReduction.hasValue()
1352 ? std::to_string(storageReduction.getValue())
1353 : "<unknown>");
1354 msg << "% storage reduction.\n";
1355 llvm::dbgs() << msg.str();
1356 });
Uday Bondhugula864d9e02019-01-23 17:16:241357
MLIR Team27d067e2019-01-16 17:55:021358 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241359 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021360 sliceState->lbs = bestSliceState->lbs;
1361 sliceState->ubs = bestSliceState->ubs;
1362 sliceState->lbOperands = bestSliceState->lbOperands;
1363 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241364
MLIR Team27d067e2019-01-16 17:55:021365 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251366 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171367 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021368 canonicalizeMapAndOperands(&sliceState->lbs[i],
1369 &sliceState->lbOperands[i]);
1370 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171371 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021372 canonicalizeMapAndOperands(&sliceState->ubs[i],
1373 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251374 }
1375 }
1376 return true;
1377}
1378
River Riddle2666b972019-12-18 18:46:161379namespace {
1380
MLIR Teamd038e342019-03-01 19:50:251381// GreedyFusion greedily fuses loop nests which have a producer/consumer or
1382// input-reuse relationship on a memref, with the goal of improving locality.
MLIR Teamf28e4df2018-11-01 14:26:001383//
MLIR Teamd038e342019-03-01 19:50:251384// The steps of the producer-consumer fusion algorithm are as follows:
MLIR Team3b692302018-12-17 17:57:141385//
MLIR Team6892ffb2018-12-20 04:42:551386// *) A worklist is initialized with node ids from the dependence graph.
1387// *) For each node id in the worklist:
Amit Sabne70a416d2019-04-09 16:17:401388// *) Pop an AffineForOp of the worklist. This 'dstAffineForOp' will be a
River Riddle5052bd82019-02-02 00:42:181389// candidate destination AffineForOp into which fusion will be attempted.
1390// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141391// *) For each LoadOp in 'dstLoadOps' do:
Amit Sabne70a416d2019-04-09 16:17:401392// *) Look up dependent loop nests which have a single store op to the same
MLIR Teamd038e342019-03-01 19:50:251393// memref.
1394// *) Check if dependences would be violated by the fusion.
MLIR Team6892ffb2018-12-20 04:42:551395// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141396// bounds to be functions of 'dstLoopNest' IVs and symbols.
1397// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
MLIR Teamd038e342019-03-01 19:50:251398// at a loop depth determined by the cost model in 'isFusionProfitable'.
River Riddle99b87c92019-03-27 21:02:021399// *) Add the newly fused load/store operations to the state,
Amit Sabne70a416d2019-04-09 16:17:401400// and also add newly fused load ops to 'dstLoopOps' to be considered
MLIR Team3b692302018-12-17 17:57:141401// as fusion dst load ops in another iteration.
1402// *) Remove old src loop nest and its associated state.
1403//
MLIR Teamd038e342019-03-01 19:50:251404// The steps of the input-reuse fusion algorithm are as follows:
1405//
1406// *) Initialize 'worklist' with node ids from the dependence graph.
1407// *) For each 'dstNode' in the worklist:
1408// *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which
1409// loads from the same memref, but which has no dependence paths to/from.
1410// *) Get a computation slice of 'sibLoopNest', which adjusts its loop
1411// bounds to be functions of 'dstLoopNest' IVs and symbols.
1412// *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest',
1413// at a loop depth determined by the cost model in 'isFusionProfitable'.
1414// This function also checks that the memref write region of 'sibLoopNest',
1415// is preserved in the fused loop nest.
1416// *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'.
1417//
River Riddle99b87c92019-03-27 21:02:021418// Given a graph where top-level operations are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141419// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551420// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141421//
MLIR Team6892ffb2018-12-20 04:42:551422// This greedy algorithm is not 'maximal' due to the current restriction of
River Riddle9db53a12020-07-07 08:35:231423// fusing along single producer consumer edges, but there is a TODO: to fix
1424// this.
MLIR Team3b692302018-12-17 17:57:141425//
River Riddle9db53a12020-07-07 08:35:231426// TODO: Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551427struct GreedyFusion {
1428public:
MLIR Teamd038e342019-03-01 19:50:251429 // The data dependence graph to traverse during fusion.
MLIR Team6892ffb2018-12-20 04:42:551430 MemRefDependenceGraph *mdg;
MLIR Teamd038e342019-03-01 19:50:251431 // Worklist of graph nodes visited during the fusion pass.
MLIR Teama78edcd2019-02-05 14:57:081432 SmallVector<unsigned, 8> worklist;
MLIR Teamd038e342019-03-01 19:50:251433 // Set of graph nodes which are present on the worklist.
MLIR Teama78edcd2019-02-05 14:57:081434 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamd038e342019-03-01 19:50:251435 // Parameter for local buffer size threshold.
1436 unsigned localBufSizeThreshold;
1437 // Parameter for fast memory space.
1438 Optional<unsigned> fastMemorySpace;
Uday Bondhugulace7e59532019-03-08 17:21:521439 // If true, ignore any additional (redundant) computation tolerance threshold
1440 // that would have prevented fusion.
1441 bool maximalFusion;
River Riddle400ad6f2020-04-08 19:57:021442 // The amount of additional computation that is tolerated while fusing
1443 // pair-wise as a fraction of the total computation.
1444 double computeToleranceThreshold;
MLIR Teamf28e4df2018-11-01 14:26:001445
MLIR Teamd038e342019-03-01 19:50:251446 using Node = MemRefDependenceGraph::Node;
1447
1448 GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold,
River Riddle400ad6f2020-04-08 19:57:021449 Optional<unsigned> fastMemorySpace, bool maximalFusion,
1450 double computeToleranceThreshold)
MLIR Teamd038e342019-03-01 19:50:251451 : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold),
River Riddle400ad6f2020-04-08 19:57:021452 fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion),
1453 computeToleranceThreshold(computeToleranceThreshold) {}
MLIR Teamd038e342019-03-01 19:50:251454
1455 // Initializes 'worklist' with nodes from 'mdg'
1456 void init() {
River Riddle9db53a12020-07-07 08:35:231457 // TODO: Add a priority queue for prioritizing nodes by different
MLIR Teama78edcd2019-02-05 14:57:081458 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Teamd038e342019-03-01 19:50:251459 worklist.clear();
1460 worklistSet.clear();
1461 for (auto &idAndNode : mdg->nodes) {
1462 const Node &node = idAndNode.second;
1463 worklist.push_back(node.id);
1464 worklistSet.insert(node.id);
1465 }
MLIR Team6892ffb2018-12-20 04:42:551466 }
MLIR Team3b692302018-12-17 17:57:141467
MLIR Teamd038e342019-03-01 19:50:251468 // Run the GreedyFusion pass.
1469 // *) First pass through the nodes fuses single-use producer nodes into their
1470 // unique consumer.
1471 // *) Second pass fuses sibling nodes which share no dependence edges.
1472 // *) Third pass fuses any remaining producer nodes into their users.
1473 void run() {
River Riddle9db53a12020-07-07 08:35:231474 // TODO: Run this repeatedly until a fixed-point is reached.
MLIR Teamd038e342019-03-01 19:50:251475 fuseProducerConsumerNodes(/*maxSrcUserCount=*/1);
1476 fuseSiblingNodes();
1477 fuseProducerConsumerNodes(
1478 /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max());
1479 eraseUnusedMemRefAllocations();
1480 }
1481
1482 void fuseProducerConsumerNodes(unsigned maxSrcUserCount) {
1483 init();
MLIR Team3b692302018-12-17 17:57:141484 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551485 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141486 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081487 worklistSet.erase(dstId);
1488
MLIR Team6892ffb2018-12-20 04:42:551489 // Skip if this node was removed (fused into another node).
1490 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141491 continue;
MLIR Team6892ffb2018-12-20 04:42:551492 // Get 'dstNode' into which to attempt fusion.
1493 auto *dstNode = mdg->getNode(dstId);
1494 // Skip if 'dstNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541495 if (!isa<AffineForOp>(dstNode->op))
MLIR Team3b692302018-12-17 17:57:141496 continue;
MLIR Team8f5f2c72019-02-15 17:32:181497 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1498 // while preserving relative order. This can increase the maximum loop
1499 // depth at which we can fuse a slice of a producer loop nest into a
1500 // consumer loop nest.
1501 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141502
River Riddle99b87c92019-03-27 21:02:021503 SmallVector<Operation *, 4> loads = dstNode->loads;
1504 SmallVector<Operation *, 4> dstLoadOpInsts;
River Riddlee62a6952019-12-23 22:45:011505 DenseSet<Value> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551506 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021507 // Get memref of load on top of the stack.
Diego Caballeroa45fb192020-05-20 00:16:041508 auto memref = cast<AffineReadOpInterface>(loads.back()).getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271509 if (visitedMemrefs.count(memref) > 0)
1510 continue;
1511 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021512 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1513 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551514 // Skip if no input edges along which to fuse.
1515 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141516 continue;
Amit Sabne70a416d2019-04-09 16:17:401517 // Iterate through in-edges for 'dstId' and src node id for any
MLIR Team1e851912019-01-31 00:01:461518 // edges on 'memref'.
1519 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551520 for (auto &srcEdge : mdg->inEdges[dstId]) {
1521 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411522 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551523 continue;
MLIR Team1e851912019-01-31 00:01:461524 srcNodeIds.push_back(srcEdge.id);
1525 }
1526 for (unsigned srcId : srcNodeIds) {
1527 // Skip if this node was removed (fused into another node).
1528 if (mdg->nodes.count(srcId) == 0)
1529 continue;
1530 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1531 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551532 // Skip if 'srcNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541533 if (!isa<AffineForOp>(srcNode->op))
MLIR Team6892ffb2018-12-20 04:42:551534 continue;
Diego Caballero34510552019-10-09 17:36:541535 // Skip if 'srcNode' has more than one live-out store to a
1536 // function-local memref.
River Riddle9db53a12020-07-07 08:35:231537 // TODO: Support more generic multi-output src loop nests
Diego Caballero34510552019-10-09 17:36:541538 // fusion.
1539 auto srcStoreOp = mdg->getUniqueOutgoingStore(srcNode);
Andy Davis68a8da42019-11-18 19:20:031540 if (!srcStoreOp) {
1541 // Get the src store op at the deepest loop depth.
1542 // We will use 'LoopFusionUtils::canFuseLoops' to check fusion
1543 // feasibility for loops with multiple stores.
1544 unsigned maxLoopDepth = 0;
1545 for (auto *op : srcNode->stores) {
Diego Caballeroa45fb192020-05-20 00:16:041546 auto storeOp = cast<AffineWriteOpInterface>(op);
Andy Davis68a8da42019-11-18 19:20:031547 if (storeOp.getMemRef() != memref) {
1548 srcStoreOp = nullptr;
1549 break;
1550 }
Uday Bondhugula42ada5f2020-04-13 04:48:101551 unsigned loopDepth = getNestingDepth(storeOp);
Andy Davis68a8da42019-11-18 19:20:031552 if (loopDepth > maxLoopDepth) {
1553 maxLoopDepth = loopDepth;
1554 srcStoreOp = storeOp;
1555 }
1556 }
1557 if (!srcStoreOp)
1558 continue;
1559 }
1560
Diego Caballero34510552019-10-09 17:36:541561 // Unique outgoing store found must write to 'memref' since 'memref'
1562 // is the one that established the producer-consumer relationship
1563 // between 'srcNode' and 'dstNode'.
1564 assert(srcStoreOp.getMemRef() == memref &&
1565 "Found store to unexpected memref");
Uday Bondhugula864d9e02019-01-23 17:16:241566
MLIR Team58aa3832019-02-16 01:12:191567 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1568 // and cannot be fused.
1569 bool writesToLiveInOrOut =
1570 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1571 if (writesToLiveInOrOut &&
Diego Caballero34510552019-10-09 17:36:541572 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, srcStoreOp, mdg))
MLIR Teamd7c82442019-01-30 23:53:411573 continue;
1574
Kazuaki Ishizaki84a61822019-12-06 13:58:591575 // Don't create a private memref if 'writesToLiveInOrOut'.
Andy Davis68a8da42019-11-18 19:20:031576 bool createPrivateMemref = !writesToLiveInOrOut;
Kazuaki Ishizaki84a61822019-12-06 13:58:591577 // Don't create a private memref if 'srcNode' has in edges on
1578 // 'memref', or if 'dstNode' has out edges on 'memref'.
Andy Davis68a8da42019-11-18 19:20:031579 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) > 0 ||
1580 mdg->getOutEdgeCount(dstNode->id, memref) > 0) {
1581 createPrivateMemref = false;
1582 }
1583
MLIR Teamd038e342019-03-01 19:50:251584 // Skip if 'srcNode' out edge count on 'memref' > 'maxSrcUserCount'.
1585 if (mdg->getOutEdgeCount(srcNode->id, memref) > maxSrcUserCount)
1586 continue;
1587
River Riddle99b87c92019-03-27 21:02:021588 // Compute an operation list insertion point for the fused loop
MLIR Teama0f3db402019-01-29 17:36:411589 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:021590 Operation *insertPointInst =
MLIR Teama78edcd2019-02-05 14:57:081591 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411592 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551593 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241594
Andy Davis68a8da42019-11-18 19:20:031595 // Compute the innermost common loop depth for dstNode loads/stores.
1596 SmallVector<Operation *, 2> dstOps(dstNode->loads.begin(),
1597 dstNode->loads.end());
1598 dstOps.append(dstNode->stores.begin(), dstNode->stores.end());
1599 unsigned dstLoopDepthTest = getInnermostCommonLoopDepth(dstOps);
1600 // Check the feasibility of fusing src loop nest into dst loop nest
1601 // at loop depths in range [1, dstLoopDepthTest].
River Riddle9db53a12020-07-07 08:35:231602 // TODO: Use slice union computation and union of memref
Andy Davis68a8da42019-11-18 19:20:031603 // read/write regions to cost model and fusion.
1604 bool canFuse = false;
1605 for (unsigned i = 1; i <= dstLoopDepthTest; ++i) {
1606 ComputationSliceState sliceUnion;
1607 FusionResult result = mlir::canFuseLoops(
1608 cast<AffineForOp>(srcNode->op), cast<AffineForOp>(dstNode->op),
1609 /*dstLoopDepth=*/i, &sliceUnion);
1610 if (result.value == FusionResult::Success)
1611 canFuse = true;
1612 }
1613
1614 // Skip if fusion is not feasible at all loop depths.
1615 if (!canFuse)
1616 continue;
1617
MLIR Teamd7c82442019-01-30 23:53:411618 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021619 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411620 for (auto *storeOpInst : dstNode->stores)
Diego Caballeroa45fb192020-05-20 00:16:041621 if (cast<AffineWriteOpInterface>(storeOpInst).getMemRef() == memref)
MLIR Teamd7c82442019-01-30 23:53:411622 dstStoreOpInsts.push_back(storeOpInst);
1623
Uday Bondhugulab4a14432019-01-26 00:00:501624 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251625 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411626 // Check if fusion would be profitable.
Diego Caballero34510552019-10-09 17:36:541627 if (!isFusionProfitable(srcStoreOp, srcStoreOp, dstLoadOpInsts,
1628 dstStoreOpInsts, &sliceState,
River Riddle400ad6f2020-04-08 19:57:021629 &bestDstLoopDepth, maximalFusion,
1630 computeToleranceThreshold))
MLIR Team38c2fe32019-01-14 19:26:251631 continue;
Andy Davis68a8da42019-11-18 19:20:031632
MLIR Team6892ffb2018-12-20 04:42:551633 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181634 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Diego Caballero34510552019-10-09 17:36:541635 srcStoreOp, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
Chris Lattnerd9b5bc82019-03-25 02:53:051636 if (sliceLoopNest) {
River Riddleaf1abcc2019-03-25 18:13:311637 LLVM_DEBUG(llvm::dbgs() << "\tslice loop nest:\n"
River Riddlef9d91532019-03-27 00:05:091638 << *sliceLoopNest.getOperation() << "\n");
River Riddle5052bd82019-02-02 00:42:181639 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleadca3c22019-05-12 00:57:321640 auto dstAffineForOp = cast<AffineForOp>(dstNode->op);
River Riddlef9d91532019-03-27 00:05:091641 if (insertPointInst != dstAffineForOp.getOperation()) {
1642 dstAffineForOp.getOperation()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411643 }
MLIR Teamc4237ae2019-01-18 16:56:271644 // Update edges between 'srcNode' and 'dstNode'.
Andy Davis68a8da42019-11-18 19:20:031645 mdg->updateEdges(srcNode->id, dstNode->id, memref,
1646 createPrivateMemref);
MLIR Teamc4237ae2019-01-18 16:56:271647
1648 // Collect slice loop stats.
1649 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:091650 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271651 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181652 for (auto forOp : sliceCollector.forOps) {
1653 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551654 }
Andy Davis68a8da42019-11-18 19:20:031655 if (createPrivateMemref) {
MLIR Team58aa3832019-02-16 01:12:191656 // Create private memref for 'memref' in 'dstAffineForOp'.
River Riddle99b87c92019-03-27 21:02:021657 SmallVector<Operation *, 4> storesForMemref;
MLIR Team58aa3832019-02-16 01:12:191658 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
Diego Caballeroa45fb192020-05-20 00:16:041659 if (cast<AffineWriteOpInterface>(storeOpInst).getMemRef() ==
1660 memref)
MLIR Team58aa3832019-02-16 01:12:191661 storesForMemref.push_back(storeOpInst);
1662 }
River Riddle9db53a12020-07-07 08:35:231663 // TODO: Use union of memref write regions to compute
Andy Davis68a8da42019-11-18 19:20:031664 // private memref footprint.
River Riddle35807bc2019-12-23 05:59:551665 auto newMemRef = createPrivateMemRef(
MLIR Team58aa3832019-02-16 01:12:191666 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1667 fastMemorySpace, localBufSizeThreshold);
1668 visitedMemrefs.insert(newMemRef);
1669 // Create new node in dependence graph for 'newMemRef' alloc op.
1670 unsigned newMemRefNodeId =
River Riddle2bdf33c2020-01-11 16:54:041671 mdg->addNode(newMemRef.getDefiningOp());
MLIR Team58aa3832019-02-16 01:12:191672 // Add edge from 'newMemRef' node to dstNode.
1673 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271674 }
MLIR Teamc4237ae2019-01-18 16:56:271675
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031676 // Collect dst loop stats after memref privatization transformation.
MLIR Teamc4237ae2019-01-18 16:56:271677 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:091678 dstLoopCollector.collect(dstAffineForOp.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271679
1680 // Add new load ops to current Node load op list 'loads' to
1681 // continue fusing based on new operands.
1682 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
Uday Bondhugula2affcd62020-05-07 03:51:111683 // NOTE: Change 'loads' to a hash set in case efficiency is an
1684 // issue. We still use a vector since it's expected to be small.
Diego Caballero2e7a0842020-06-11 21:39:441685 if (!llvm::is_contained(loads, loadOpInst))
MLIR Teamc4237ae2019-01-18 16:56:271686 loads.push_back(loadOpInst);
1687 }
Diego Caballero2e7a0842020-06-11 21:39:441688 // Clear visited memrefs after fusion so that previously visited src
1689 // nodes are considered for fusion again in the context of the new
1690 // fused node.
1691 // TODO: This shouldn't be necessary if we visited candidates in the
1692 // dependence graph in post-order or once we fully support
1693 // multi-store producers. Currently, in a multi-store producer
1694 // scenario such as A->B, A->C, B->C, we fail to fuse A+B due to the
1695 // multiple outgoing edges. However, after fusing B+C, A has a
1696 // single outgoing edge and can be fused if we revisit it in the
1697 // context of the new fused B+C node.
1698 visitedMemrefs.clear();
MLIR Teamc4237ae2019-01-18 16:56:271699
Amit Sabne70a416d2019-04-09 16:17:401700 // Clear and add back loads and stores.
MLIR Teamc4237ae2019-01-18 16:56:271701 mdg->clearNodeLoadAndStores(dstNode->id);
1702 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1703 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371704 // Remove old src loop nest if it no longer has outgoing dependence
Amit Sabne70a416d2019-04-09 16:17:401705 // edges, and if it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191706 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1707 // been fused into 'dstNode' and write region of 'dstNode' covers
1708 // the write region of 'srcNode', and 'srcNode' has no other users
1709 // so it is safe to remove.
1710 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271711 mdg->removeNode(srcNode->id);
River Riddle99b87c92019-03-27 21:02:021712 srcNode->op->erase();
MLIR Teama78edcd2019-02-05 14:57:081713 } else {
1714 // Add remaining users of 'oldMemRef' back on the worklist (if not
1715 // already there), as its replacement with a local/private memref
1716 // has reduced dependences on 'oldMemRef' which may have created
1717 // new fusion opportunities.
1718 if (mdg->outEdges.count(srcNode->id) > 0) {
1719 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1720 mdg->outEdges[srcNode->id];
1721 for (auto &outEdge : oldOutEdges) {
1722 if (outEdge.value == memref &&
1723 worklistSet.count(outEdge.id) == 0) {
1724 worklist.push_back(outEdge.id);
1725 worklistSet.insert(outEdge.id);
1726 }
1727 }
1728 }
MLIR Teamc4237ae2019-01-18 16:56:271729 }
MLIR Team3b692302018-12-17 17:57:141730 }
MLIR Team3b692302018-12-17 17:57:141731 }
1732 }
1733 }
MLIR Teamd038e342019-03-01 19:50:251734 }
1735
1736 // Visits each node in the graph, and for each node, attempts to fuse it with
1737 // its sibling nodes (nodes which share a parent, but no dependence edges).
1738 void fuseSiblingNodes() {
1739 init();
1740 while (!worklist.empty()) {
1741 unsigned dstId = worklist.back();
1742 worklist.pop_back();
1743 worklistSet.erase(dstId);
1744
1745 // Skip if this node was removed (fused into another node).
1746 if (mdg->nodes.count(dstId) == 0)
1747 continue;
1748 // Get 'dstNode' into which to attempt fusion.
1749 auto *dstNode = mdg->getNode(dstId);
1750 // Skip if 'dstNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541751 if (!isa<AffineForOp>(dstNode->op))
MLIR Teamd038e342019-03-01 19:50:251752 continue;
1753 // Attempt to fuse 'dstNode' with its sibling nodes in the graph.
1754 fuseWithSiblingNodes(dstNode);
1755 }
1756 }
1757
1758 // Attempt to fuse 'dstNode' with sibling nodes in the graph.
1759 void fuseWithSiblingNodes(Node *dstNode) {
1760 DenseSet<unsigned> visitedSibNodeIds;
River Riddlee62a6952019-12-23 22:45:011761 std::pair<unsigned, Value> idAndMemref;
MLIR Teamd038e342019-03-01 19:50:251762 while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) {
1763 unsigned sibId = idAndMemref.first;
River Riddlee62a6952019-12-23 22:45:011764 Value memref = idAndMemref.second;
River Riddle9db53a12020-07-07 08:35:231765 // TODO: Check that 'sibStoreOpInst' post-dominates all other
MLIR Teamd038e342019-03-01 19:50:251766 // stores to the same memref in 'sibNode' loop nest.
1767 auto *sibNode = mdg->getNode(sibId);
River Riddle99b87c92019-03-27 21:02:021768 // Compute an operation list insertion point for the fused loop
MLIR Teamd038e342019-03-01 19:50:251769 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:021770 assert(sibNode->op->getBlock() == dstNode->op->getBlock());
1771 Operation *insertPointInst =
1772 sibNode->op->isBeforeInBlock(dstNode->op)
MLIR Teamd038e342019-03-01 19:50:251773 ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id)
1774 : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id);
1775 if (insertPointInst == nullptr)
1776 continue;
1777
1778 // Check if fusion would be profitable and at what depth.
1779
1780 // Get unique 'sibNode' load op to 'memref'.
River Riddle99b87c92019-03-27 21:02:021781 SmallVector<Operation *, 2> sibLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:251782 sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts);
1783 // Currently findSiblingNodeToFuse searches for siblings with one load.
1784 assert(sibLoadOpInsts.size() == 1);
River Riddle99b87c92019-03-27 21:02:021785 Operation *sibLoadOpInst = sibLoadOpInsts[0];
MLIR Teamd038e342019-03-01 19:50:251786 assert(!sibNode->stores.empty());
River Riddle9db53a12020-07-07 08:35:231787 // TODO: Choose the store which postdominates all other stores.
MLIR Teamd038e342019-03-01 19:50:251788 auto *sibStoreOpInst = sibNode->stores.back();
1789
1790 // Gather 'dstNode' load ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021791 SmallVector<Operation *, 2> dstLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:251792 dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts);
1793
1794 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021795 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd038e342019-03-01 19:50:251796 dstNode->getStoreOpsForMemref(memref, &dstStoreOpInsts);
1797
1798 unsigned bestDstLoopDepth;
1799 mlir::ComputationSliceState sliceState;
1800
1801 // Check if fusion would be profitable.
1802 if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstLoadOpInsts,
Uday Bondhugulace7e59532019-03-08 17:21:521803 dstStoreOpInsts, &sliceState, &bestDstLoopDepth,
River Riddle400ad6f2020-04-08 19:57:021804 maximalFusion, computeToleranceThreshold))
MLIR Teamd038e342019-03-01 19:50:251805 continue;
1806
1807 // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'.
1808 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
1809 sibLoadOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
1810 if (sliceLoopNest != nullptr) {
River Riddleadca3c22019-05-12 00:57:321811 auto dstForInst = cast<AffineForOp>(dstNode->op);
River Riddle99b87c92019-03-27 21:02:021812 // Update operation position of fused loop nest (if needed).
River Riddlef9d91532019-03-27 00:05:091813 if (insertPointInst != dstForInst.getOperation()) {
1814 dstForInst.getOperation()->moveBefore(insertPointInst);
MLIR Teamd038e342019-03-01 19:50:251815 }
1816 // Update data dependence graph state post fusion.
1817 updateStateAfterSiblingFusion(sliceLoopNest, sibNode, dstNode);
1818 }
1819 }
1820 }
1821
MLIR Team9d30b362019-03-29 15:06:251822 // Searches function argument uses and the graph from 'dstNode' looking for a
1823 // fusion candidate sibling node which shares no dependences with 'dstNode'
1824 // but which loads from the same memref. Returns true and sets
1825 // 'idAndMemrefToFuse' on success. Returns false otherwise.
MLIR Teamd038e342019-03-01 19:50:251826 bool findSiblingNodeToFuse(Node *dstNode,
1827 DenseSet<unsigned> *visitedSibNodeIds,
River Riddlee62a6952019-12-23 22:45:011828 std::pair<unsigned, Value> *idAndMemrefToFuse) {
MLIR Team9d30b362019-03-29 15:06:251829 // Returns true if 'sibNode' can be fused with 'dstNode' for input reuse
1830 // on 'memref'.
River Riddlee62a6952019-12-23 22:45:011831 auto canFuseWithSibNode = [&](Node *sibNode, Value memref) {
MLIR Team9d30b362019-03-29 15:06:251832 // Skip if 'outEdge' is not a read-after-write dependence.
River Riddle9db53a12020-07-07 08:35:231833 // TODO: Remove restrict to single load op restriction.
MLIR Team9d30b362019-03-29 15:06:251834 if (sibNode->getLoadOpCount(memref) != 1)
1835 return false;
1836 // Skip if there exists a path of dependent edges between
1837 // 'sibNode' and 'dstNode'.
1838 if (mdg->hasDependencePath(sibNode->id, dstNode->id) ||
1839 mdg->hasDependencePath(dstNode->id, sibNode->id))
1840 return false;
1841 // Skip sib node if it loads to (and stores from) the same memref on
1842 // which it also has an input dependence edge.
River Riddlee62a6952019-12-23 22:45:011843 DenseSet<Value> loadAndStoreMemrefSet;
MLIR Team9d30b362019-03-29 15:06:251844 sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet);
River Riddlee62a6952019-12-23 22:45:011845 if (llvm::any_of(loadAndStoreMemrefSet, [=](Value memref) {
MLIR Team9d30b362019-03-29 15:06:251846 return mdg->getIncomingMemRefAccesses(sibNode->id, memref) > 0;
1847 }))
1848 return false;
1849
1850 // Check that all stores are to the same memref.
River Riddlee62a6952019-12-23 22:45:011851 DenseSet<Value> storeMemrefs;
MLIR Team9d30b362019-03-29 15:06:251852 for (auto *storeOpInst : sibNode->stores) {
Diego Caballeroa45fb192020-05-20 00:16:041853 storeMemrefs.insert(
1854 cast<AffineWriteOpInterface>(storeOpInst).getMemRef());
MLIR Team9d30b362019-03-29 15:06:251855 }
1856 if (storeMemrefs.size() != 1)
1857 return false;
Tung D. Le2b5d1772020-06-24 16:56:051858
1859 // Skip if a memref value in one node is used by a non-affine memref
1860 // access that lies between 'dstNode' and 'sibNode'.
1861 if (hasNonAffineUsersOnThePath(dstNode->id, sibNode->id, mdg) ||
1862 hasNonAffineUsersOnThePath(sibNode->id, dstNode->id, mdg))
1863 return false;
MLIR Team9d30b362019-03-29 15:06:251864 return true;
1865 };
1866
1867 // Search for siblings which load the same memref function argument.
River Riddlece502af2019-07-08 18:20:261868 auto fn = dstNode->op->getParentOfType<FuncOp>();
River Riddle54cd6a72019-07-01 17:29:091869 for (unsigned i = 0, e = fn.getNumArguments(); i != e; ++i) {
River Riddle2bdf33c2020-01-11 16:54:041870 for (auto *user : fn.getArgument(i).getUsers()) {
Diego Caballeroa45fb192020-05-20 00:16:041871 if (auto loadOp = dyn_cast<AffineReadOpInterface>(user)) {
MLIR Team9d30b362019-03-29 15:06:251872 // Gather loops surrounding 'use'.
1873 SmallVector<AffineForOp, 4> loops;
River Riddle8780d8d2019-05-18 18:09:071874 getLoopIVs(*user, &loops);
MLIR Team9d30b362019-03-29 15:06:251875 // Skip 'use' if it is not within a loop nest.
1876 if (loops.empty())
1877 continue;
1878 Node *sibNode = mdg->getForOpNode(loops[0]);
1879 assert(sibNode != nullptr);
1880 // Skip 'use' if it not a sibling to 'dstNode'.
1881 if (sibNode->id == dstNode->id)
1882 continue;
1883 // Skip 'use' if it has been visited.
1884 if (visitedSibNodeIds->count(sibNode->id) > 0)
1885 continue;
1886 // Skip 'use' if it does not load from the same memref as 'dstNode'.
River Riddle35807bc2019-12-23 05:59:551887 auto memref = loadOp.getMemRef();
MLIR Team9d30b362019-03-29 15:06:251888 if (dstNode->getLoadOpCount(memref) == 0)
1889 continue;
1890 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1891 if (canFuseWithSibNode(sibNode, memref)) {
1892 visitedSibNodeIds->insert(sibNode->id);
1893 idAndMemrefToFuse->first = sibNode->id;
1894 idAndMemrefToFuse->second = memref;
1895 return true;
1896 }
1897 }
1898 }
1899 }
1900
1901 // Search for siblings by following edges through an intermediate src node.
MLIR Teamd038e342019-03-01 19:50:251902 // Collect candidate 'dstNode' input edges in 'inEdges'.
1903 SmallVector<MemRefDependenceGraph::Edge, 2> inEdges;
1904 mdg->forEachMemRefInputEdge(
1905 dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) {
1906 // Add 'inEdge' if it is a read-after-write dependence.
1907 if (dstNode->getLoadOpCount(inEdge.value) > 0 &&
1908 mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0)
1909 inEdges.push_back(inEdge);
1910 });
1911
1912 // Search for sibling nodes to fuse by visiting output edges from each input
1913 // edge in 'inEdges'.
1914 for (auto &inEdge : inEdges) {
1915 // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'.
1916 SmallVector<MemRefDependenceGraph::Edge, 2> outEdges;
1917 mdg->forEachMemRefOutputEdge(
1918 inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) {
1919 unsigned sibNodeId = outEdge.id;
1920 if (visitedSibNodeIds->count(sibNodeId) > 0)
1921 return;
1922 // Skip output edge if not a sibling using the same memref.
1923 if (outEdge.id == dstNode->id || outEdge.value != inEdge.value)
1924 return;
1925 auto *sibNode = mdg->getNode(sibNodeId);
River Riddled5b60ee82019-05-12 01:59:541926 if (!isa<AffineForOp>(sibNode->op))
MLIR Teamd038e342019-03-01 19:50:251927 return;
MLIR Team9d30b362019-03-29 15:06:251928 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1929 if (canFuseWithSibNode(sibNode, outEdge.value)) {
1930 // Add candidate 'outEdge' to sibling node.
1931 outEdges.push_back(outEdge);
MLIR Teamd038e342019-03-01 19:50:251932 }
MLIR Teamd038e342019-03-01 19:50:251933 });
1934
1935 // Add first candidate if any were returned.
1936 if (!outEdges.empty()) {
1937 visitedSibNodeIds->insert(outEdges[0].id);
1938 idAndMemrefToFuse->first = outEdges[0].id;
1939 idAndMemrefToFuse->second = outEdges[0].value;
1940 return true;
1941 }
1942 }
1943 return false;
1944 }
1945
Chris Lattnerd9b5bc82019-03-25 02:53:051946 void updateStateAfterSiblingFusion(AffineForOp sliceLoopNest, Node *sibNode,
1947 Node *dstNode) {
MLIR Teamd038e342019-03-01 19:50:251948 // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion.
1949 mdg->updateEdges(sibNode->id, dstNode->id);
1950
1951 // Collect slice loop stats.
1952 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:091953 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamd038e342019-03-01 19:50:251954 // Promote single iteration slice loops to single IV value.
1955 for (auto forOp : sliceCollector.forOps) {
1956 promoteIfSingleIteration(forOp);
1957 }
1958
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031959 // Collect dst loop stats after memref privatization transformation.
River Riddleadca3c22019-05-12 00:57:321960 auto dstForInst = cast<AffineForOp>(dstNode->op);
MLIR Teamd038e342019-03-01 19:50:251961 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:091962 dstLoopCollector.collect(dstForInst.getOperation());
MLIR Teamd038e342019-03-01 19:50:251963 // Clear and add back loads and stores
1964 mdg->clearNodeLoadAndStores(dstNode->id);
1965 mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts,
1966 dstLoopCollector.storeOpInsts);
1967 // Remove old sibling loop nest if it no longer has outgoing dependence
1968 // edges, and it does not write to a memref which escapes the
1969 // function.
1970 if (mdg->getOutEdgeCount(sibNode->id) == 0) {
1971 mdg->removeNode(sibNode->id);
River Riddleadca3c22019-05-12 00:57:321972 sibNode->op->erase();
MLIR Teamd038e342019-03-01 19:50:251973 }
1974 }
1975
1976 // Clean up any allocs with no users.
1977 void eraseUnusedMemRefAllocations() {
MLIR Teamc4237ae2019-01-18 16:56:271978 for (auto &pair : mdg->memrefEdgeCount) {
1979 if (pair.second > 0)
1980 continue;
River Riddle35807bc2019-12-23 05:59:551981 auto memref = pair.first;
River Riddle99b87c92019-03-27 21:02:021982 // Skip if there exist other uses (return operation or function calls).
River Riddle2bdf33c2020-01-11 16:54:041983 if (!memref.use_empty())
MLIR Team71495d52019-01-22 21:23:371984 continue;
MLIR Teamc4237ae2019-01-18 16:56:271985 // Use list expected to match the dep graph info.
River Riddle2bdf33c2020-01-11 16:54:041986 auto *op = memref.getDefiningOp();
River Riddle1423acc2019-04-23 21:38:261987 if (isa_and_nonnull<AllocOp>(op))
River Riddle99b87c92019-03-27 21:02:021988 op->erase();
MLIR Teamc4237ae2019-01-18 16:56:271989 }
MLIR Teamf28e4df2018-11-01 14:26:001990 }
MLIR Team3b692302018-12-17 17:57:141991};
1992
1993} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001994
River Riddleed5fe202019-02-28 22:50:421995void LoopFusion::runOnFunction() {
MLIR Team6892ffb2018-12-20 04:42:551996 MemRefDependenceGraph g;
River Riddle400ad6f2020-04-08 19:57:021997 if (!g.init(getFunction()))
1998 return;
1999
2000 Optional<unsigned> fastMemorySpaceOpt;
2001 if (fastMemorySpace.hasValue())
2002 fastMemorySpaceOpt = fastMemorySpace;
2003 unsigned localBufSizeThresholdBytes = localBufSizeThreshold * 1024;
2004 GreedyFusion fusion(&g, localBufSizeThresholdBytes, fastMemorySpaceOpt,
2005 maximalFusion, computeToleranceThreshold);
2006 fusion.run();
MLIR Teamf28e4df2018-11-01 14:26:002007}