blob: 80308ea6a404af9fc0667fa8e28da56b25a4ed86 [file] [log] [blame]
MLIR Teamf28e4df2018-11-01 14:26:001//===- LoopFusion.cpp - Code to perform loop fusion -----------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements loop fusion.
19//
20//===----------------------------------------------------------------------===//
21
River Riddle75553832019-01-29 05:23:5322#include "mlir/AffineOps/AffineOps.h"
MLIR Teamf28e4df2018-11-01 14:26:0023#include "mlir/Analysis/AffineAnalysis.h"
Uday Bondhuguladfe07b72019-02-23 00:51:0824#include "mlir/Analysis/AffineStructures.h"
MLIR Teamf28e4df2018-11-01 14:26:0025#include "mlir/Analysis/LoopAnalysis.h"
MLIR Team3b692302018-12-17 17:57:1426#include "mlir/Analysis/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0027#include "mlir/IR/AffineExpr.h"
28#include "mlir/IR/AffineMap.h"
29#include "mlir/IR/Builders.h"
River Riddle48ccae22019-02-20 01:17:4630#include "mlir/Pass/Pass.h"
Lei Zhang85d9b6c2019-03-01 21:48:2431#include "mlir/StandardOps/Ops.h"
MLIR Teamf28e4df2018-11-01 14:26:0032#include "mlir/Transforms/LoopUtils.h"
33#include "mlir/Transforms/Passes.h"
MLIR Teamc4237ae2019-01-18 16:56:2734#include "mlir/Transforms/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0035#include "llvm/ADT/DenseMap.h"
MLIR Team3b692302018-12-17 17:57:1436#include "llvm/ADT/DenseSet.h"
37#include "llvm/ADT/SetVector.h"
MLIR Team4eef7952018-12-21 19:06:2338#include "llvm/Support/CommandLine.h"
MLIR Team38c2fe32019-01-14 19:26:2539#include "llvm/Support/Debug.h"
MLIR Team3b692302018-12-17 17:57:1440#include "llvm/Support/raw_ostream.h"
Uday Bondhugula864d9e02019-01-23 17:16:2441#include <iomanip>
Jacques Pienaar57270a92019-03-19 15:45:0642#include <sstream>
MLIR Team3b692302018-12-17 17:57:1443
MLIR Team38c2fe32019-01-14 19:26:2544#define DEBUG_TYPE "loop-fusion"
45
MLIR Team3b692302018-12-17 17:57:1446using llvm::SetVector;
MLIR Teamf28e4df2018-11-01 14:26:0047
48using namespace mlir;
49
River Riddle75c21e12019-01-26 06:14:0450static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options");
51
Uday Bondhugulace7e59532019-03-08 17:21:5252/// Disables fusion profitability check and fuses if valid. Ignore any
53/// additional (redundant) computation tolerance threshold
54/// that would have prevented fusion.
MLIR Teamc4237ae2019-01-18 16:56:2755static llvm::cl::opt<bool>
Uday Bondhugulaeee85362019-03-02 01:42:1356 clMaximalLoopFusion("fusion-maximal",
River Riddle75c21e12019-01-26 06:14:0457 llvm::cl::desc("Enables maximal loop fusion"),
58 llvm::cl::cat(clOptionsCategory));
Uday Bondhugula864d9e02019-01-23 17:16:2459
60/// A threshold in percent of additional computation allowed when fusing.
61static llvm::cl::opt<double> clFusionAddlComputeTolerance(
Uday Bondhugulaeee85362019-03-02 01:42:1362 "fusion-compute-tolerance",
Uday Bondhugulaa1dad3a2019-02-20 02:17:1963 llvm::cl::desc("Fractional increase in additional "
64 "computation tolerated while fusing"),
River Riddle75c21e12019-01-26 06:14:0465 llvm::cl::cat(clOptionsCategory));
MLIR Teamc4237ae2019-01-18 16:56:2766
Uday Bondhugula8be26272019-02-02 01:06:2267static llvm::cl::opt<unsigned> clFusionFastMemorySpace(
Uday Bondhugulaeee85362019-03-02 01:42:1368 "fusion-fast-mem-space",
Uday Bondhugula8be26272019-02-02 01:06:2269 llvm::cl::desc("Faster memory space number to promote fusion buffers to"),
70 llvm::cl::cat(clOptionsCategory));
71
Uday Bondhugulace7e59532019-03-08 17:21:5272// A local buffer of size less than or equal to this size is automatically
73// promoted to fast memory after producer-consumer fusion.
Uday Bondhugulad4b3ff12019-02-27 00:10:1974static llvm::cl::opt<unsigned long long> clFusionLocalBufThreshold(
Uday Bondhugulaeee85362019-03-02 01:42:1375 "fusion-local-buf-threshold",
Uday Bondhugulad4b3ff12019-02-27 00:10:1976 llvm::cl::desc("Threshold size (KiB) for promoting local buffers to fast "
Uday Bondhugula8be26272019-02-02 01:06:2277 "memory space"),
78 llvm::cl::cat(clOptionsCategory));
79
MLIR Teamf28e4df2018-11-01 14:26:0080namespace {
81
MLIR Team3b692302018-12-17 17:57:1482/// Loop fusion pass. This pass currently supports a greedy fusion policy,
83/// which fuses loop nests with single-writer/single-reader memref dependences
84/// with the goal of improving locality.
85
86// TODO(andydavis) Support fusion of source loop nests which write to multiple
87// memrefs, where each memref can have multiple users (if profitable).
MLIR Teamf28e4df2018-11-01 14:26:0088// TODO(andydavis) Extend this pass to check for fusion preventing dependences,
89// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1490
River Riddlec6c53442019-02-27 18:59:2991struct LoopFusion : public FunctionPass<LoopFusion> {
Uday Bondhugulace7e59532019-03-08 17:21:5292 LoopFusion(unsigned fastMemorySpace = 0, uint64_t localBufSizeThreshold = 0,
93 bool maximalFusion = false)
River Riddlec6c53442019-02-27 18:59:2994 : localBufSizeThreshold(localBufSizeThreshold),
Uday Bondhugulace7e59532019-03-08 17:21:5295 fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {}
MLIR Teamf28e4df2018-11-01 14:26:0096
River Riddleed5fe202019-02-28 22:50:4297 void runOnFunction() override;
Uday Bondhugula864d9e02019-01-23 17:16:2498
Uday Bondhugulad4b3ff12019-02-27 00:10:1999 // Any local buffers smaller than this size (in bytes) will be created in
Uday Bondhugula8be26272019-02-02 01:06:22100 // `fastMemorySpace` if provided.
Uday Bondhugulad4b3ff12019-02-27 00:10:19101 uint64_t localBufSizeThreshold;
Uday Bondhugula8be26272019-02-02 01:06:22102 Optional<unsigned> fastMemorySpace = None;
Uday Bondhugulace7e59532019-03-08 17:21:52103 // If true, ignore any additional (redundant) computation tolerance threshold
104 // that would have prevented fusion.
105 bool maximalFusion;
Uday Bondhugula8be26272019-02-02 01:06:22106
Uday Bondhugula864d9e02019-01-23 17:16:24107 // The amount of additional computation that is tolerated while fusing
108 // pair-wise as a fraction of the total computation.
109 constexpr static double kComputeToleranceThreshold = 0.30f;
MLIR Teamf28e4df2018-11-01 14:26:00110};
111
MLIR Teamf28e4df2018-11-01 14:26:00112} // end anonymous namespace
113
River Riddlec6c53442019-02-27 18:59:29114FunctionPassBase *mlir::createLoopFusionPass(unsigned fastMemorySpace,
Uday Bondhugulace7e59532019-03-08 17:21:52115 uint64_t localBufSizeThreshold,
116 bool maximalFusion) {
117 return new LoopFusion(fastMemorySpace, localBufSizeThreshold, maximalFusion);
Uday Bondhugulad4b3ff12019-02-27 00:10:19118}
MLIR Teamf28e4df2018-11-01 14:26:00119
MLIR Team3b692302018-12-17 17:57:14120namespace {
MLIR Teamf28e4df2018-11-01 14:26:00121
MLIR Team3b692302018-12-17 17:57:14122// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:35123// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:44124struct LoopNestStateCollector {
Chris Lattnerd9b5bc82019-03-25 02:53:05125 SmallVector<AffineForOp, 4> forOps;
River Riddle99b87c92019-03-27 21:02:02126 SmallVector<Operation *, 4> loadOpInsts;
127 SmallVector<Operation *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:53128 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:14129
River Riddle99b87c92019-03-27 21:02:02130 void collect(Operation *opToWalk) {
131 opToWalk->walk([&](Operation *op) {
132 if (op->isa<AffineForOp>())
133 forOps.push_back(op->cast<AffineForOp>());
134 else if (op->getNumRegions() != 0)
River Riddlebf9c3812019-02-05 00:24:44135 hasNonForRegion = true;
River Riddle99b87c92019-03-27 21:02:02136 else if (op->isa<LoadOp>())
137 loadOpInsts.push_back(op);
138 else if (op->isa<StoreOp>())
139 storeOpInsts.push_back(op);
River Riddlebf9c3812019-02-05 00:24:44140 });
MLIR Team3b692302018-12-17 17:57:14141 }
142};
143
MLIR Team71495d52019-01-22 21:23:37144// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
River Riddle99b87c92019-03-27 21:02:02145static bool isMemRefDereferencingOp(Operation &op) {
MLIR Team71495d52019-01-22 21:23:37146 if (op.isa<LoadOp>() || op.isa<StoreOp>() || op.isa<DmaStartOp>() ||
147 op.isa<DmaWaitOp>())
148 return true;
149 return false;
150}
MLIR Teamd038e342019-03-01 19:50:25151
MLIR Team6892ffb2018-12-20 04:42:55152// MemRefDependenceGraph is a graph data structure where graph nodes are
River Riddle99b87c92019-03-27 21:02:02153// top-level operations in a Function which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55154// are memref dependences between the nodes.
MLIR Teamc4237ae2019-01-18 16:56:27155// TODO(andydavis) Add a more flexible dependece graph representation.
MLIR Team6892ffb2018-12-20 04:42:55156// TODO(andydavis) Add a depth parameter to dependence graph construction.
157struct MemRefDependenceGraph {
158public:
159 // Node represents a node in the graph. A Node is either an entire loop nest
160 // rooted at the top level which contains loads/stores, or a top level
161 // load/store.
162 struct Node {
163 // The unique identifier of this node in the graph.
164 unsigned id;
165 // The top-level statment which is (or contains) loads/stores.
River Riddle99b87c92019-03-27 21:02:02166 Operation *op;
Chris Lattner5187cfc2018-12-28 05:21:41167 // List of load operations.
River Riddle99b87c92019-03-27 21:02:02168 SmallVector<Operation *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35169 // List of store op insts.
River Riddle99b87c92019-03-27 21:02:02170 SmallVector<Operation *, 4> stores;
171 Node(unsigned id, Operation *op) : id(id), op(op) {}
MLIR Team6892ffb2018-12-20 04:42:55172
173 // Returns the load op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10174 unsigned getLoadOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55175 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35176 for (auto *loadOpInst : loads) {
River Riddle96ebde92019-03-25 20:02:06177 if (memref == loadOpInst->cast<LoadOp>().getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55178 ++loadOpCount;
179 }
180 return loadOpCount;
181 }
182
183 // Returns the store op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10184 unsigned getStoreOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55185 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35186 for (auto *storeOpInst : stores) {
River Riddle96ebde92019-03-25 20:02:06187 if (memref == storeOpInst->cast<StoreOp>().getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55188 ++storeOpCount;
189 }
190 return storeOpCount;
191 }
MLIR Team58aa3832019-02-16 01:12:19192
MLIR Teamd038e342019-03-01 19:50:25193 // Returns all store ops in 'storeOps' which access 'memref'.
MLIR Team58aa3832019-02-16 01:12:19194 void getStoreOpsForMemref(Value *memref,
River Riddle99b87c92019-03-27 21:02:02195 SmallVectorImpl<Operation *> *storeOps) {
MLIR Team58aa3832019-02-16 01:12:19196 for (auto *storeOpInst : stores) {
River Riddle96ebde92019-03-25 20:02:06197 if (memref == storeOpInst->cast<StoreOp>().getMemRef())
MLIR Team58aa3832019-02-16 01:12:19198 storeOps->push_back(storeOpInst);
199 }
200 }
MLIR Teamd038e342019-03-01 19:50:25201
202 // Returns all load ops in 'loadOps' which access 'memref'.
203 void getLoadOpsForMemref(Value *memref,
River Riddle99b87c92019-03-27 21:02:02204 SmallVectorImpl<Operation *> *loadOps) {
MLIR Teamd038e342019-03-01 19:50:25205 for (auto *loadOpInst : loads) {
River Riddle96ebde92019-03-25 20:02:06206 if (memref == loadOpInst->cast<LoadOp>().getMemRef())
MLIR Teamd038e342019-03-01 19:50:25207 loadOps->push_back(loadOpInst);
208 }
209 }
210
211 // Returns all memrefs in 'loadAndStoreMemrefSet' for which this node
212 // has at least one load and store operation.
213 void getLoadAndStoreMemrefSet(DenseSet<Value *> *loadAndStoreMemrefSet) {
214 llvm::SmallDenseSet<Value *, 2> loadMemrefs;
215 for (auto *loadOpInst : loads) {
River Riddle96ebde92019-03-25 20:02:06216 loadMemrefs.insert(loadOpInst->cast<LoadOp>().getMemRef());
MLIR Teamd038e342019-03-01 19:50:25217 }
218 for (auto *storeOpInst : stores) {
River Riddle96ebde92019-03-25 20:02:06219 auto *memref = storeOpInst->cast<StoreOp>().getMemRef();
MLIR Teamd038e342019-03-01 19:50:25220 if (loadMemrefs.count(memref) > 0)
221 loadAndStoreMemrefSet->insert(memref);
222 }
223 }
MLIR Team6892ffb2018-12-20 04:42:55224 };
225
MLIR Teama0f3db402019-01-29 17:36:41226 // Edge represents a data dependece between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55227 struct Edge {
228 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46229 // If this edge is stored in Edge = Node.inEdges[i], then
230 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
231 // If this edge is stored in Edge = Node.outEdges[i], then
232 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55233 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41234 // The SSA value on which this edge represents a dependence.
235 // If the value is a memref, then the dependence is between graph nodes
236 // which contain accesses to the same memref 'value'. If the value is a
237 // non-memref value, then the dependence is between a graph node which
238 // defines an SSA value and another graph node which uses the SSA value
River Riddle99b87c92019-03-27 21:02:02239 // (e.g. a constant operation defining a value which is used inside a loop
MLIR Teama0f3db402019-01-29 17:36:41240 // nest).
241 Value *value;
MLIR Team6892ffb2018-12-20 04:42:55242 };
243
244 // Map from node id to Node.
245 DenseMap<unsigned, Node> nodes;
246 // Map from node id to list of input edges.
247 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
248 // Map from node id to list of output edges.
249 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27250 // Map from memref to a count on the dependence edges associated with that
251 // memref.
252 DenseMap<Value *, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41253 // The next unique identifier to use for newly created graph nodes.
254 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55255
256 MemRefDependenceGraph() {}
257
258 // Initializes the dependence graph based on operations in 'f'.
259 // Returns true on success, false otherwise.
Chris Lattner46ade282019-03-26 01:02:49260 bool init(Function &f);
MLIR Team6892ffb2018-12-20 04:42:55261
262 // Returns the graph node for 'id'.
263 Node *getNode(unsigned id) {
264 auto it = nodes.find(id);
265 assert(it != nodes.end());
266 return &it->second;
267 }
268
River Riddle99b87c92019-03-27 21:02:02269 // Adds a node with 'op' to the graph and returns its unique identifier.
270 unsigned addNode(Operation *op) {
271 Node node(nextNodeId++, op);
MLIR Teama0f3db402019-01-29 17:36:41272 nodes.insert({node.id, node});
273 return node.id;
274 }
275
MLIR Teamc4237ae2019-01-18 16:56:27276 // Remove node 'id' (and its associated edges) from graph.
277 void removeNode(unsigned id) {
278 // Remove each edge in 'inEdges[id]'.
279 if (inEdges.count(id) > 0) {
280 SmallVector<Edge, 2> oldInEdges = inEdges[id];
281 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41282 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27283 }
284 }
285 // Remove each edge in 'outEdges[id]'.
286 if (outEdges.count(id) > 0) {
287 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
288 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41289 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27290 }
291 }
292 // Erase remaining node state.
293 inEdges.erase(id);
294 outEdges.erase(id);
295 nodes.erase(id);
296 }
297
MLIR Teamd7c82442019-01-30 23:53:41298 // Returns true if node 'id' writes to any memref which escapes (or is an
299 // argument to) the function/block. Returns false otherwise.
300 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37301 Node *node = getNode(id);
302 for (auto *storeOpInst : node->stores) {
River Riddle96ebde92019-03-25 20:02:06303 auto *memref = storeOpInst->cast<StoreOp>().getMemRef();
River Riddle99b87c92019-03-27 21:02:02304 auto *op = memref->getDefiningOp();
MLIR Team58aa3832019-02-16 01:12:19305 // Return true if 'memref' is a block argument.
River Riddle99b87c92019-03-27 21:02:02306 if (!op)
MLIR Teamd7c82442019-01-30 23:53:41307 return true;
MLIR Team58aa3832019-02-16 01:12:19308 // Return true if any use of 'memref' escapes the function.
River Riddleb4992772019-02-04 18:38:47309 for (auto &use : memref->getUses())
310 if (!isMemRefDereferencingOp(*use.getOwner()))
MLIR Teamd7c82442019-01-30 23:53:41311 return true;
MLIR Teamd7c82442019-01-30 23:53:41312 }
313 return false;
314 }
315
316 // Returns true if node 'id' can be removed from the graph. Returns false
317 // otherwise. A node can be removed from the graph iff the following
318 // conditions are met:
319 // *) The node does not write to any memref which escapes (or is a
320 // function/block argument).
321 // *) The node has no successors in the dependence graph.
322 bool canRemoveNode(unsigned id) {
323 if (writesToLiveInOrEscapingMemrefs(id))
324 return false;
325 Node *node = getNode(id);
326 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41327 // Return false if there exist out edges from 'id' on 'memref'.
River Riddle96ebde92019-03-25 20:02:06328 if (getOutEdgeCount(id, storeOpInst->cast<StoreOp>().getMemRef()) > 0)
MLIR Teama0f3db402019-01-29 17:36:41329 return false;
MLIR Team71495d52019-01-22 21:23:37330 }
MLIR Teama0f3db402019-01-29 17:36:41331 return true;
MLIR Team71495d52019-01-22 21:23:37332 }
333
MLIR Teamd038e342019-03-01 19:50:25334 // Returns true iff there is an edge from node 'srcId' to node 'dstId' which
335 // is for 'value' if non-null, or for any value otherwise. Returns false
336 // otherwise.
337 bool hasEdge(unsigned srcId, unsigned dstId, Value *value = nullptr) {
MLIR Team27d067e2019-01-16 17:55:02338 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
339 return false;
340 }
341 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25342 return edge.id == dstId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02343 });
344 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25345 return edge.id == srcId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02346 });
347 return hasOutEdge && hasInEdge;
348 }
349
MLIR Teama0f3db402019-01-29 17:36:41350 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
351 void addEdge(unsigned srcId, unsigned dstId, Value *value) {
352 if (!hasEdge(srcId, dstId, value)) {
353 outEdges[srcId].push_back({dstId, value});
354 inEdges[dstId].push_back({srcId, value});
355 if (value->getType().isa<MemRefType>())
356 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02357 }
MLIR Team6892ffb2018-12-20 04:42:55358 }
359
MLIR Teama0f3db402019-01-29 17:36:41360 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
361 void removeEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team6892ffb2018-12-20 04:42:55362 assert(inEdges.count(dstId) > 0);
363 assert(outEdges.count(srcId) > 0);
MLIR Teama0f3db402019-01-29 17:36:41364 if (value->getType().isa<MemRefType>()) {
365 assert(memrefEdgeCount.count(value) > 0);
366 memrefEdgeCount[value]--;
367 }
MLIR Team6892ffb2018-12-20 04:42:55368 // Remove 'srcId' from 'inEdges[dstId]'.
369 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41370 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55371 inEdges[dstId].erase(it);
372 break;
373 }
374 }
375 // Remove 'dstId' from 'outEdges[srcId]'.
376 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41377 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55378 outEdges[srcId].erase(it);
379 break;
380 }
381 }
382 }
383
MLIR Teamd038e342019-03-01 19:50:25384 // Returns true if there is a path in the dependence graph from node 'srcId'
385 // to node 'dstId'. Returns false otherwise.
386 bool hasDependencePath(unsigned srcId, unsigned dstId) {
387 // Worklist state is: <node-id, next-output-edge-index-to-visit>
388 SmallVector<std::pair<unsigned, unsigned>, 4> worklist;
389 worklist.push_back({srcId, 0});
390 // Run DFS traversal to see if 'dstId' is reachable from 'srcId'.
391 while (!worklist.empty()) {
392 auto &idAndIndex = worklist.back();
393 // Return true if we have reached 'dstId'.
394 if (idAndIndex.first == dstId)
395 return true;
396 // Pop and continue if node has no out edges, or if all out edges have
397 // already been visited.
398 if (outEdges.count(idAndIndex.first) == 0 ||
399 idAndIndex.second == outEdges[idAndIndex.first].size()) {
400 worklist.pop_back();
401 continue;
402 }
403 // Get graph edge to traverse.
404 Edge edge = outEdges[idAndIndex.first][idAndIndex.second];
405 // Increment next output edge index for 'idAndIndex'.
406 ++idAndIndex.second;
407 // Add node at 'edge.id' to worklist.
408 worklist.push_back({edge.id, 0});
409 }
410 return false;
411 }
412
MLIR Teama0f3db402019-01-29 17:36:41413 // Returns the input edge count for node 'id' and 'memref' from src nodes
MLIR Teamd038e342019-03-01 19:50:25414 // which access 'memref' with a store operation.
MLIR Teama0f3db402019-01-29 17:36:41415 unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55416 unsigned inEdgeCount = 0;
417 if (inEdges.count(id) > 0)
418 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41419 if (inEdge.value == memref) {
420 Node *srcNode = getNode(inEdge.id);
421 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
MLIR Teamd038e342019-03-01 19:50:25422 if (srcNode->getStoreOpCount(memref) > 0)
MLIR Teama0f3db402019-01-29 17:36:41423 ++inEdgeCount;
424 }
MLIR Team6892ffb2018-12-20 04:42:55425 return inEdgeCount;
426 }
427
MLIR Teamd038e342019-03-01 19:50:25428 // Returns the output edge count for node 'id' and 'memref' (if non-null),
429 // otherwise returns the total output edge count from node 'id'.
430 unsigned getOutEdgeCount(unsigned id, Value *memref = nullptr) {
MLIR Team6892ffb2018-12-20 04:42:55431 unsigned outEdgeCount = 0;
432 if (outEdges.count(id) > 0)
433 for (auto &outEdge : outEdges[id])
MLIR Teamd038e342019-03-01 19:50:25434 if (!memref || outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55435 ++outEdgeCount;
436 return outEdgeCount;
437 }
438
River Riddle99b87c92019-03-27 21:02:02439 // Computes and returns an insertion point operation, before which the
MLIR Teama0f3db402019-01-29 17:36:41440 // the fused <srcId, dstId> loop nest can be inserted while preserving
441 // dependences. Returns nullptr if no such insertion point is found.
River Riddle99b87c92019-03-27 21:02:02442 Operation *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40443 if (outEdges.count(srcId) == 0)
River Riddle99b87c92019-03-27 21:02:02444 return getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41445
446 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
River Riddle99b87c92019-03-27 21:02:02447 SmallPtrSet<Operation *, 2> srcDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41448 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08449 if (outEdge.id != dstId)
River Riddle99b87c92019-03-27 21:02:02450 srcDepInsts.insert(getNode(outEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41451
452 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
River Riddle99b87c92019-03-27 21:02:02453 SmallPtrSet<Operation *, 2> dstDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41454 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08455 if (inEdge.id != srcId)
River Riddle99b87c92019-03-27 21:02:02456 dstDepInsts.insert(getNode(inEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41457
River Riddle99b87c92019-03-27 21:02:02458 Operation *srcNodeInst = getNode(srcId)->op;
459 Operation *dstNodeInst = getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41460
461 // Computing insertion point:
River Riddle99b87c92019-03-27 21:02:02462 // *) Walk all operation positions in Block operation list in the
463 // range (src, dst). For each operation 'op' visited in this search:
464 // *) Store in 'firstSrcDepPos' the first position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41465 // dependence edge from 'srcNode'.
River Riddle99b87c92019-03-27 21:02:02466 // *) Store in 'lastDstDepPost' the last position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41467 // dependence edge to 'dstNode'.
468 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
River Riddle99b87c92019-03-27 21:02:02469 // operation insertion point (or return null pointer if no such
MLIR Teama0f3db402019-01-29 17:36:41470 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
River Riddle99b87c92019-03-27 21:02:02471 SmallVector<Operation *, 2> depInsts;
MLIR Teama0f3db402019-01-29 17:36:41472 Optional<unsigned> firstSrcDepPos;
473 Optional<unsigned> lastDstDepPos;
474 unsigned pos = 0;
475 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
476 it != Block::iterator(dstNodeInst); ++it) {
River Riddle99b87c92019-03-27 21:02:02477 Operation *op = &(*it);
478 if (srcDepInsts.count(op) > 0 && firstSrcDepPos == None)
MLIR Teama0f3db402019-01-29 17:36:41479 firstSrcDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02480 if (dstDepInsts.count(op) > 0)
MLIR Teama0f3db402019-01-29 17:36:41481 lastDstDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02482 depInsts.push_back(op);
MLIR Teama0f3db402019-01-29 17:36:41483 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40484 }
MLIR Teama0f3db402019-01-29 17:36:41485
486 if (firstSrcDepPos.hasValue()) {
487 if (lastDstDepPos.hasValue()) {
488 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
489 // No valid insertion point exists which preserves dependences.
490 return nullptr;
491 }
492 }
493 // Return the insertion point at 'firstSrcDepPos'.
494 return depInsts[firstSrcDepPos.getValue()];
495 }
496 // No dependence targets in range (or only dst deps in range), return
497 // 'dstNodInst' insertion point.
498 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55499 }
500
MLIR Teama0f3db402019-01-29 17:36:41501 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
502 // has been replaced in node at 'dstId' by a private memref.
503 void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef) {
MLIR Team6892ffb2018-12-20 04:42:55504 // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'.
505 if (inEdges.count(srcId) > 0) {
506 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
507 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41508 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
509 if (inEdge.value != oldMemRef)
510 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55511 }
512 }
MLIR Teamc4237ae2019-01-18 16:56:27513 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55514 if (outEdges.count(srcId) > 0) {
515 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
516 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27517 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
518 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41519 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55520 }
521 }
MLIR Teama0f3db402019-01-29 17:36:41522 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
523 // replaced by a private memref). These edges could come from nodes
524 // other than 'srcId' which were removed in the previous step.
525 if (inEdges.count(dstId) > 0) {
526 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
527 for (auto &inEdge : oldInEdges)
528 if (inEdge.value == oldMemRef)
529 removeEdge(inEdge.id, dstId, inEdge.value);
530 }
MLIR Team6892ffb2018-12-20 04:42:55531 }
532
MLIR Teamd038e342019-03-01 19:50:25533 // Update edge mappings for nodes 'sibId' and 'dstId' to reflect fusion
534 // of sibling node 'sidId' into node 'dstId'.
535 void updateEdges(unsigned sibId, unsigned dstId) {
536 // For each edge in 'inEdges[sibId]':
537 // *) Add new edge from source node 'inEdge.id' to 'dstNode'.
538 // *) Remove edge from source node 'inEdge.id' to 'sibNode'.
539 if (inEdges.count(sibId) > 0) {
540 SmallVector<Edge, 2> oldInEdges = inEdges[sibId];
541 for (auto &inEdge : oldInEdges) {
542 addEdge(inEdge.id, dstId, inEdge.value);
543 removeEdge(inEdge.id, sibId, inEdge.value);
544 }
545 }
546
547 // For each edge in 'outEdges[sibId]' to node 'id'
548 // *) Add new edge from 'dstId' to 'outEdge.id'.
549 // *) Remove edge from 'sibId' to 'outEdge.id'.
550 if (outEdges.count(sibId) > 0) {
551 SmallVector<Edge, 2> oldOutEdges = outEdges[sibId];
552 for (auto &outEdge : oldOutEdges) {
553 addEdge(dstId, outEdge.id, outEdge.value);
554 removeEdge(sibId, outEdge.id, outEdge.value);
555 }
556 }
557 }
558
MLIR Team6892ffb2018-12-20 04:42:55559 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddle99b87c92019-03-27 21:02:02560 void addToNode(unsigned id, const SmallVectorImpl<Operation *> &loads,
561 const SmallVectorImpl<Operation *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55562 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35563 for (auto *loadOpInst : loads)
564 node->loads.push_back(loadOpInst);
565 for (auto *storeOpInst : stores)
566 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55567 }
568
MLIR Teamc4237ae2019-01-18 16:56:27569 void clearNodeLoadAndStores(unsigned id) {
570 Node *node = getNode(id);
571 node->loads.clear();
572 node->stores.clear();
573 }
574
MLIR Teamd038e342019-03-01 19:50:25575 // Calls 'callback' for each input edge incident to node 'id' which carries a
576 // memref dependence.
577 void forEachMemRefInputEdge(unsigned id,
578 const std::function<void(Edge)> &callback) {
579 if (inEdges.count(id) > 0)
580 forEachMemRefEdge(inEdges[id], callback);
581 }
582 // Calls 'callback' for each output edge from node 'id' which carries a
583 // memref dependence.
584 void forEachMemRefOutputEdge(unsigned id,
585 const std::function<void(Edge)> &callback) {
586 if (outEdges.count(id) > 0)
587 forEachMemRefEdge(outEdges[id], callback);
588 }
589 // Calls 'callback' for each edge in 'edges' which carries a memref
590 // dependence.
591 void forEachMemRefEdge(ArrayRef<Edge> edges,
592 const std::function<void(Edge)> &callback) {
593 for (auto &edge : edges) {
594 // Skip if 'edge' is not a memref dependence edge.
595 if (!edge.value->getType().isa<MemRefType>())
596 continue;
597 assert(nodes.count(edge.id) > 0);
598 // Skip if 'edge.id' is not a loop nest.
River Riddle99b87c92019-03-27 21:02:02599 if (!getNode(edge.id)->op->isa<AffineForOp>())
MLIR Teamd038e342019-03-01 19:50:25600 continue;
601 // Visit current input edge 'edge'.
602 callback(edge);
603 }
604 }
605
MLIR Team6892ffb2018-12-20 04:42:55606 void print(raw_ostream &os) const {
607 os << "\nMemRefDependenceGraph\n";
608 os << "\nNodes:\n";
609 for (auto &idAndNode : nodes) {
610 os << "Node: " << idAndNode.first << "\n";
611 auto it = inEdges.find(idAndNode.first);
612 if (it != inEdges.end()) {
613 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41614 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55615 }
616 it = outEdges.find(idAndNode.first);
617 if (it != outEdges.end()) {
618 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41619 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55620 }
621 }
622 }
623 void dump() const { print(llvm::errs()); }
624};
625
River Riddle99b87c92019-03-27 21:02:02626// Intializes the data dependence graph by walking operations in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55627// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39628// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55629// dependence graph at a different depth.
Chris Lattner46ade282019-03-26 01:02:49630bool MemRefDependenceGraph::init(Function &f) {
Chris Lattner3f190312018-12-27 22:35:10631 DenseMap<Value *, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43632
633 // TODO: support multi-block functions.
Chris Lattner46ade282019-03-26 01:02:49634 if (f.getBlocks().size() != 1)
Chris Lattnerdffc5892018-12-29 23:33:43635 return false;
636
River Riddle99b87c92019-03-27 21:02:02637 DenseMap<Operation *, unsigned> forToNodeMap;
638 for (auto &op : f.front()) {
639 if (auto forOp = op.dyn_cast<AffineForOp>()) {
River Riddle5052bd82019-02-02 00:42:18640 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55641 // all loads and store accesses it contains.
642 LoopNestStateCollector collector;
River Riddle99b87c92019-03-27 21:02:02643 collector.collect(&op);
River Riddle832567b2019-03-25 17:14:34644 // Return false if a non 'affine.for' region was found (not currently
645 // supported).
River Riddle75553832019-01-29 05:23:53646 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55647 return false;
River Riddle99b87c92019-03-27 21:02:02648 Node node(nextNodeId++, &op);
Chris Lattner456ad6a2018-12-29 00:05:35649 for (auto *opInst : collector.loadOpInsts) {
650 node.loads.push_back(opInst);
River Riddle96ebde92019-03-25 20:02:06651 auto *memref = opInst->cast<LoadOp>().getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55652 memrefAccesses[memref].insert(node.id);
653 }
Chris Lattner456ad6a2018-12-29 00:05:35654 for (auto *opInst : collector.storeOpInsts) {
655 node.stores.push_back(opInst);
River Riddle96ebde92019-03-25 20:02:06656 auto *memref = opInst->cast<StoreOp>().getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55657 memrefAccesses[memref].insert(node.id);
658 }
River Riddle99b87c92019-03-27 21:02:02659 forToNodeMap[&op] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55660 nodes.insert({node.id, node});
River Riddle99b87c92019-03-27 21:02:02661 } else if (auto loadOp = op.dyn_cast<LoadOp>()) {
River Riddleb4992772019-02-04 18:38:47662 // Create graph node for top-level load op.
River Riddle99b87c92019-03-27 21:02:02663 Node node(nextNodeId++, &op);
664 node.loads.push_back(&op);
665 auto *memref = op.cast<LoadOp>().getMemRef();
River Riddleb4992772019-02-04 18:38:47666 memrefAccesses[memref].insert(node.id);
667 nodes.insert({node.id, node});
River Riddle99b87c92019-03-27 21:02:02668 } else if (auto storeOp = op.dyn_cast<StoreOp>()) {
River Riddleb4992772019-02-04 18:38:47669 // Create graph node for top-level store op.
River Riddle99b87c92019-03-27 21:02:02670 Node node(nextNodeId++, &op);
671 node.stores.push_back(&op);
672 auto *memref = op.cast<StoreOp>().getMemRef();
River Riddleb4992772019-02-04 18:38:47673 memrefAccesses[memref].insert(node.id);
674 nodes.insert({node.id, node});
River Riddle99b87c92019-03-27 21:02:02675 } else if (op.getNumRegions() != 0) {
River Riddleb4992772019-02-04 18:38:47676 // Return false if another region is found (not currently supported).
677 return false;
River Riddle99b87c92019-03-27 21:02:02678 } else if (op.getNumResults() > 0 && !op.use_empty()) {
River Riddleb4992772019-02-04 18:38:47679 // Create graph node for top-level producer of SSA values, which
680 // could be used by loop nest nodes.
River Riddle99b87c92019-03-27 21:02:02681 Node node(nextNodeId++, &op);
River Riddleb4992772019-02-04 18:38:47682 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41683 }
684 }
685
686 // Add dependence edges between nodes which produce SSA values and their
687 // users.
688 for (auto &idAndNode : nodes) {
689 const Node &node = idAndNode.second;
690 if (!node.loads.empty() || !node.stores.empty())
691 continue;
River Riddle99b87c92019-03-27 21:02:02692 auto *opInst = node.op;
MLIR Teama0f3db402019-01-29 17:36:41693 for (auto *value : opInst->getResults()) {
694 for (auto &use : value->getUses()) {
Chris Lattnerd9b5bc82019-03-25 02:53:05695 SmallVector<AffineForOp, 4> loops;
River Riddleb4992772019-02-04 18:38:47696 getLoopIVs(*use.getOwner(), &loops);
MLIR Teama0f3db402019-01-29 17:36:41697 if (loops.empty())
698 continue;
River Riddlef9d91532019-03-27 00:05:09699 assert(forToNodeMap.count(loops[0].getOperation()) > 0);
700 unsigned userLoopNestId = forToNodeMap[loops[0].getOperation()];
MLIR Teama0f3db402019-01-29 17:36:41701 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55702 }
703 }
MLIR Team6892ffb2018-12-20 04:42:55704 }
705
706 // Walk memref access lists and add graph edges between dependent nodes.
707 for (auto &memrefAndList : memrefAccesses) {
708 unsigned n = memrefAndList.second.size();
709 for (unsigned i = 0; i < n; ++i) {
710 unsigned srcId = memrefAndList.second[i];
711 bool srcHasStore =
712 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
713 for (unsigned j = i + 1; j < n; ++j) {
714 unsigned dstId = memrefAndList.second[j];
715 bool dstHasStore =
716 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
717 if (srcHasStore || dstHasStore)
718 addEdge(srcId, dstId, memrefAndList.first);
719 }
720 }
721 }
722 return true;
723}
724
MLIR Team38c2fe32019-01-14 19:26:25725namespace {
726
727// LoopNestStats aggregates various per-loop statistics (eg. loop trip count
728// and operation count) for a loop nest up until the innermost loop body.
729struct LoopNestStats {
River Riddle5052bd82019-02-02 00:42:18730 // Map from AffineForOp to immediate child AffineForOps in its loop body.
River Riddle99b87c92019-03-27 21:02:02731 DenseMap<Operation *, SmallVector<AffineForOp, 2>> loopMap;
River Riddle5052bd82019-02-02 00:42:18732 // Map from AffineForOp to count of operations in its loop body.
River Riddle99b87c92019-03-27 21:02:02733 DenseMap<Operation *, uint64_t> opCountMap;
River Riddle5052bd82019-02-02 00:42:18734 // Map from AffineForOp to its constant trip count.
River Riddle99b87c92019-03-27 21:02:02735 DenseMap<Operation *, uint64_t> tripCountMap;
MLIR Team38c2fe32019-01-14 19:26:25736};
737
738// LoopNestStatsCollector walks a single loop nest and gathers per-loop
739// trip count and operation count statistics and records them in 'stats'.
River Riddlebf9c3812019-02-05 00:24:44740struct LoopNestStatsCollector {
MLIR Team38c2fe32019-01-14 19:26:25741 LoopNestStats *stats;
742 bool hasLoopWithNonConstTripCount = false;
743
744 LoopNestStatsCollector(LoopNestStats *stats) : stats(stats) {}
745
River Riddle99b87c92019-03-27 21:02:02746 void collect(Operation *op) {
747 op->walk<AffineForOp>([&](AffineForOp forOp) {
River Riddlef9d91532019-03-27 00:05:09748 auto *forInst = forOp.getOperation();
River Riddle9c085402019-03-27 15:55:17749 auto *parentInst = forOp.getOperation()->getParentOp();
River Riddlebf9c3812019-02-05 00:24:44750 if (parentInst != nullptr) {
751 assert(parentInst->isa<AffineForOp>() && "Expected parent AffineForOp");
752 // Add mapping to 'forOp' from its parent AffineForOp.
753 stats->loopMap[parentInst].push_back(forOp);
754 }
River Riddle5052bd82019-02-02 00:42:18755
River Riddle99b87c92019-03-27 21:02:02756 // Record the number of op operations in the body of 'forOp'.
River Riddlebf9c3812019-02-05 00:24:44757 unsigned count = 0;
758 stats->opCountMap[forInst] = 0;
River Riddle99b87c92019-03-27 21:02:02759 for (auto &op : *forOp.getBody()) {
760 if (!op.isa<AffineForOp>() && !op.isa<AffineIfOp>())
River Riddlebf9c3812019-02-05 00:24:44761 ++count;
762 }
763 stats->opCountMap[forInst] = count;
764 // Record trip count for 'forOp'. Set flag if trip count is not
765 // constant.
766 Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp);
767 if (!maybeConstTripCount.hasValue()) {
768 hasLoopWithNonConstTripCount = true;
769 return;
770 }
771 stats->tripCountMap[forInst] = maybeConstTripCount.getValue();
772 });
MLIR Team38c2fe32019-01-14 19:26:25773 }
774};
775
River Riddle5052bd82019-02-02 00:42:18776// Computes the total cost of the loop nest rooted at 'forOp'.
MLIR Team38c2fe32019-01-14 19:26:25777// Currently, the total cost is computed by counting the total operation
778// instance count (i.e. total number of operations in the loop bodyloop
779// operation count * loop trip count) for the entire loop nest.
780// If 'tripCountOverrideMap' is non-null, overrides the trip count for loops
781// specified in the map when computing the total op instance count.
782// NOTE: this is used to compute the cost of computation slices, which are
783// sliced along the iteration dimension, and thus reduce the trip count.
River Riddle5052bd82019-02-02 00:42:18784// If 'computeCostMap' is non-null, the total op count for forOps specified
MLIR Team38c2fe32019-01-14 19:26:25785// in the map is increased (not overridden) by adding the op count from the
786// map to the existing op count for the for loop. This is done before
787// multiplying by the loop's trip count, and is used to model the cost of
788// inserting a sliced loop nest of known cost into the loop's body.
789// NOTE: this is used to compute the cost of fusing a slice of some loop nest
790// within another loop.
Uday Bondhugula864d9e02019-01-23 17:16:24791static int64_t getComputeCost(
River Riddle99b87c92019-03-27 21:02:02792 Operation *forInst, LoopNestStats *stats,
793 llvm::SmallDenseMap<Operation *, uint64_t, 8> *tripCountOverrideMap,
794 DenseMap<Operation *, int64_t> *computeCostMap) {
River Riddle5052bd82019-02-02 00:42:18795 // 'opCount' is the total number operations in one iteration of 'forOp' body
Uday Bondhugula864d9e02019-01-23 17:16:24796 int64_t opCount = stats->opCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25797 if (stats->loopMap.count(forInst) > 0) {
River Riddle5052bd82019-02-02 00:42:18798 for (auto childForOp : stats->loopMap[forInst]) {
River Riddlef9d91532019-03-27 00:05:09799 opCount += getComputeCost(childForOp.getOperation(), stats,
River Riddle5052bd82019-02-02 00:42:18800 tripCountOverrideMap, computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:25801 }
802 }
803 // Add in additional op instances from slice (if specified in map).
804 if (computeCostMap != nullptr) {
805 auto it = computeCostMap->find(forInst);
806 if (it != computeCostMap->end()) {
807 opCount += it->second;
808 }
809 }
810 // Override trip count (if specified in map).
Uday Bondhugula864d9e02019-01-23 17:16:24811 int64_t tripCount = stats->tripCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25812 if (tripCountOverrideMap != nullptr) {
813 auto it = tripCountOverrideMap->find(forInst);
814 if (it != tripCountOverrideMap->end()) {
815 tripCount = it->second;
816 }
817 }
818 // Returns the total number of dynamic instances of operations in loop body.
819 return tripCount * opCount;
820}
821
822} // end anonymous namespace
823
Uday Bondhugula7aa60a32019-02-27 01:32:47824// TODO(andydavis,b/126426796): extend this to handle multiple result maps.
MLIR Team27d067e2019-01-16 17:55:02825static Optional<uint64_t> getConstDifference(AffineMap lbMap, AffineMap ubMap) {
Uday Bondhugulac1ca23e2019-01-16 21:13:00826 assert(lbMap.getNumResults() == 1 && "expected single result bound map");
827 assert(ubMap.getNumResults() == 1 && "expected single result bound map");
MLIR Team27d067e2019-01-16 17:55:02828 assert(lbMap.getNumDims() == ubMap.getNumDims());
829 assert(lbMap.getNumSymbols() == ubMap.getNumSymbols());
MLIR Team27d067e2019-01-16 17:55:02830 AffineExpr lbExpr(lbMap.getResult(0));
831 AffineExpr ubExpr(ubMap.getResult(0));
832 auto loopSpanExpr = simplifyAffineExpr(ubExpr - lbExpr, lbMap.getNumDims(),
833 lbMap.getNumSymbols());
834 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
835 if (!cExpr)
836 return None;
837 return cExpr.getValue();
838}
839
River Riddle5052bd82019-02-02 00:42:18840// Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop
MLIR Team38c2fe32019-01-14 19:26:25841// nest surrounding 'srcAccess' utilizing slice loop bounds in 'sliceState'.
842// Returns true on success, false otherwise (if a non-constant trip count
843// was encountered).
844// TODO(andydavis) Make this work with non-unit step loops.
MLIR Team27d067e2019-01-16 17:55:02845static bool buildSliceTripCountMap(
River Riddle99b87c92019-03-27 21:02:02846 Operation *srcOpInst, ComputationSliceState *sliceState,
847 llvm::SmallDenseMap<Operation *, uint64_t, 8> *tripCountMap) {
Chris Lattnerd9b5bc82019-03-25 02:53:05848 SmallVector<AffineForOp, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:02849 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:25850 unsigned numSrcLoopIVs = srcLoopIVs.size();
River Riddle5052bd82019-02-02 00:42:18851 // Populate map from AffineForOp -> trip count
MLIR Team38c2fe32019-01-14 19:26:25852 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
853 AffineMap lbMap = sliceState->lbs[i];
854 AffineMap ubMap = sliceState->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17855 if (lbMap == AffineMap() || ubMap == AffineMap()) {
MLIR Team38c2fe32019-01-14 19:26:25856 // The iteration of src loop IV 'i' was not sliced. Use full loop bounds.
River Riddleaf1abcc2019-03-25 18:13:31857 if (srcLoopIVs[i].hasConstantLowerBound() &&
858 srcLoopIVs[i].hasConstantUpperBound()) {
River Riddlef9d91532019-03-27 00:05:09859 (*tripCountMap)[srcLoopIVs[i].getOperation()] =
River Riddleaf1abcc2019-03-25 18:13:31860 srcLoopIVs[i].getConstantUpperBound() -
861 srcLoopIVs[i].getConstantLowerBound();
MLIR Team38c2fe32019-01-14 19:26:25862 continue;
863 }
864 return false;
865 }
MLIR Team27d067e2019-01-16 17:55:02866 Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap);
867 if (!tripCount.hasValue())
MLIR Team38c2fe32019-01-14 19:26:25868 return false;
River Riddlef9d91532019-03-27 00:05:09869 (*tripCountMap)[srcLoopIVs[i].getOperation()] = tripCount.getValue();
MLIR Team38c2fe32019-01-14 19:26:25870 }
871 return true;
872}
873
MLIR Team27d067e2019-01-16 17:55:02874// Removes load operations from 'srcLoads' which operate on 'memref', and
875// adds them to 'dstLoads'.
River Riddle99b87c92019-03-27 21:02:02876static void moveLoadsAccessingMemrefTo(Value *memref,
877 SmallVectorImpl<Operation *> *srcLoads,
878 SmallVectorImpl<Operation *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02879 dstLoads->clear();
River Riddle99b87c92019-03-27 21:02:02880 SmallVector<Operation *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02881 for (auto *load : *srcLoads) {
River Riddle96ebde92019-03-25 20:02:06882 if (load->cast<LoadOp>().getMemRef() == memref)
MLIR Team27d067e2019-01-16 17:55:02883 dstLoads->push_back(load);
884 else
885 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25886 }
MLIR Team27d067e2019-01-16 17:55:02887 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25888}
889
MLIR Team27d067e2019-01-16 17:55:02890// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddle99b87c92019-03-27 21:02:02891static unsigned getInnermostCommonLoopDepth(ArrayRef<Operation *> ops) {
MLIR Team27d067e2019-01-16 17:55:02892 unsigned numOps = ops.size();
893 assert(numOps > 0);
894
Chris Lattnerd9b5bc82019-03-25 02:53:05895 std::vector<SmallVector<AffineForOp, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02896 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
897 for (unsigned i = 0; i < numOps; ++i) {
898 getLoopIVs(*ops[i], &loops[i]);
899 loopDepthLimit =
900 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25901 }
MLIR Team27d067e2019-01-16 17:55:02902
903 unsigned loopDepth = 0;
904 for (unsigned d = 0; d < loopDepthLimit; ++d) {
905 unsigned i;
906 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18907 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02908 break;
MLIR Team27d067e2019-01-16 17:55:02909 }
910 if (i != numOps)
911 break;
912 ++loopDepth;
913 }
914 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25915}
916
MLIR Teamd7c82442019-01-30 23:53:41917// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
918// and 'storeOpInsts' are satisfied.
River Riddle99b87c92019-03-27 21:02:02919static unsigned getMaxLoopDepth(ArrayRef<Operation *> loadOpInsts,
920 ArrayRef<Operation *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41921 // Merge loads and stores into the same array.
River Riddle99b87c92019-03-27 21:02:02922 SmallVector<Operation *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41923 ops.append(storeOpInsts.begin(), storeOpInsts.end());
924
925 // Compute the innermost common loop depth for loads and stores.
926 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
927
928 // Return common loop depth for loads if there are no store ops.
929 if (storeOpInsts.empty())
930 return loopDepth;
931
932 // Check dependences on all pairs of ops in 'ops' and store the minimum
933 // loop depth at which a dependence is satisfied.
934 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
935 auto *srcOpInst = ops[i];
936 MemRefAccess srcAccess(srcOpInst);
937 for (unsigned j = 0; j < e; ++j) {
938 auto *dstOpInst = ops[j];
939 MemRefAccess dstAccess(dstOpInst);
940
941 unsigned numCommonLoops =
942 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
943 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
944 FlatAffineConstraints dependenceConstraints;
945 // TODO(andydavis) Cache dependence analysis results, check cache here.
946 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
947 &dependenceConstraints,
948 /*dependenceComponents=*/nullptr)) {
949 // Store minimum loop depth and break because we want the min 'd' at
950 // which there is a dependence.
951 loopDepth = std::min(loopDepth, d - 1);
952 break;
953 }
954 }
955 }
956 }
957 return loopDepth;
958}
959
MLIR Team8f5f2c72019-02-15 17:32:18960// Compute loop interchange permutation:
961// *) Computes dependence components between all op pairs in 'ops' for loop
962// depths in range [1, 'maxLoopDepth'].
963// *) Classifies the outermost 'maxLoopDepth' loops surrounding 'ops' as either
964// parallel or sequential.
965// *) Computes the loop permutation which sinks sequential loops deeper into
966// the loop nest, while preserving the relative order between other loops.
967// *) Checks each dependence component against the permutation to see if the
968// desired loop interchange would violated dependences by making the a
969// dependence componenent lexicographically negative.
970// TODO(andydavis) Move this function to LoopUtils.
971static bool
River Riddle99b87c92019-03-27 21:02:02972computeLoopInterchangePermutation(ArrayRef<Operation *> ops,
MLIR Team8f5f2c72019-02-15 17:32:18973 unsigned maxLoopDepth,
974 SmallVectorImpl<unsigned> *loopPermMap) {
975 // Gather dependence components for dependences between all ops in 'ops'
976 // at loop depths in range [1, maxLoopDepth].
977 // TODO(andydavis) Refactor this loop into a LoopUtil utility function:
978 // mlir::getDependenceComponents().
979 // TODO(andydavis) Split this loop into two: first check all dependences,
980 // and construct dep vectors. Then, scan through them to detect the parallel
981 // ones.
982 std::vector<llvm::SmallVector<DependenceComponent, 2>> depCompsVec;
983 llvm::SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true);
984 unsigned numOps = ops.size();
985 for (unsigned d = 1; d <= maxLoopDepth; ++d) {
986 for (unsigned i = 0; i < numOps; ++i) {
987 auto *srcOpInst = ops[i];
988 MemRefAccess srcAccess(srcOpInst);
989 for (unsigned j = 0; j < numOps; ++j) {
990 auto *dstOpInst = ops[j];
991 MemRefAccess dstAccess(dstOpInst);
992
993 FlatAffineConstraints dependenceConstraints;
994 llvm::SmallVector<DependenceComponent, 2> depComps;
995 // TODO(andydavis,bondhugula) Explore whether it would be profitable
996 // to pre-compute and store deps instead of repeatidly checking.
997 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
998 &dependenceConstraints, &depComps)) {
999 isParallelLoop[d - 1] = false;
1000 depCompsVec.push_back(depComps);
1001 }
1002 }
1003 }
1004 }
1005 // Count the number of parallel loops.
1006 unsigned numParallelLoops = 0;
1007 for (unsigned i = 0, e = isParallelLoop.size(); i < e; ++i)
1008 if (isParallelLoop[i])
1009 ++numParallelLoops;
1010
1011 // Compute permutation of loops that sinks sequential loops (and thus raises
1012 // parallel loops) while preserving relative order.
1013 llvm::SmallVector<unsigned, 4> loopPermMapInv;
1014 loopPermMapInv.resize(maxLoopDepth);
1015 loopPermMap->resize(maxLoopDepth);
1016 unsigned nextSequentialLoop = numParallelLoops;
1017 unsigned nextParallelLoop = 0;
1018 for (unsigned i = 0; i < maxLoopDepth; ++i) {
1019 if (isParallelLoop[i]) {
1020 (*loopPermMap)[i] = nextParallelLoop;
1021 loopPermMapInv[nextParallelLoop++] = i;
1022 } else {
1023 (*loopPermMap)[i] = nextSequentialLoop;
1024 loopPermMapInv[nextSequentialLoop++] = i;
1025 }
1026 }
1027
1028 // Check each dependence component against the permutation to see if the
1029 // desired loop interchange permutation would make the dependence vectors
1030 // lexicographically negative.
1031 // Example 1: [-1, 1][0, 0]
1032 // Example 2: [0, 0][-1, 1]
1033 for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) {
1034 llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i];
1035 assert(depComps.size() >= maxLoopDepth);
1036 // Check if the first non-zero dependence component is positive.
1037 for (unsigned j = 0; j < maxLoopDepth; ++j) {
1038 unsigned permIndex = loopPermMapInv[j];
1039 assert(depComps[permIndex].lb.hasValue());
1040 int64_t depCompLb = depComps[permIndex].lb.getValue();
1041 if (depCompLb > 0)
1042 break;
1043 if (depCompLb < 0)
1044 return false;
1045 }
1046 }
1047 return true;
1048}
1049
1050// Sinks all sequential loops to the innermost levels (while preserving
1051// relative order among them) and moves all parallel loops to the
1052// outermost (while again preserving relative order among them).
1053// This can increase the loop depth at which we can fuse a slice, since we are
1054// pushing loop carried dependence to a greater depth in the loop nest.
1055static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
River Riddle99b87c92019-03-27 21:02:021056 assert(node->op->isa<AffineForOp>());
Alex Zinenko5a5bba02019-03-27 12:11:581057 // Get perfectly nested sequence of loops starting at root of loop nest
1058 // (the first op being another AffineFor, and the second op - a terminator).
MLIR Team8f5f2c72019-02-15 17:32:181059 // TODO(andydavis,bondhugula) Share this with similar code in loop tiling.
Chris Lattnerd9b5bc82019-03-25 02:53:051060 SmallVector<AffineForOp, 4> loops;
River Riddle99b87c92019-03-27 21:02:021061 AffineForOp curr = node->op->cast<AffineForOp>();
MLIR Team8f5f2c72019-02-15 17:32:181062 loops.push_back(curr);
River Riddleaf1abcc2019-03-25 18:13:311063 auto *currBody = curr.getBody();
Alex Zinenko5a5bba02019-03-27 12:11:581064 while (currBody->begin() == std::prev(currBody->end(), 2) &&
River Riddleaf1abcc2019-03-25 18:13:311065 (curr = curr.getBody()->front().dyn_cast<AffineForOp>())) {
MLIR Team8f5f2c72019-02-15 17:32:181066 loops.push_back(curr);
River Riddleaf1abcc2019-03-25 18:13:311067 currBody = curr.getBody();
MLIR Team8f5f2c72019-02-15 17:32:181068 }
1069 if (loops.size() < 2)
1070 return;
1071
1072 // Merge loads and stores into the same array.
River Riddle99b87c92019-03-27 21:02:021073 SmallVector<Operation *, 2> memOps(node->loads.begin(), node->loads.end());
MLIR Team8f5f2c72019-02-15 17:32:181074 memOps.append(node->stores.begin(), node->stores.end());
1075
1076 // Compute loop permutation in 'loopPermMap'.
1077 llvm::SmallVector<unsigned, 4> loopPermMap;
1078 if (!computeLoopInterchangePermutation(memOps, loops.size(), &loopPermMap))
1079 return;
1080
1081 int loopNestRootIndex = -1;
1082 for (int i = loops.size() - 1; i >= 0; --i) {
1083 int permIndex = static_cast<int>(loopPermMap[i]);
1084 // Store the index of the for loop which will be the new loop nest root.
1085 if (permIndex == 0)
1086 loopNestRootIndex = i;
1087 if (permIndex > i) {
1088 // Sink loop 'i' by 'permIndex - i' levels deeper into the loop nest.
1089 sinkLoop(loops[i], permIndex - i);
1090 }
1091 }
1092 assert(loopNestRootIndex != -1 && "invalid root index");
River Riddle99b87c92019-03-27 21:02:021093 node->op = loops[loopNestRootIndex].getOperation();
MLIR Team8f5f2c72019-02-15 17:32:181094}
1095
Uday Bondhugula8be26272019-02-02 01:06:221096// TODO(mlir-team): improve/complete this when we have target data.
1097unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
1098 auto elementType = memRefType.getElementType();
1099
1100 unsigned sizeInBits;
1101 if (elementType.isIntOrFloat()) {
1102 sizeInBits = elementType.getIntOrFloatBitWidth();
1103 } else {
1104 auto vectorType = elementType.cast<VectorType>();
1105 sizeInBits =
1106 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
1107 }
1108 return llvm::divideCeil(sizeInBits, 8);
1109}
1110
MLIR Teamc4237ae2019-01-18 16:56:271111// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:181112// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:521113// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1114// TODO(bondhugula): consider refactoring the common code from generateDma and
1115// this one.
River Riddle99b87c92019-03-27 21:02:021116static Value *createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst,
Uday Bondhugula8be26272019-02-02 01:06:221117 unsigned dstLoopDepth,
1118 Optional<unsigned> fastMemorySpace,
Uday Bondhugulad4b3ff12019-02-27 00:10:191119 uint64_t localBufSizeThreshold) {
River Riddlef9d91532019-03-27 00:05:091120 auto *forInst = forOp.getOperation();
River Riddle5052bd82019-02-02 00:42:181121
1122 // Create builder to insert alloc op just before 'forOp'.
MLIR Teamc4237ae2019-01-18 16:56:271123 FuncBuilder b(forInst);
1124 // Builder to create constants at the top level.
1125 FuncBuilder top(forInst->getFunction());
1126 // Create new memref type based on slice bounds.
River Riddle96ebde92019-03-25 20:02:061127 auto *oldMemRef = srcStoreOpInst->cast<StoreOp>().getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271128 auto oldMemRefType = oldMemRef->getType().cast<MemRefType>();
1129 unsigned rank = oldMemRefType.getRank();
1130
Uday Bondhugula94a03f82019-01-22 21:58:521131 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:441132 MemRefRegion region(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471133 bool validRegion = succeeded(region.compute(srcStoreOpInst, dstLoopDepth));
MLIR Teamd42ef782019-03-04 19:01:251134 (void)validRegion;
1135 assert(validRegion && "unexpected memref region failure");
River Riddle6859f332019-01-23 22:39:451136 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:271137 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:521138 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:271139 lbs.reserve(rank);
1140 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:521141 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:271142 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:441143 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:221144 assert(numElements.hasValue() &&
1145 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:271146
Uday Bondhugula0f504142019-02-04 21:48:441147 const FlatAffineConstraints *cst = region.getConstraints();
Uday Bondhugula94a03f82019-01-22 21:58:521148 // 'outerIVs' holds the values that this memory region is symbolic/paramteric
1149 // on; this would correspond to loop IVs surrounding the level at which the
1150 // slice is being materialized.
1151 SmallVector<Value *, 8> outerIVs;
1152 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
1153
1154 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:271155 SmallVector<AffineExpr, 4> offsets;
1156 offsets.reserve(rank);
1157 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:521158 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
1159
MLIR Teamc4237ae2019-01-18 16:56:271160 AffineExpr offset = top.getAffineConstantExpr(0);
1161 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
1162 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
1163 }
Uday Bondhugula94a03f82019-01-22 21:58:521164 assert(lbDivisors[d] > 0);
1165 offset =
1166 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:271167 offsets.push_back(offset);
1168 }
1169
1170 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
1171 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:221172 uint64_t bufSize =
1173 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
1174 unsigned newMemSpace;
Uday Bondhugulad4b3ff12019-02-27 00:10:191175 if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
Uday Bondhugula8be26272019-02-02 01:06:221176 newMemSpace = fastMemorySpace.getValue();
1177 } else {
1178 newMemSpace = oldMemRefType.getMemorySpace();
1179 }
1180 auto newMemRefType = top.getMemRefType(
1181 newShape, oldMemRefType.getElementType(), {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:271182 // Gather alloc operands for the dynamic dimensions of the memref.
1183 SmallVector<Value *, 4> allocOperands;
1184 unsigned dynamicDimCount = 0;
1185 for (auto dimSize : oldMemRefType.getShape()) {
1186 if (dimSize == -1)
1187 allocOperands.push_back(
River Riddleaf1abcc2019-03-25 18:13:311188 top.create<DimOp>(forOp.getLoc(), oldMemRef, dynamicDimCount++));
MLIR Teamc4237ae2019-01-18 16:56:271189 }
1190
River Riddle5052bd82019-02-02 00:42:181191 // Create new private memref for fused loop 'forOp'.
MLIR Teama0f3db402019-01-29 17:36:411192 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
1193 // consumer loop nests to reduce their live range. Currently they are added
1194 // at the beginning of the function, because loop nests can be reordered
1195 // during the fusion pass.
MLIR Teamc4237ae2019-01-18 16:56:271196 Value *newMemRef =
River Riddleaf1abcc2019-03-25 18:13:311197 top.create<AllocOp>(forOp.getLoc(), newMemRefType, allocOperands);
MLIR Teamc4237ae2019-01-18 16:56:271198
1199 // Build an AffineMap to remap access functions based on lower bound offsets.
1200 SmallVector<AffineExpr, 4> remapExprs;
1201 remapExprs.reserve(rank);
1202 unsigned zeroOffsetCount = 0;
1203 for (unsigned i = 0; i < rank; i++) {
1204 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
1205 if (constExpr.getValue() == 0)
1206 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:521207 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
1208
1209 auto remapExpr =
1210 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
1211 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:271212 }
Uday Bondhugula94a03f82019-01-22 21:58:521213 auto indexRemap =
1214 zeroOffsetCount == rank
Nicolas Vasilache0e7a8a92019-01-26 18:41:171215 ? AffineMap()
Uday Bondhugula94a03f82019-01-22 21:58:521216 : b.getAffineMap(outerIVs.size() + rank, 0, remapExprs, {});
MLIR Teamc4237ae2019-01-18 16:56:271217 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugula94a03f82019-01-22 21:58:521218 bool ret =
1219 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
1220 /*extraOperands=*/outerIVs,
River Riddleaf1abcc2019-03-25 18:13:311221 /*domInstFilter=*/&*forOp.getBody()->begin());
Uday Bondhugula94a03f82019-01-22 21:58:521222 assert(ret && "replaceAllMemrefUsesWith should always succeed here");
MLIR Team71495d52019-01-22 21:23:371223 (void)ret;
MLIR Teamc4237ae2019-01-18 16:56:271224 return newMemRef;
1225}
1226
Uday Bondhugula864d9e02019-01-23 17:16:241227// Does the slice have a single iteration?
1228static uint64_t getSliceIterationCount(
River Riddle99b87c92019-03-27 21:02:021229 const llvm::SmallDenseMap<Operation *, uint64_t, 8> &sliceTripCountMap) {
Uday Bondhugula864d9e02019-01-23 17:16:241230 uint64_t iterCount = 1;
1231 for (const auto &count : sliceTripCountMap) {
1232 iterCount *= count.second;
1233 }
1234 return iterCount;
1235}
1236
MLIR Team58aa3832019-02-16 01:12:191237// Checks if node 'srcId' (which writes to a live out memref), can be safely
1238// fused into node 'dstId'. Returns true if the following conditions are met:
1239// *) 'srcNode' writes only writes to live out 'memref'.
1240// *) 'srcNode' has exaclty one output edge on 'memref' (which is to 'dstId').
1241// *) 'dstNode' does write to 'memref'.
1242// *) 'dstNode's write region to 'memref' is a super set of 'srcNode's write
1243// region to 'memref'.
1244// TODO(andydavis) Generalize this to handle more live in/out cases.
1245static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
1246 Value *memref,
1247 MemRefDependenceGraph *mdg) {
1248 auto *srcNode = mdg->getNode(srcId);
1249 auto *dstNode = mdg->getNode(dstId);
1250
1251 // Return false if any of the following are true:
1252 // *) 'srcNode' writes to a live in/out memref other than 'memref'.
1253 // *) 'srcNode' has more than one output edge on 'memref'.
1254 // *) 'dstNode' does not write to 'memref'.
1255 if (srcNode->getStoreOpCount(memref) != 1 ||
1256 mdg->getOutEdgeCount(srcNode->id, memref) != 1 ||
1257 dstNode->getStoreOpCount(memref) == 0)
1258 return false;
1259 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOpInst' on 'memref'.
1260 auto *srcStoreOpInst = srcNode->stores.front();
1261 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471262 if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251263 LLVM_DEBUG(llvm::dbgs()
1264 << "Unable to compute MemRefRegion for source operation\n.");
1265 return false;
1266 }
MLIR Team58aa3832019-02-16 01:12:191267 SmallVector<int64_t, 4> srcShape;
1268 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
1269 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1270 Optional<int64_t> srcNumElements =
1271 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1272 if (!srcNumElements.hasValue())
1273 return false;
1274
1275 // Compute MemRefRegion 'dstWriteRegion' for 'dstStoreOpInst' on 'memref'.
River Riddle99b87c92019-03-27 21:02:021276 SmallVector<Operation *, 2> dstStoreOps;
MLIR Team58aa3832019-02-16 01:12:191277 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1278 assert(dstStoreOps.size() == 1);
1279 auto *dstStoreOpInst = dstStoreOps[0];
1280 MemRefRegion dstWriteRegion(dstStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471281 if (failed(dstWriteRegion.compute(dstStoreOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251282 LLVM_DEBUG(llvm::dbgs()
1283 << "Unable to compute MemRefRegion for dest operation\n.");
1284 return false;
1285 }
MLIR Team58aa3832019-02-16 01:12:191286 SmallVector<int64_t, 4> dstShape;
1287 // Query 'dstWriteRegion' for 'dstShape' and 'dstNumElements'.
1288 // by 'dstStoreOpInst' at depth 'dstLoopDepth'.
1289 Optional<int64_t> dstNumElements =
1290 dstWriteRegion.getConstantBoundingSizeAndShape(&dstShape);
1291 if (!dstNumElements.hasValue())
1292 return false;
1293
1294 // Return false if write region is not a superset of 'srcNodes' write
1295 // region to 'memref'.
1296 // TODO(andydavis) Check the shape and lower bounds here too.
1297 if (srcNumElements != dstNumElements)
1298 return false;
1299 return true;
1300}
1301
MLIR Teamc1ff9e82019-03-06 04:33:301302// Computes the union of all slice bounds computed between 'srcOpInst'
1303// and each load op in 'dstLoadOpInsts' at 'dstLoopDepth', and returns
1304// the union in 'sliceState'. Returns true on success, false otherwise.
1305// TODO(andydavis) Move this to a loop fusion utility function.
River Riddle99b87c92019-03-27 21:02:021306static bool getSliceUnion(Operation *srcOpInst,
1307 ArrayRef<Operation *> dstLoadOpInsts,
MLIR Teamc1ff9e82019-03-06 04:33:301308 unsigned numSrcLoopIVs, unsigned dstLoopDepth,
1309 ComputationSliceState *sliceState) {
1310 MemRefAccess srcAccess(srcOpInst);
1311 unsigned numDstLoadOpInsts = dstLoadOpInsts.size();
1312 assert(numDstLoadOpInsts > 0);
1313 // Compute the slice bounds between 'srcOpInst' and 'dstLoadOpInsts[0]'.
River Riddle1e55ae12019-03-08 06:14:471314 if (failed(mlir::getBackwardComputationSliceState(
1315 srcAccess, MemRefAccess(dstLoadOpInsts[0]), dstLoopDepth,
1316 sliceState)))
MLIR Teamc1ff9e82019-03-06 04:33:301317 return false;
1318 // Handle the common case of one dst load without a copy.
1319 if (numDstLoadOpInsts == 1)
1320 return true;
1321
1322 // Initialize 'sliceUnionCst' with the bounds computed in previous step.
1323 FlatAffineConstraints sliceUnionCst;
River Riddle1e55ae12019-03-08 06:14:471324 if (failed(sliceState->getAsConstraints(&sliceUnionCst))) {
MLIR Teamc1ff9e82019-03-06 04:33:301325 LLVM_DEBUG(llvm::dbgs() << "Unable to compute slice bound constraints\n.");
1326 return false;
1327 }
1328
1329 // Compute the union of slice bounds between 'srcOpInst' and each load
1330 // in 'dstLoadOpInsts' in range [1, numDstLoadOpInsts), in 'sliceUnionCst'.
1331 for (unsigned i = 1; i < numDstLoadOpInsts; ++i) {
1332 MemRefAccess dstAccess(dstLoadOpInsts[i]);
1333 // Compute slice bounds for 'srcOpInst' and 'dstLoadOpInsts[i]'.
1334 ComputationSliceState tmpSliceState;
River Riddle1e55ae12019-03-08 06:14:471335 if (failed(mlir::getBackwardComputationSliceState(
1336 srcAccess, dstAccess, dstLoopDepth, &tmpSliceState))) {
MLIR Teamc1ff9e82019-03-06 04:33:301337 LLVM_DEBUG(llvm::dbgs() << "Unable to compute slice bounds\n.");
1338 return false;
1339 }
1340
1341 // Compute constraints for 'tmpSliceState' in 'tmpSliceCst'.
1342 FlatAffineConstraints tmpSliceCst;
River Riddle1e55ae12019-03-08 06:14:471343 if (failed(tmpSliceState.getAsConstraints(&tmpSliceCst))) {
MLIR Teamc1ff9e82019-03-06 04:33:301344 LLVM_DEBUG(llvm::dbgs()
1345 << "Unable to compute slice bound constraints\n.");
1346 return false;
1347 }
1348 // Compute union bounding box of 'sliceUnionCst' and 'tmpSliceCst'.
River Riddle1e55ae12019-03-08 06:14:471349 if (failed(sliceUnionCst.unionBoundingBox(tmpSliceCst))) {
MLIR Teamc1ff9e82019-03-06 04:33:301350 LLVM_DEBUG(llvm::dbgs()
1351 << "Unable to compute union bounding box of slice bounds.\n.");
1352 return false;
1353 }
1354 }
1355
1356 // Convert any dst loop IVs which are symbol identifiers to dim identifiers.
1357 sliceUnionCst.convertLoopIVSymbolsToDims();
1358
1359 sliceState->clearBounds();
1360 sliceState->lbs.resize(numSrcLoopIVs, AffineMap());
1361 sliceState->ubs.resize(numSrcLoopIVs, AffineMap());
1362
1363 // Get slice bounds from slice union constraints 'sliceUnionCst'.
1364 sliceUnionCst.getSliceBounds(numSrcLoopIVs, srcOpInst->getContext(),
1365 &sliceState->lbs, &sliceState->ubs);
1366 // Add slice bound operands of union.
1367 SmallVector<Value *, 4> sliceBoundOperands;
1368 sliceUnionCst.getIdValues(numSrcLoopIVs,
1369 sliceUnionCst.getNumDimAndSymbolIds(),
1370 &sliceBoundOperands);
1371 // Give each bound its own copy of 'sliceBoundOperands' for subsequent
1372 // canonicalization.
1373 sliceState->lbOperands.resize(numSrcLoopIVs, sliceBoundOperands);
1374 sliceState->ubOperands.resize(numSrcLoopIVs, sliceBoundOperands);
1375 return true;
1376}
1377
MLIR Team27d067e2019-01-16 17:55:021378// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411379// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
MLIR Teamd038e342019-03-01 19:50:251380// The argument 'srcStoreOpInst' is used to calculate the storage reduction on
1381// the memref being produced and consumed, which is an input to the cost model.
1382// For producer-constumer fusion, 'srcStoreOpInst' will be the same as
1383// 'srcOpInst', as we are slicing w.r.t to that producer.
1384// For input-reuse fusion, 'srcOpInst' will be the src loop nest LoadOp which
1385// reads from the same memref as dst loop nest load ops, and 'srcStoreOpInst'
1386// will be the unique store op in the src node, which will be used to check
1387// that the write region is the same after input-reuse fusion.
Uday Bondhugulab4a14432019-01-26 00:00:501388// Returns true if it is profitable to fuse the candidate loop nests. Returns
1389// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1390// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251391// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021392// *) Computes the backward computation slice at 'srcOpInst'. This
1393// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251394// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021395// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251396// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1397// loop nest is the total number of dynamic operation instances in the loop
1398// nest).
1399// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021400// loop nest at various values of dst loop depth, attempting to fuse
1401// the largest compution slice at the maximal dst loop depth (closest to the
1402// load) to minimize reuse distance and potentially enable subsequent
1403// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411404// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021405// the same memref as is written by 'srcOpInst', then the union of slice
1406// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501407// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251408// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021409// NOTE: We attempt to maximize the dst loop depth, but there are cases
1410// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251411// loop (within the src computation slice) at a depth which results in
1412// execessive recomputation (see unit tests for examples).
1413// *) Compares the total cost of the unfused loop nests to the min cost fused
1414// loop nest computed in the previous step, and returns true if the latter
1415// is lower.
River Riddle99b87c92019-03-27 21:02:021416static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
1417 ArrayRef<Operation *> dstLoadOpInsts,
1418 ArrayRef<Operation *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251419 ComputationSliceState *sliceState,
Uday Bondhugulace7e59532019-03-08 17:21:521420 unsigned *dstLoopDepth, bool maximalFusion) {
Uday Bondhugula06d21d92019-01-25 01:01:491421 LLVM_DEBUG({
1422 llvm::dbgs() << "Checking whether fusion is profitable between:\n";
Uday Bondhugulaa1dad3a2019-02-20 02:17:191423 llvm::dbgs() << " " << *srcOpInst << " and \n";
MLIR Teamd7c82442019-01-30 23:53:411424 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191425 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491426 };
1427 });
Uday Bondhugula864d9e02019-01-23 17:16:241428
MLIR Team38c2fe32019-01-14 19:26:251429 // Compute cost of sliced and unsliced src loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051430 SmallVector<AffineForOp, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021431 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251432 unsigned numSrcLoopIVs = srcLoopIVs.size();
1433
1434 // Walk src loop nest and collect stats.
1435 LoopNestStats srcLoopNestStats;
1436 LoopNestStatsCollector srcStatsCollector(&srcLoopNestStats);
River Riddlef9d91532019-03-27 00:05:091437 srcStatsCollector.collect(srcLoopIVs[0].getOperation());
MLIR Team38c2fe32019-01-14 19:26:251438 // Currently only constant trip count loop nests are supported.
MLIR Teamc1ff9e82019-03-06 04:33:301439 if (srcStatsCollector.hasLoopWithNonConstTripCount) {
1440 LLVM_DEBUG(llvm::dbgs() << "Non-constant trip count loops unsupported.\n");
MLIR Team38c2fe32019-01-14 19:26:251441 return false;
MLIR Teamc1ff9e82019-03-06 04:33:301442 }
MLIR Team38c2fe32019-01-14 19:26:251443 // Compute cost of dst loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051444 SmallVector<AffineForOp, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411445 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251446
1447 LoopNestStats dstLoopNestStats;
1448 LoopNestStatsCollector dstStatsCollector(&dstLoopNestStats);
River Riddlef9d91532019-03-27 00:05:091449 dstStatsCollector.collect(dstLoopIVs[0].getOperation());
MLIR Team38c2fe32019-01-14 19:26:251450 // Currently only constant trip count loop nests are supported.
MLIR Teamc1ff9e82019-03-06 04:33:301451 if (dstStatsCollector.hasLoopWithNonConstTripCount) {
1452 LLVM_DEBUG(llvm::dbgs() << "Non-constant trip count loops unsupported.\n");
MLIR Team38c2fe32019-01-14 19:26:251453 return false;
MLIR Teamc1ff9e82019-03-06 04:33:301454 }
MLIR Team38c2fe32019-01-14 19:26:251455
MLIR Teamd7c82442019-01-30 23:53:411456 // Compute the maximum loop depth at which we can can insert the src slice
MLIR Teamd038e342019-03-01 19:50:251457 // and still satisfy dest loop nest dependences, for producer-consumer fusion.
1458 unsigned maxDstLoopDepth =
1459 (srcOpInst == srcStoreOpInst)
1460 ? getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts)
1461 : dstLoopIVs.size();
MLIR Teamc1ff9e82019-03-06 04:33:301462 if (maxDstLoopDepth == 0) {
1463 LLVM_DEBUG(llvm::dbgs() << "Can't fuse: maxDstLoopDepth == 0 .\n");
MLIR Team27d067e2019-01-16 17:55:021464 return false;
MLIR Teamc1ff9e82019-03-06 04:33:301465 }
MLIR Team27d067e2019-01-16 17:55:021466
1467 // Search for min cost value for 'dstLoopDepth'. At each value of
1468 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1469 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1470 // of these bounds). Next the union slice bounds are used to calculate
1471 // the cost of the slice and the cost of the slice inserted into the dst
1472 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241473 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
MLIR Teamd038e342019-03-01 19:50:251474 double maxStorageReduction = 0.0;
Uday Bondhugula864d9e02019-01-23 17:16:241475 Optional<uint64_t> sliceMemEstimate = None;
1476
MLIR Team27d067e2019-01-16 17:55:021477 SmallVector<ComputationSliceState, 4> sliceStates;
1478 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241479 // The best loop depth at which to materialize the slice.
1480 Optional<unsigned> bestDstLoopDepth = None;
1481
1482 // Compute op instance count for the src loop nest without iteration slicing.
River Riddle5052bd82019-02-02 00:42:181483 uint64_t srcLoopNestCost =
River Riddlef9d91532019-03-27 00:05:091484 getComputeCost(srcLoopIVs[0].getOperation(), &srcLoopNestStats,
River Riddle5052bd82019-02-02 00:42:181485 /*tripCountOverrideMap=*/nullptr,
1486 /*computeCostMap=*/nullptr);
Uday Bondhugula864d9e02019-01-23 17:16:241487
MLIR Teamb9dde912019-02-06 19:01:101488 // Compute src loop nest write region size.
MLIR Teamd038e342019-03-01 19:50:251489 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471490 if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251491 LLVM_DEBUG(llvm::dbgs()
River Riddle99b87c92019-03-27 21:02:021492 << "Unable to compute MemRefRegion for source operation\n.");
MLIR Teamd42ef782019-03-04 19:01:251493 return false;
1494 }
1495
MLIR Teamb9dde912019-02-06 19:01:101496 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1497 srcWriteRegion.getRegionSize();
1498 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1499 return false;
1500 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1501
Uday Bondhugula864d9e02019-01-23 17:16:241502 // Compute op instance count for the src loop nest.
River Riddle5052bd82019-02-02 00:42:181503 uint64_t dstLoopNestCost =
River Riddlef9d91532019-03-27 00:05:091504 getComputeCost(dstLoopIVs[0].getOperation(), &dstLoopNestStats,
River Riddle5052bd82019-02-02 00:42:181505 /*tripCountOverrideMap=*/nullptr,
1506 /*computeCostMap=*/nullptr);
MLIR Team27d067e2019-01-16 17:55:021507
MLIR Teamb9dde912019-02-06 19:01:101508 // Evaluate all depth choices for materializing the slice in the destination
1509 // loop nest.
River Riddle99b87c92019-03-27 21:02:021510 llvm::SmallDenseMap<Operation *, uint64_t, 8> sliceTripCountMap;
1511 DenseMap<Operation *, int64_t> computeCostMap;
MLIR Team27d067e2019-01-16 17:55:021512 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
MLIR Teamc1ff9e82019-03-06 04:33:301513 // Compute the union of slice bounds of all ops in 'dstLoadOpInsts'.
1514 if (!getSliceUnion(srcOpInst, dstLoadOpInsts, numSrcLoopIVs, i,
1515 &sliceStates[i - 1])) {
1516 LLVM_DEBUG(llvm::dbgs()
1517 << "getSliceUnion failed for loopDepth: " << i << "\n");
1518 continue;
MLIR Team38c2fe32019-01-14 19:26:251519 }
MLIR Teamc1ff9e82019-03-06 04:33:301520
Uday Bondhugulab4a14432019-01-26 00:00:501521 // Build trip count map for computation slice. We'll skip cases where the
1522 // trip count was non-constant.
MLIR Team27d067e2019-01-16 17:55:021523 sliceTripCountMap.clear();
1524 if (!buildSliceTripCountMap(srcOpInst, &sliceStates[i - 1],
MLIR Teamc1ff9e82019-03-06 04:33:301525 &sliceTripCountMap)) {
1526 LLVM_DEBUG(llvm::dbgs() << "Unable to build slice trip count map.\n.");
Uday Bondhugula864d9e02019-01-23 17:16:241527 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301528 }
Uday Bondhugula864d9e02019-01-23 17:16:241529
1530 // Checks whether a store to load forwarding will happen.
1531 int64_t sliceIterationCount = getSliceIterationCount(sliceTripCountMap);
Uday Bondhugula864d9e02019-01-23 17:16:241532 assert(sliceIterationCount > 0);
Uday Bondhugulab4a14432019-01-26 00:00:501533 bool storeLoadFwdGuaranteed = (sliceIterationCount == 1);
Uday Bondhugula864d9e02019-01-23 17:16:241534
1535 // Compute cost of fusion for this dest loop depth.
1536
1537 computeCostMap.clear();
1538
1539 // The store and loads to this memref will disappear.
MLIR Teamd038e342019-03-01 19:50:251540 // TODO(andydavis) Add load coalescing to memref data flow opt pass.
Uday Bondhugula864d9e02019-01-23 17:16:241541 if (storeLoadFwdGuaranteed) {
1542 // A single store disappears: -1 for that.
River Riddlef9d91532019-03-27 00:05:091543 computeCostMap[srcLoopIVs[numSrcLoopIVs - 1].getOperation()] = -1;
MLIR Teamd7c82442019-01-30 23:53:411544 for (auto *loadOp : dstLoadOpInsts) {
River Riddle9c085402019-03-27 15:55:171545 auto *parentInst = loadOp->getParentOp();
River Riddleb4992772019-02-04 18:38:471546 if (parentInst && parentInst->isa<AffineForOp>())
River Riddle5052bd82019-02-02 00:42:181547 computeCostMap[parentInst] = -1;
Uday Bondhugula864d9e02019-01-23 17:16:241548 }
1549 }
MLIR Team27d067e2019-01-16 17:55:021550
MLIR Team38c2fe32019-01-14 19:26:251551 // Compute op instance count for the src loop nest with iteration slicing.
Uday Bondhugula864d9e02019-01-23 17:16:241552 int64_t sliceComputeCost =
River Riddlef9d91532019-03-27 00:05:091553 getComputeCost(srcLoopIVs[0].getOperation(), &srcLoopNestStats,
Uday Bondhugula864d9e02019-01-23 17:16:241554 /*tripCountOverrideMap=*/&sliceTripCountMap,
1555 /*computeCostMap=*/&computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:251556
Uday Bondhugula864d9e02019-01-23 17:16:241557 // Compute cost of fusion for this depth.
River Riddlef9d91532019-03-27 00:05:091558 computeCostMap[dstLoopIVs[i - 1].getOperation()] = sliceComputeCost;
Uday Bondhugula864d9e02019-01-23 17:16:241559
1560 int64_t fusedLoopNestComputeCost =
River Riddlef9d91532019-03-27 00:05:091561 getComputeCost(dstLoopIVs[0].getOperation(), &dstLoopNestStats,
MLIR Team27d067e2019-01-16 17:55:021562 /*tripCountOverrideMap=*/nullptr, &computeCostMap);
Uday Bondhugula864d9e02019-01-23 17:16:241563
1564 double additionalComputeFraction =
1565 fusedLoopNestComputeCost /
1566 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1567 1;
1568
MLIR Teamb9dde912019-02-06 19:01:101569 // Compute what the slice write MemRefRegion would be, if the src loop
1570 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1571 // nest at loop depth 'i'
MLIR Teamd038e342019-03-01 19:50:251572 MemRefRegion sliceWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471573 if (failed(sliceWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0,
1574 &sliceStates[i - 1]))) {
MLIR Teamc1ff9e82019-03-06 04:33:301575 LLVM_DEBUG(llvm::dbgs()
1576 << "Failed to compute slice write region at loopDepth: " << i
1577 << "\n");
MLIR Teamd42ef782019-03-04 19:01:251578 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301579 }
MLIR Teamd42ef782019-03-04 19:01:251580
MLIR Teamb9dde912019-02-06 19:01:101581 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1582 sliceWriteRegion.getRegionSize();
1583 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
MLIR Teamc1ff9e82019-03-06 04:33:301584 maybeSliceWriteRegionSizeBytes.getValue() == 0) {
1585 LLVM_DEBUG(llvm::dbgs()
1586 << "Failed to get slice write region size at loopDepth: " << i
1587 << "\n");
MLIR Teamb9dde912019-02-06 19:01:101588 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301589 }
MLIR Teamb9dde912019-02-06 19:01:101590 int64_t sliceWriteRegionSizeBytes =
1591 maybeSliceWriteRegionSizeBytes.getValue();
1592
MLIR Teamd038e342019-03-01 19:50:251593 // If we are fusing for reuse, check that write regions remain the same.
1594 // TODO(andydavis) Write region check should check sizes and offsets in
1595 // each dimension, so that we are sure they are covering the same memref
1596 // region. Also, move this out to a isMemRefRegionSuperSet helper function.
1597 if (srcOpInst != srcStoreOpInst &&
1598 sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes)
1599 continue;
1600
MLIR Teamb9dde912019-02-06 19:01:101601 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1602 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241603
Uday Bondhugula06d21d92019-01-25 01:01:491604 LLVM_DEBUG({
1605 std::stringstream msg;
1606 msg << " evaluating fusion profitability at depth : " << i << "\n"
Uday Bondhugulad4b3ff12019-02-27 00:10:191607 << std::fixed << std::setprecision(2)
1608 << " additional compute fraction: "
Uday Bondhugula06d21d92019-01-25 01:01:491609 << 100.0 * additionalComputeFraction << "%\n"
1610 << " storage reduction factor: " << storageReduction << "x\n"
1611 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191612 << " slice iteration count: " << sliceIterationCount << "\n"
1613 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1614 << " slice write region size: " << sliceWriteRegionSizeBytes
1615 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491616 llvm::dbgs() << msg.str();
1617 });
Uday Bondhugula864d9e02019-01-23 17:16:241618
1619 double computeToleranceThreshold =
1620 clFusionAddlComputeTolerance.getNumOccurrences() > 0
1621 ? clFusionAddlComputeTolerance
1622 : LoopFusion::kComputeToleranceThreshold;
1623
1624 // TODO(b/123247369): This is a placeholder cost model.
1625 // Among all choices that add an acceptable amount of redundant computation
1626 // (as per computeToleranceThreshold), we will simply pick the one that
1627 // reduces the intermediary size the most.
1628 if ((storageReduction > maxStorageReduction) &&
Uday Bondhugulace7e59532019-03-08 17:21:521629 (maximalFusion ||
Uday Bondhugula864d9e02019-01-23 17:16:241630 (additionalComputeFraction < computeToleranceThreshold))) {
1631 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021632 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241633 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101634 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251635 }
1636 }
1637
Uday Bondhugula864d9e02019-01-23 17:16:241638 // A simple cost model: fuse if it reduces the memory footprint. If
1639 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251640
Uday Bondhugulace7e59532019-03-08 17:21:521641 if (!maximalFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191642 LLVM_DEBUG(
1643 llvm::dbgs()
1644 << "All fusion choices involve more than the threshold amount of "
1645 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251646 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241647 }
1648
MLIR Teamd42ef782019-03-04 19:01:251649 if (!bestDstLoopDepth.hasValue()) {
1650 LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n");
1651 return false;
1652 }
Uday Bondhugula864d9e02019-01-23 17:16:241653
1654 // Set dstLoopDepth based on best values from search.
1655 *dstLoopDepth = bestDstLoopDepth.getValue();
1656
1657 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491658 llvm::dbgs() << " LoopFusion fusion stats:"
1659 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241660 << "\n src loop nest compute cost: " << srcLoopNestCost
1661 << "\n dst loop nest compute cost: " << dstLoopNestCost
1662 << "\n fused loop nest compute cost: "
1663 << minFusedLoopNestComputeCost << "\n");
1664
River Riddle5052bd82019-02-02 00:42:181665 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1666 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241667
1668 Optional<double> storageReduction = None;
1669
Uday Bondhugulace7e59532019-03-08 17:21:521670 if (!maximalFusion) {
Uday Bondhugula864d9e02019-01-23 17:16:241671 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1672 LLVM_DEBUG(
1673 llvm::dbgs()
1674 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1675 return false;
1676 }
1677
1678 auto srcMemSizeVal = srcMemSize.getValue();
1679 auto dstMemSizeVal = dstMemSize.getValue();
1680
1681 assert(sliceMemEstimate.hasValue() && "expected value");
Uday Bondhugula864d9e02019-01-23 17:16:241682 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1683
1684 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1685 << " dst mem: " << dstMemSizeVal << "\n"
1686 << " fused mem: " << fusedMem << "\n"
1687 << " slice mem: " << sliceMemEstimate << "\n");
1688
1689 if (fusedMem > srcMemSizeVal + dstMemSizeVal) {
1690 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1691 return false;
1692 }
1693 storageReduction =
1694 100.0 *
1695 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1696 }
1697
1698 double additionalComputeFraction =
1699 100.0 * (minFusedLoopNestComputeCost /
1700 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1701 1);
MLIR Team5c5739d2019-01-25 06:27:401702 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491703 LLVM_DEBUG({
1704 std::stringstream msg;
1705 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591706 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491707 << "% redundant computation and a ";
1708 msg << (storageReduction.hasValue()
1709 ? std::to_string(storageReduction.getValue())
1710 : "<unknown>");
1711 msg << "% storage reduction.\n";
1712 llvm::dbgs() << msg.str();
1713 });
Uday Bondhugula864d9e02019-01-23 17:16:241714
MLIR Team27d067e2019-01-16 17:55:021715 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241716 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021717 sliceState->lbs = bestSliceState->lbs;
1718 sliceState->ubs = bestSliceState->ubs;
1719 sliceState->lbOperands = bestSliceState->lbOperands;
1720 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241721
MLIR Team27d067e2019-01-16 17:55:021722 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251723 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171724 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021725 canonicalizeMapAndOperands(&sliceState->lbs[i],
1726 &sliceState->lbOperands[i]);
1727 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171728 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021729 canonicalizeMapAndOperands(&sliceState->ubs[i],
1730 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251731 }
1732 }
1733 return true;
1734}
1735
MLIR Teamd038e342019-03-01 19:50:251736// GreedyFusion greedily fuses loop nests which have a producer/consumer or
1737// input-reuse relationship on a memref, with the goal of improving locality.
MLIR Teamf28e4df2018-11-01 14:26:001738//
MLIR Teamd038e342019-03-01 19:50:251739// The steps of the producer-consumer fusion algorithm are as follows:
MLIR Team3b692302018-12-17 17:57:141740//
MLIR Team6892ffb2018-12-20 04:42:551741// *) A worklist is initialized with node ids from the dependence graph.
1742// *) For each node id in the worklist:
River Riddle5052bd82019-02-02 00:42:181743// *) Pop a AffineForOp of the worklist. This 'dstAffineForOp' will be a
1744// candidate destination AffineForOp into which fusion will be attempted.
1745// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141746// *) For each LoadOp in 'dstLoadOps' do:
MLIR Teamd038e342019-03-01 19:50:251747// *) Lookup dependent loop nests which have a single store op to the same
1748// memref.
1749// *) Check if dependences would be violated by the fusion.
MLIR Team6892ffb2018-12-20 04:42:551750// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141751// bounds to be functions of 'dstLoopNest' IVs and symbols.
1752// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
MLIR Teamd038e342019-03-01 19:50:251753// at a loop depth determined by the cost model in 'isFusionProfitable'.
River Riddle99b87c92019-03-27 21:02:021754// *) Add the newly fused load/store operations to the state,
MLIR Team3b692302018-12-17 17:57:141755// and also add newly fuse load ops to 'dstLoopOps' to be considered
1756// as fusion dst load ops in another iteration.
1757// *) Remove old src loop nest and its associated state.
1758//
MLIR Teamd038e342019-03-01 19:50:251759// The steps of the input-reuse fusion algorithm are as follows:
1760//
1761// *) Initialize 'worklist' with node ids from the dependence graph.
1762// *) For each 'dstNode' in the worklist:
1763// *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which
1764// loads from the same memref, but which has no dependence paths to/from.
1765// *) Get a computation slice of 'sibLoopNest', which adjusts its loop
1766// bounds to be functions of 'dstLoopNest' IVs and symbols.
1767// *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest',
1768// at a loop depth determined by the cost model in 'isFusionProfitable'.
1769// This function also checks that the memref write region of 'sibLoopNest',
1770// is preserved in the fused loop nest.
1771// *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'.
1772//
River Riddle99b87c92019-03-27 21:02:021773// Given a graph where top-level operations are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141774// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551775// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141776//
MLIR Team6892ffb2018-12-20 04:42:551777// This greedy algorithm is not 'maximal' due to the current restriction of
1778// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141779//
1780// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551781struct GreedyFusion {
1782public:
MLIR Teamd038e342019-03-01 19:50:251783 // The data dependence graph to traverse during fusion.
MLIR Team6892ffb2018-12-20 04:42:551784 MemRefDependenceGraph *mdg;
MLIR Teamd038e342019-03-01 19:50:251785 // Worklist of graph nodes visited during the fusion pass.
MLIR Teama78edcd2019-02-05 14:57:081786 SmallVector<unsigned, 8> worklist;
MLIR Teamd038e342019-03-01 19:50:251787 // Set of graph nodes which are present on the worklist.
MLIR Teama78edcd2019-02-05 14:57:081788 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamd038e342019-03-01 19:50:251789 // Parameter for local buffer size threshold.
1790 unsigned localBufSizeThreshold;
1791 // Parameter for fast memory space.
1792 Optional<unsigned> fastMemorySpace;
Uday Bondhugulace7e59532019-03-08 17:21:521793 // If true, ignore any additional (redundant) computation tolerance threshold
1794 // that would have prevented fusion.
1795 bool maximalFusion;
MLIR Teamf28e4df2018-11-01 14:26:001796
MLIR Teamd038e342019-03-01 19:50:251797 using Node = MemRefDependenceGraph::Node;
1798
1799 GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold,
Uday Bondhugulace7e59532019-03-08 17:21:521800 Optional<unsigned> fastMemorySpace, bool maximalFusion)
MLIR Teamd038e342019-03-01 19:50:251801 : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold),
Uday Bondhugulace7e59532019-03-08 17:21:521802 fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {}
MLIR Teamd038e342019-03-01 19:50:251803
1804 // Initializes 'worklist' with nodes from 'mdg'
1805 void init() {
MLIR Teama78edcd2019-02-05 14:57:081806 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1807 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Teamd038e342019-03-01 19:50:251808 worklist.clear();
1809 worklistSet.clear();
1810 for (auto &idAndNode : mdg->nodes) {
1811 const Node &node = idAndNode.second;
1812 worklist.push_back(node.id);
1813 worklistSet.insert(node.id);
1814 }
MLIR Team6892ffb2018-12-20 04:42:551815 }
MLIR Team3b692302018-12-17 17:57:141816
MLIR Teamd038e342019-03-01 19:50:251817 // Run the GreedyFusion pass.
1818 // *) First pass through the nodes fuses single-use producer nodes into their
1819 // unique consumer.
1820 // *) Second pass fuses sibling nodes which share no dependence edges.
1821 // *) Third pass fuses any remaining producer nodes into their users.
1822 void run() {
MLIR Teamc1ff9e82019-03-06 04:33:301823 // TODO(andydavis) Run this repeatedly until a fixed-point is reached.
MLIR Teamd038e342019-03-01 19:50:251824 fuseProducerConsumerNodes(/*maxSrcUserCount=*/1);
1825 fuseSiblingNodes();
1826 fuseProducerConsumerNodes(
1827 /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max());
1828 eraseUnusedMemRefAllocations();
1829 }
1830
1831 void fuseProducerConsumerNodes(unsigned maxSrcUserCount) {
1832 init();
MLIR Team3b692302018-12-17 17:57:141833 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551834 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141835 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081836 worklistSet.erase(dstId);
1837
MLIR Team6892ffb2018-12-20 04:42:551838 // Skip if this node was removed (fused into another node).
1839 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141840 continue;
MLIR Team6892ffb2018-12-20 04:42:551841 // Get 'dstNode' into which to attempt fusion.
1842 auto *dstNode = mdg->getNode(dstId);
1843 // Skip if 'dstNode' is not a loop nest.
River Riddle99b87c92019-03-27 21:02:021844 if (!dstNode->op->isa<AffineForOp>())
MLIR Team3b692302018-12-17 17:57:141845 continue;
MLIR Team8f5f2c72019-02-15 17:32:181846 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1847 // while preserving relative order. This can increase the maximum loop
1848 // depth at which we can fuse a slice of a producer loop nest into a
1849 // consumer loop nest.
1850 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141851
River Riddle99b87c92019-03-27 21:02:021852 SmallVector<Operation *, 4> loads = dstNode->loads;
1853 SmallVector<Operation *, 4> dstLoadOpInsts;
MLIR Teamc4237ae2019-01-18 16:56:271854 DenseSet<Value *> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551855 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021856 // Get memref of load on top of the stack.
River Riddle96ebde92019-03-25 20:02:061857 auto *memref = loads.back()->cast<LoadOp>().getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271858 if (visitedMemrefs.count(memref) > 0)
1859 continue;
1860 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021861 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1862 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551863 // Skip if no input edges along which to fuse.
1864 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141865 continue;
MLIR Team1e851912019-01-31 00:01:461866 // Iterate through in edges for 'dstId' and src node id for any
1867 // edges on 'memref'.
1868 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551869 for (auto &srcEdge : mdg->inEdges[dstId]) {
1870 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411871 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551872 continue;
MLIR Team1e851912019-01-31 00:01:461873 srcNodeIds.push_back(srcEdge.id);
1874 }
1875 for (unsigned srcId : srcNodeIds) {
1876 // Skip if this node was removed (fused into another node).
1877 if (mdg->nodes.count(srcId) == 0)
1878 continue;
1879 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1880 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551881 // Skip if 'srcNode' is not a loop nest.
River Riddle99b87c92019-03-27 21:02:021882 if (!srcNode->op->isa<AffineForOp>())
MLIR Team6892ffb2018-12-20 04:42:551883 continue;
MLIR Teamb28009b2019-01-23 19:11:431884 // Skip if 'srcNode' has more than one store to any memref.
1885 // TODO(andydavis) Support fusing multi-output src loop nests.
1886 if (srcNode->stores.size() != 1)
MLIR Team6892ffb2018-12-20 04:42:551887 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241888
MLIR Teama0f3db402019-01-29 17:36:411889 // Skip 'srcNode' if it has in edges on 'memref'.
MLIR Team6892ffb2018-12-20 04:42:551890 // TODO(andydavis) Track dependence type with edges, and just check
MLIR Teama0f3db402019-01-29 17:36:411891 // for WAW dependence edge here. Note that this check is overly
1892 // conservative and will be removed in the future.
1893 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) != 0)
MLIR Team6892ffb2018-12-20 04:42:551894 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241895
MLIR Team58aa3832019-02-16 01:12:191896 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1897 // and cannot be fused.
1898 bool writesToLiveInOrOut =
1899 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1900 if (writesToLiveInOrOut &&
1901 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, memref, mdg))
MLIR Teamd7c82442019-01-30 23:53:411902 continue;
1903
MLIR Teamd038e342019-03-01 19:50:251904 // Skip if 'srcNode' out edge count on 'memref' > 'maxSrcUserCount'.
1905 if (mdg->getOutEdgeCount(srcNode->id, memref) > maxSrcUserCount)
1906 continue;
1907
River Riddle99b87c92019-03-27 21:02:021908 // Compute an operation list insertion point for the fused loop
MLIR Teama0f3db402019-01-29 17:36:411909 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:021910 Operation *insertPointInst =
MLIR Teama78edcd2019-02-05 14:57:081911 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411912 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551913 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241914
MLIR Team6892ffb2018-12-20 04:42:551915 // Get unique 'srcNode' store op.
Chris Lattner456ad6a2018-12-29 00:05:351916 auto *srcStoreOpInst = srcNode->stores.front();
MLIR Teamd7c82442019-01-30 23:53:411917 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021918 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411919 for (auto *storeOpInst : dstNode->stores)
River Riddle96ebde92019-03-25 20:02:061920 if (storeOpInst->cast<StoreOp>().getMemRef() == memref)
MLIR Teamd7c82442019-01-30 23:53:411921 dstStoreOpInsts.push_back(storeOpInst);
1922
Uday Bondhugulab4a14432019-01-26 00:00:501923 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251924 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411925 // Check if fusion would be profitable.
MLIR Teamd038e342019-03-01 19:50:251926 if (!isFusionProfitable(srcStoreOpInst, srcStoreOpInst,
1927 dstLoadOpInsts, dstStoreOpInsts, &sliceState,
Uday Bondhugulace7e59532019-03-08 17:21:521928 &bestDstLoopDepth, maximalFusion))
MLIR Team38c2fe32019-01-14 19:26:251929 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241930
MLIR Team6892ffb2018-12-20 04:42:551931 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181932 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Uday Bondhugulab4a14432019-01-26 00:00:501933 srcStoreOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
Chris Lattnerd9b5bc82019-03-25 02:53:051934 if (sliceLoopNest) {
River Riddleaf1abcc2019-03-25 18:13:311935 LLVM_DEBUG(llvm::dbgs() << "\tslice loop nest:\n"
River Riddlef9d91532019-03-27 00:05:091936 << *sliceLoopNest.getOperation() << "\n");
River Riddle5052bd82019-02-02 00:42:181937 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddle99b87c92019-03-27 21:02:021938 auto dstAffineForOp = dstNode->op->cast<AffineForOp>();
River Riddlef9d91532019-03-27 00:05:091939 if (insertPointInst != dstAffineForOp.getOperation()) {
1940 dstAffineForOp.getOperation()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411941 }
MLIR Teamc4237ae2019-01-18 16:56:271942 // Update edges between 'srcNode' and 'dstNode'.
MLIR Teama0f3db402019-01-29 17:36:411943 mdg->updateEdges(srcNode->id, dstNode->id, memref);
MLIR Teamc4237ae2019-01-18 16:56:271944
1945 // Collect slice loop stats.
1946 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:091947 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271948 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181949 for (auto forOp : sliceCollector.forOps) {
1950 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551951 }
MLIR Team58aa3832019-02-16 01:12:191952 if (!writesToLiveInOrOut) {
1953 // Create private memref for 'memref' in 'dstAffineForOp'.
River Riddle99b87c92019-03-27 21:02:021954 SmallVector<Operation *, 4> storesForMemref;
MLIR Team58aa3832019-02-16 01:12:191955 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
River Riddle96ebde92019-03-25 20:02:061956 if (storeOpInst->cast<StoreOp>().getMemRef() == memref)
MLIR Team58aa3832019-02-16 01:12:191957 storesForMemref.push_back(storeOpInst);
1958 }
1959 assert(storesForMemref.size() == 1);
1960 auto *newMemRef = createPrivateMemRef(
1961 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1962 fastMemorySpace, localBufSizeThreshold);
1963 visitedMemrefs.insert(newMemRef);
1964 // Create new node in dependence graph for 'newMemRef' alloc op.
1965 unsigned newMemRefNodeId =
River Riddlef9d91532019-03-27 00:05:091966 mdg->addNode(newMemRef->getDefiningOp());
MLIR Team58aa3832019-02-16 01:12:191967 // Add edge from 'newMemRef' node to dstNode.
1968 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271969 }
MLIR Teamc4237ae2019-01-18 16:56:271970
1971 // Collect dst loop stats after memref privatizaton transformation.
1972 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:091973 dstLoopCollector.collect(dstAffineForOp.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271974
1975 // Add new load ops to current Node load op list 'loads' to
1976 // continue fusing based on new operands.
1977 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
River Riddle96ebde92019-03-25 20:02:061978 auto *loadMemRef = loadOpInst->cast<LoadOp>().getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271979 if (visitedMemrefs.count(loadMemRef) == 0)
1980 loads.push_back(loadOpInst);
1981 }
1982
1983 // Clear and add back loads and stores
1984 mdg->clearNodeLoadAndStores(dstNode->id);
1985 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1986 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371987 // Remove old src loop nest if it no longer has outgoing dependence
1988 // edges, and it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191989 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1990 // been fused into 'dstNode' and write region of 'dstNode' covers
1991 // the write region of 'srcNode', and 'srcNode' has no other users
1992 // so it is safe to remove.
1993 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271994 mdg->removeNode(srcNode->id);
River Riddle99b87c92019-03-27 21:02:021995 srcNode->op->erase();
MLIR Teama78edcd2019-02-05 14:57:081996 } else {
1997 // Add remaining users of 'oldMemRef' back on the worklist (if not
1998 // already there), as its replacement with a local/private memref
1999 // has reduced dependences on 'oldMemRef' which may have created
2000 // new fusion opportunities.
2001 if (mdg->outEdges.count(srcNode->id) > 0) {
2002 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
2003 mdg->outEdges[srcNode->id];
2004 for (auto &outEdge : oldOutEdges) {
2005 if (outEdge.value == memref &&
2006 worklistSet.count(outEdge.id) == 0) {
2007 worklist.push_back(outEdge.id);
2008 worklistSet.insert(outEdge.id);
2009 }
2010 }
2011 }
MLIR Teamc4237ae2019-01-18 16:56:272012 }
MLIR Team3b692302018-12-17 17:57:142013 }
MLIR Team3b692302018-12-17 17:57:142014 }
2015 }
2016 }
MLIR Teamd038e342019-03-01 19:50:252017 }
2018
2019 // Visits each node in the graph, and for each node, attempts to fuse it with
2020 // its sibling nodes (nodes which share a parent, but no dependence edges).
2021 void fuseSiblingNodes() {
2022 init();
2023 while (!worklist.empty()) {
2024 unsigned dstId = worklist.back();
2025 worklist.pop_back();
2026 worklistSet.erase(dstId);
2027
2028 // Skip if this node was removed (fused into another node).
2029 if (mdg->nodes.count(dstId) == 0)
2030 continue;
2031 // Get 'dstNode' into which to attempt fusion.
2032 auto *dstNode = mdg->getNode(dstId);
2033 // Skip if 'dstNode' is not a loop nest.
River Riddle99b87c92019-03-27 21:02:022034 if (!dstNode->op->isa<AffineForOp>())
MLIR Teamd038e342019-03-01 19:50:252035 continue;
2036 // Attempt to fuse 'dstNode' with its sibling nodes in the graph.
2037 fuseWithSiblingNodes(dstNode);
2038 }
2039 }
2040
2041 // Attempt to fuse 'dstNode' with sibling nodes in the graph.
2042 void fuseWithSiblingNodes(Node *dstNode) {
2043 DenseSet<unsigned> visitedSibNodeIds;
2044 std::pair<unsigned, Value *> idAndMemref;
2045 while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) {
2046 unsigned sibId = idAndMemref.first;
2047 Value *memref = idAndMemref.second;
2048 // TODO(andydavis) Check that 'sibStoreOpInst' post-dominates all other
2049 // stores to the same memref in 'sibNode' loop nest.
2050 auto *sibNode = mdg->getNode(sibId);
River Riddle99b87c92019-03-27 21:02:022051 // Compute an operation list insertion point for the fused loop
MLIR Teamd038e342019-03-01 19:50:252052 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:022053 assert(sibNode->op->getBlock() == dstNode->op->getBlock());
2054 Operation *insertPointInst =
2055 sibNode->op->isBeforeInBlock(dstNode->op)
MLIR Teamd038e342019-03-01 19:50:252056 ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id)
2057 : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id);
2058 if (insertPointInst == nullptr)
2059 continue;
2060
2061 // Check if fusion would be profitable and at what depth.
2062
2063 // Get unique 'sibNode' load op to 'memref'.
River Riddle99b87c92019-03-27 21:02:022064 SmallVector<Operation *, 2> sibLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:252065 sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts);
2066 // Currently findSiblingNodeToFuse searches for siblings with one load.
2067 assert(sibLoadOpInsts.size() == 1);
River Riddle99b87c92019-03-27 21:02:022068 Operation *sibLoadOpInst = sibLoadOpInsts[0];
MLIR Teamd038e342019-03-01 19:50:252069 assert(!sibNode->stores.empty());
2070 // TODO(andydavis) Choose the store which postdominates all other stores.
2071 auto *sibStoreOpInst = sibNode->stores.back();
2072
2073 // Gather 'dstNode' load ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:022074 SmallVector<Operation *, 2> dstLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:252075 dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts);
2076
2077 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:022078 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd038e342019-03-01 19:50:252079 dstNode->getStoreOpsForMemref(memref, &dstStoreOpInsts);
2080
2081 unsigned bestDstLoopDepth;
2082 mlir::ComputationSliceState sliceState;
2083
2084 // Check if fusion would be profitable.
2085 if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstLoadOpInsts,
Uday Bondhugulace7e59532019-03-08 17:21:522086 dstStoreOpInsts, &sliceState, &bestDstLoopDepth,
2087 maximalFusion))
MLIR Teamd038e342019-03-01 19:50:252088 continue;
2089
2090 // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'.
2091 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
2092 sibLoadOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
2093 if (sliceLoopNest != nullptr) {
River Riddle99b87c92019-03-27 21:02:022094 auto dstForInst = dstNode->op->cast<AffineForOp>();
2095 // Update operation position of fused loop nest (if needed).
River Riddlef9d91532019-03-27 00:05:092096 if (insertPointInst != dstForInst.getOperation()) {
2097 dstForInst.getOperation()->moveBefore(insertPointInst);
MLIR Teamd038e342019-03-01 19:50:252098 }
2099 // Update data dependence graph state post fusion.
2100 updateStateAfterSiblingFusion(sliceLoopNest, sibNode, dstNode);
2101 }
2102 }
2103 }
2104
2105 // Searches the graph from 'dstNode' looking for a fusion candidate sibling
2106 // node which shares no dependences with 'dstNode' but which loads from the
2107 // same memref. Returns true and sets 'idAndMemrefToFuse' on success. Returns
2108 // false otherwise.
2109 bool findSiblingNodeToFuse(Node *dstNode,
2110 DenseSet<unsigned> *visitedSibNodeIds,
2111 std::pair<unsigned, Value *> *idAndMemrefToFuse) {
2112 // TODO(andydavis) Currently we discover siblings by following edges
2113 // through an intermediate src node. We should also consider siblings
2114 // which load from the same memref, but which do not necessarily share
2115 // a src node parent (e.g. loading from a memref which is a function arg).
2116 // Collect candidate 'dstNode' input edges in 'inEdges'.
2117 SmallVector<MemRefDependenceGraph::Edge, 2> inEdges;
2118 mdg->forEachMemRefInputEdge(
2119 dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) {
2120 // Add 'inEdge' if it is a read-after-write dependence.
2121 if (dstNode->getLoadOpCount(inEdge.value) > 0 &&
2122 mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0)
2123 inEdges.push_back(inEdge);
2124 });
2125
2126 // Search for sibling nodes to fuse by visiting output edges from each input
2127 // edge in 'inEdges'.
2128 for (auto &inEdge : inEdges) {
2129 // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'.
2130 SmallVector<MemRefDependenceGraph::Edge, 2> outEdges;
2131 mdg->forEachMemRefOutputEdge(
2132 inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) {
2133 unsigned sibNodeId = outEdge.id;
2134 if (visitedSibNodeIds->count(sibNodeId) > 0)
2135 return;
2136 // Skip output edge if not a sibling using the same memref.
2137 if (outEdge.id == dstNode->id || outEdge.value != inEdge.value)
2138 return;
2139 auto *sibNode = mdg->getNode(sibNodeId);
River Riddle99b87c92019-03-27 21:02:022140 if (!sibNode->op->isa<AffineForOp>())
MLIR Teamd038e342019-03-01 19:50:252141 return;
2142 // Skip if 'outEdge' is not a read-after-write dependence.
2143 // TODO(andydavis) Remove restrict to single load op restriction.
2144 if (sibNode->getLoadOpCount(inEdge.value) != 1)
2145 return;
2146 // Skip if there exists a path of dependent edges between
2147 // 'sibNode' and 'dstNode'.
2148 if (mdg->hasDependencePath(sibNodeId, dstNode->id) ||
2149 mdg->hasDependencePath(dstNode->id, sibNodeId))
2150 return;
2151 // Skip sib node if it loads to (and stores from) the same memref on
2152 // which it also has an input dependence edge.
2153 DenseSet<Value *> loadAndStoreMemrefSet;
2154 sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet);
2155 if (llvm::any_of(loadAndStoreMemrefSet, [=](Value *memref) {
2156 return mdg->getIncomingMemRefAccesses(sibNode->id, memref) >
2157 0;
2158 }))
2159 return;
2160 // Check that all stores are to the same memref.
2161 DenseSet<Value *> storeMemrefs;
2162 for (auto *storeOpInst : sibNode->stores) {
River Riddle96ebde92019-03-25 20:02:062163 storeMemrefs.insert(storeOpInst->cast<StoreOp>().getMemRef());
MLIR Teamd038e342019-03-01 19:50:252164 }
2165 if (storeMemrefs.size() != 1)
2166 return;
2167 // Add candidate 'outEdge' to sibling node.
2168 outEdges.push_back(outEdge);
2169 });
2170
2171 // Add first candidate if any were returned.
2172 if (!outEdges.empty()) {
2173 visitedSibNodeIds->insert(outEdges[0].id);
2174 idAndMemrefToFuse->first = outEdges[0].id;
2175 idAndMemrefToFuse->second = outEdges[0].value;
2176 return true;
2177 }
2178 }
2179 return false;
2180 }
2181
Chris Lattnerd9b5bc82019-03-25 02:53:052182 void updateStateAfterSiblingFusion(AffineForOp sliceLoopNest, Node *sibNode,
2183 Node *dstNode) {
MLIR Teamd038e342019-03-01 19:50:252184 // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion.
2185 mdg->updateEdges(sibNode->id, dstNode->id);
2186
2187 // Collect slice loop stats.
2188 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:092189 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamd038e342019-03-01 19:50:252190 // Promote single iteration slice loops to single IV value.
2191 for (auto forOp : sliceCollector.forOps) {
2192 promoteIfSingleIteration(forOp);
2193 }
2194
2195 // Collect dst loop stats after memref privatizaton transformation.
River Riddle99b87c92019-03-27 21:02:022196 auto dstForInst = dstNode->op->cast<AffineForOp>();
MLIR Teamd038e342019-03-01 19:50:252197 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:092198 dstLoopCollector.collect(dstForInst.getOperation());
MLIR Teamd038e342019-03-01 19:50:252199 // Clear and add back loads and stores
2200 mdg->clearNodeLoadAndStores(dstNode->id);
2201 mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts,
2202 dstLoopCollector.storeOpInsts);
2203 // Remove old sibling loop nest if it no longer has outgoing dependence
2204 // edges, and it does not write to a memref which escapes the
2205 // function.
2206 if (mdg->getOutEdgeCount(sibNode->id) == 0) {
2207 mdg->removeNode(sibNode->id);
River Riddle99b87c92019-03-27 21:02:022208 sibNode->op->cast<AffineForOp>().erase();
MLIR Teamd038e342019-03-01 19:50:252209 }
2210 }
2211
2212 // Clean up any allocs with no users.
2213 void eraseUnusedMemRefAllocations() {
MLIR Teamc4237ae2019-01-18 16:56:272214 for (auto &pair : mdg->memrefEdgeCount) {
2215 if (pair.second > 0)
2216 continue;
2217 auto *memref = pair.first;
River Riddle99b87c92019-03-27 21:02:022218 // Skip if there exist other uses (return operation or function calls).
MLIR Team71495d52019-01-22 21:23:372219 if (!memref->use_empty())
2220 continue;
MLIR Teamc4237ae2019-01-18 16:56:272221 // Use list expected to match the dep graph info.
River Riddle99b87c92019-03-27 21:02:022222 auto *op = memref->getDefiningOp();
2223 if (op && op->isa<AllocOp>())
2224 op->erase();
MLIR Teamc4237ae2019-01-18 16:56:272225 }
MLIR Teamf28e4df2018-11-01 14:26:002226 }
MLIR Team3b692302018-12-17 17:57:142227};
2228
2229} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:002230
River Riddleed5fe202019-02-28 22:50:422231void LoopFusion::runOnFunction() {
Uday Bondhugulad4b3ff12019-02-27 00:10:192232 // Override if a command line argument was provided.
Uday Bondhugula8be26272019-02-02 01:06:222233 if (clFusionFastMemorySpace.getNumOccurrences() > 0) {
2234 fastMemorySpace = clFusionFastMemorySpace.getValue();
2235 }
2236
Uday Bondhugulad4b3ff12019-02-27 00:10:192237 // Override if a command line argument was provided.
2238 if (clFusionLocalBufThreshold.getNumOccurrences() > 0) {
2239 localBufSizeThreshold = clFusionLocalBufThreshold * 1024;
2240 }
2241
Uday Bondhugulace7e59532019-03-08 17:21:522242 if (clMaximalLoopFusion.getNumOccurrences() > 0)
2243 maximalFusion = clMaximalLoopFusion;
2244
MLIR Team6892ffb2018-12-20 04:42:552245 MemRefDependenceGraph g;
Uday Bondhugula02af8c22019-03-05 23:05:342246 if (g.init(getFunction()))
Uday Bondhugulace7e59532019-03-08 17:21:522247 GreedyFusion(&g, localBufSizeThreshold, fastMemorySpace, maximalFusion)
2248 .run();
MLIR Teamf28e4df2018-11-01 14:26:002249}
Jacques Pienaar6f0fb222018-11-07 02:34:182250
2251static PassRegistration<LoopFusion> pass("loop-fusion", "Fuse loop nests");