blob: 0f4e45c372ae03bfa57621bb92f672363d422337 [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"
MLIR Teamf28e4df2018-11-01 14:26:0029#include "mlir/IR/Builders.h"
30#include "mlir/IR/BuiltinOps.h"
River Riddle48ccae22019-02-20 01:17:4631#include "mlir/Pass/Pass.h"
MLIR Teamf28e4df2018-11-01 14:26:0032#include "mlir/StandardOps/StandardOps.h"
33#include "mlir/Transforms/LoopUtils.h"
34#include "mlir/Transforms/Passes.h"
MLIR Teamc4237ae2019-01-18 16:56:2735#include "mlir/Transforms/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0036#include "llvm/ADT/DenseMap.h"
MLIR Team3b692302018-12-17 17:57:1437#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/SetVector.h"
MLIR Team4eef7952018-12-21 19:06:2339#include "llvm/Support/CommandLine.h"
MLIR Team38c2fe32019-01-14 19:26:2540#include "llvm/Support/Debug.h"
MLIR Team3b692302018-12-17 17:57:1441#include "llvm/Support/raw_ostream.h"
Uday Bondhugula864d9e02019-01-23 17:16:2442#include <iomanip>
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 Bondhugula864d9e02019-01-23 17:16:2452/// Disables fusion profitability check and fuses if valid.
MLIR Teamc4237ae2019-01-18 16:56:2753static llvm::cl::opt<bool>
54 clMaximalLoopFusion("fusion-maximal", llvm::cl::Hidden,
River Riddle75c21e12019-01-26 06:14:0455 llvm::cl::desc("Enables maximal loop fusion"),
56 llvm::cl::cat(clOptionsCategory));
Uday Bondhugula864d9e02019-01-23 17:16:2457
58/// A threshold in percent of additional computation allowed when fusing.
59static llvm::cl::opt<double> clFusionAddlComputeTolerance(
60 "fusion-compute-tolerance", llvm::cl::Hidden,
Uday Bondhugulaa1dad3a2019-02-20 02:17:1961 llvm::cl::desc("Fractional increase in additional "
62 "computation tolerated while fusing"),
River Riddle75c21e12019-01-26 06:14:0463 llvm::cl::cat(clOptionsCategory));
MLIR Teamc4237ae2019-01-18 16:56:2764
Uday Bondhugula8be26272019-02-02 01:06:2265static llvm::cl::opt<unsigned> clFusionFastMemorySpace(
66 "fusion-fast-mem-space", llvm::cl::Hidden,
67 llvm::cl::desc("Faster memory space number to promote fusion buffers to"),
68 llvm::cl::cat(clOptionsCategory));
69
Uday Bondhugulad4b3ff12019-02-27 00:10:1970// A local buffer of size less than or equal to this size is promoted to fast
71// memory.
72static llvm::cl::opt<unsigned long long> clFusionLocalBufThreshold(
Uday Bondhugula8be26272019-02-02 01:06:2273 "fusion-local-buf-threshold", llvm::cl::Hidden,
Uday Bondhugulad4b3ff12019-02-27 00:10:1974 llvm::cl::desc("Threshold size (KiB) for promoting local buffers to fast "
Uday Bondhugula8be26272019-02-02 01:06:2275 "memory space"),
76 llvm::cl::cat(clOptionsCategory));
77
MLIR Teamf28e4df2018-11-01 14:26:0078namespace {
79
MLIR Team3b692302018-12-17 17:57:1480/// Loop fusion pass. This pass currently supports a greedy fusion policy,
81/// which fuses loop nests with single-writer/single-reader memref dependences
82/// with the goal of improving locality.
83
84// TODO(andydavis) Support fusion of source loop nests which write to multiple
85// memrefs, where each memref can have multiple users (if profitable).
MLIR Teamf28e4df2018-11-01 14:26:0086// TODO(andydavis) Extend this pass to check for fusion preventing dependences,
87// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1488
MLIR Teamf28e4df2018-11-01 14:26:0089struct LoopFusion : public FunctionPass {
Uday Bondhugulad4b3ff12019-02-27 00:10:1990 LoopFusion(unsigned fastMemorySpace = 0, uint64_t localBufSizeThreshold = 0)
91 : FunctionPass(&LoopFusion::passID),
92 localBufSizeThreshold(localBufSizeThreshold),
93 fastMemorySpace(fastMemorySpace) {}
MLIR Teamf28e4df2018-11-01 14:26:0094
Chris Lattner79748892018-12-31 07:10:3595 PassResult runOnFunction(Function *f) override;
River Riddle3e656592019-02-22 02:01:0996 constexpr static PassID passID = {};
Uday Bondhugula864d9e02019-01-23 17:16:2497
Uday Bondhugulad4b3ff12019-02-27 00:10:1998 // Any local buffers smaller than this size (in bytes) will be created in
Uday Bondhugula8be26272019-02-02 01:06:2299 // `fastMemorySpace` if provided.
Uday Bondhugulad4b3ff12019-02-27 00:10:19100 uint64_t localBufSizeThreshold;
Uday Bondhugula8be26272019-02-02 01:06:22101 Optional<unsigned> fastMemorySpace = None;
102
Uday Bondhugula864d9e02019-01-23 17:16:24103 // The amount of additional computation that is tolerated while fusing
104 // pair-wise as a fraction of the total computation.
105 constexpr static double kComputeToleranceThreshold = 0.30f;
MLIR Teamf28e4df2018-11-01 14:26:00106};
107
MLIR Teamf28e4df2018-11-01 14:26:00108} // end anonymous namespace
109
Uday Bondhugulad4b3ff12019-02-27 00:10:19110FunctionPass *mlir::createLoopFusionPass(unsigned fastMemorySpace,
111 uint64_t localBufSizeThreshold) {
112 return new LoopFusion(fastMemorySpace, localBufSizeThreshold);
113}
MLIR Teamf28e4df2018-11-01 14:26:00114
MLIR Team3b692302018-12-17 17:57:14115namespace {
MLIR Teamf28e4df2018-11-01 14:26:00116
MLIR Team3b692302018-12-17 17:57:14117// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:35118// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:44119struct LoopNestStateCollector {
River Riddle5052bd82019-02-02 00:42:18120 SmallVector<OpPointer<AffineForOp>, 4> forOps;
River Riddleb4992772019-02-04 18:38:47121 SmallVector<Instruction *, 4> loadOpInsts;
122 SmallVector<Instruction *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:53123 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:14124
River Riddlebf9c3812019-02-05 00:24:44125 void collect(Instruction *instToWalk) {
126 instToWalk->walk([&](Instruction *opInst) {
127 if (opInst->isa<AffineForOp>())
128 forOps.push_back(opInst->cast<AffineForOp>());
129 else if (opInst->getNumBlockLists() != 0)
130 hasNonForRegion = true;
131 else if (opInst->isa<LoadOp>())
132 loadOpInsts.push_back(opInst);
133 else if (opInst->isa<StoreOp>())
134 storeOpInsts.push_back(opInst);
135 });
MLIR Team3b692302018-12-17 17:57:14136 }
137};
138
MLIR Team71495d52019-01-22 21:23:37139// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
River Riddleb4992772019-02-04 18:38:47140static bool isMemRefDereferencingOp(const Instruction &op) {
MLIR Team71495d52019-01-22 21:23:37141 if (op.isa<LoadOp>() || op.isa<StoreOp>() || op.isa<DmaStartOp>() ||
142 op.isa<DmaWaitOp>())
143 return true;
144 return false;
145}
MLIR Team6892ffb2018-12-20 04:42:55146// MemRefDependenceGraph is a graph data structure where graph nodes are
Chris Lattner456ad6a2018-12-29 00:05:35147// top-level instructions in a Function which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55148// are memref dependences between the nodes.
MLIR Teamc4237ae2019-01-18 16:56:27149// TODO(andydavis) Add a more flexible dependece graph representation.
MLIR Team6892ffb2018-12-20 04:42:55150// TODO(andydavis) Add a depth parameter to dependence graph construction.
151struct MemRefDependenceGraph {
152public:
153 // Node represents a node in the graph. A Node is either an entire loop nest
154 // rooted at the top level which contains loads/stores, or a top level
155 // load/store.
156 struct Node {
157 // The unique identifier of this node in the graph.
158 unsigned id;
159 // The top-level statment which is (or contains) loads/stores.
Chris Lattner456ad6a2018-12-29 00:05:35160 Instruction *inst;
Chris Lattner5187cfc2018-12-28 05:21:41161 // List of load operations.
River Riddleb4992772019-02-04 18:38:47162 SmallVector<Instruction *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35163 // List of store op insts.
River Riddleb4992772019-02-04 18:38:47164 SmallVector<Instruction *, 4> stores;
Chris Lattner456ad6a2018-12-29 00:05:35165 Node(unsigned id, Instruction *inst) : id(id), inst(inst) {}
MLIR Team6892ffb2018-12-20 04:42:55166
167 // Returns the load op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10168 unsigned getLoadOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55169 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35170 for (auto *loadOpInst : loads) {
171 if (memref == loadOpInst->cast<LoadOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55172 ++loadOpCount;
173 }
174 return loadOpCount;
175 }
176
177 // Returns the store op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10178 unsigned getStoreOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55179 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35180 for (auto *storeOpInst : stores) {
181 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55182 ++storeOpCount;
183 }
184 return storeOpCount;
185 }
MLIR Team58aa3832019-02-16 01:12:19186
187 // Returns all store ups in 'storeOps' which access 'memref'.
188 void getStoreOpsForMemref(Value *memref,
189 SmallVectorImpl<Instruction *> *storeOps) {
190 for (auto *storeOpInst : stores) {
191 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
192 storeOps->push_back(storeOpInst);
193 }
194 }
MLIR Team6892ffb2018-12-20 04:42:55195 };
196
MLIR Teama0f3db402019-01-29 17:36:41197 // Edge represents a data dependece between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55198 struct Edge {
199 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46200 // If this edge is stored in Edge = Node.inEdges[i], then
201 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
202 // If this edge is stored in Edge = Node.outEdges[i], then
203 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55204 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41205 // The SSA value on which this edge represents a dependence.
206 // If the value is a memref, then the dependence is between graph nodes
207 // which contain accesses to the same memref 'value'. If the value is a
208 // non-memref value, then the dependence is between a graph node which
209 // defines an SSA value and another graph node which uses the SSA value
210 // (e.g. a constant instruction defining a value which is used inside a loop
211 // nest).
212 Value *value;
MLIR Team6892ffb2018-12-20 04:42:55213 };
214
215 // Map from node id to Node.
216 DenseMap<unsigned, Node> nodes;
217 // Map from node id to list of input edges.
218 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
219 // Map from node id to list of output edges.
220 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27221 // Map from memref to a count on the dependence edges associated with that
222 // memref.
223 DenseMap<Value *, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41224 // The next unique identifier to use for newly created graph nodes.
225 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55226
227 MemRefDependenceGraph() {}
228
229 // Initializes the dependence graph based on operations in 'f'.
230 // Returns true on success, false otherwise.
Chris Lattner69d9e992018-12-28 16:48:09231 bool init(Function *f);
MLIR Team6892ffb2018-12-20 04:42:55232
233 // Returns the graph node for 'id'.
234 Node *getNode(unsigned id) {
235 auto it = nodes.find(id);
236 assert(it != nodes.end());
237 return &it->second;
238 }
239
MLIR Teama0f3db402019-01-29 17:36:41240 // Adds a node with 'inst' to the graph and returns its unique identifier.
241 unsigned addNode(Instruction *inst) {
242 Node node(nextNodeId++, inst);
243 nodes.insert({node.id, node});
244 return node.id;
245 }
246
MLIR Teamc4237ae2019-01-18 16:56:27247 // Remove node 'id' (and its associated edges) from graph.
248 void removeNode(unsigned id) {
249 // Remove each edge in 'inEdges[id]'.
250 if (inEdges.count(id) > 0) {
251 SmallVector<Edge, 2> oldInEdges = inEdges[id];
252 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41253 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27254 }
255 }
256 // Remove each edge in 'outEdges[id]'.
257 if (outEdges.count(id) > 0) {
258 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
259 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41260 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27261 }
262 }
263 // Erase remaining node state.
264 inEdges.erase(id);
265 outEdges.erase(id);
266 nodes.erase(id);
267 }
268
MLIR Teamd7c82442019-01-30 23:53:41269 // Returns true if node 'id' writes to any memref which escapes (or is an
270 // argument to) the function/block. Returns false otherwise.
271 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37272 Node *node = getNode(id);
273 for (auto *storeOpInst : node->stores) {
274 auto *memref = storeOpInst->cast<StoreOp>()->getMemRef();
275 auto *inst = memref->getDefiningInst();
MLIR Team58aa3832019-02-16 01:12:19276 // Return true if 'memref' is a block argument.
River Riddleb4992772019-02-04 18:38:47277 if (!inst)
MLIR Teamd7c82442019-01-30 23:53:41278 return true;
MLIR Team58aa3832019-02-16 01:12:19279 // Return true if any use of 'memref' escapes the function.
River Riddleb4992772019-02-04 18:38:47280 for (auto &use : memref->getUses())
281 if (!isMemRefDereferencingOp(*use.getOwner()))
MLIR Teamd7c82442019-01-30 23:53:41282 return true;
MLIR Teamd7c82442019-01-30 23:53:41283 }
284 return false;
285 }
286
287 // Returns true if node 'id' can be removed from the graph. Returns false
288 // otherwise. A node can be removed from the graph iff the following
289 // conditions are met:
290 // *) The node does not write to any memref which escapes (or is a
291 // function/block argument).
292 // *) The node has no successors in the dependence graph.
293 bool canRemoveNode(unsigned id) {
294 if (writesToLiveInOrEscapingMemrefs(id))
295 return false;
296 Node *node = getNode(id);
297 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41298 // Return false if there exist out edges from 'id' on 'memref'.
MLIR Teamd7c82442019-01-30 23:53:41299 if (getOutEdgeCount(id, storeOpInst->cast<StoreOp>()->getMemRef()) > 0)
MLIR Teama0f3db402019-01-29 17:36:41300 return false;
MLIR Team71495d52019-01-22 21:23:37301 }
MLIR Teama0f3db402019-01-29 17:36:41302 return true;
MLIR Team71495d52019-01-22 21:23:37303 }
304
MLIR Team27d067e2019-01-16 17:55:02305 // Returns true iff there is an edge from node 'srcId' to node 'dstId' for
MLIR Teama0f3db402019-01-29 17:36:41306 // 'value'. Returns false otherwise.
307 bool hasEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team27d067e2019-01-16 17:55:02308 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
309 return false;
310 }
311 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41312 return edge.id == dstId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02313 });
314 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41315 return edge.id == srcId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02316 });
317 return hasOutEdge && hasInEdge;
318 }
319
MLIR Teama0f3db402019-01-29 17:36:41320 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
321 void addEdge(unsigned srcId, unsigned dstId, Value *value) {
322 if (!hasEdge(srcId, dstId, value)) {
323 outEdges[srcId].push_back({dstId, value});
324 inEdges[dstId].push_back({srcId, value});
325 if (value->getType().isa<MemRefType>())
326 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02327 }
MLIR Team6892ffb2018-12-20 04:42:55328 }
329
MLIR Teama0f3db402019-01-29 17:36:41330 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
331 void removeEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team6892ffb2018-12-20 04:42:55332 assert(inEdges.count(dstId) > 0);
333 assert(outEdges.count(srcId) > 0);
MLIR Teama0f3db402019-01-29 17:36:41334 if (value->getType().isa<MemRefType>()) {
335 assert(memrefEdgeCount.count(value) > 0);
336 memrefEdgeCount[value]--;
337 }
MLIR Team6892ffb2018-12-20 04:42:55338 // Remove 'srcId' from 'inEdges[dstId]'.
339 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41340 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55341 inEdges[dstId].erase(it);
342 break;
343 }
344 }
345 // Remove 'dstId' from 'outEdges[srcId]'.
346 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41347 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55348 outEdges[srcId].erase(it);
349 break;
350 }
351 }
352 }
353
MLIR Teama0f3db402019-01-29 17:36:41354 // Returns the input edge count for node 'id' and 'memref' from src nodes
355 // which access 'memref'.
356 unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55357 unsigned inEdgeCount = 0;
358 if (inEdges.count(id) > 0)
359 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41360 if (inEdge.value == memref) {
361 Node *srcNode = getNode(inEdge.id);
362 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
363 if (srcNode->getLoadOpCount(memref) > 0 ||
364 srcNode->getStoreOpCount(memref) > 0)
365 ++inEdgeCount;
366 }
MLIR Team6892ffb2018-12-20 04:42:55367 return inEdgeCount;
368 }
369
370 // Returns the output edge count for node 'id' and 'memref'.
Chris Lattner3f190312018-12-27 22:35:10371 unsigned getOutEdgeCount(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55372 unsigned outEdgeCount = 0;
373 if (outEdges.count(id) > 0)
374 for (auto &outEdge : outEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41375 if (outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55376 ++outEdgeCount;
377 return outEdgeCount;
378 }
379
MLIR Teama0f3db402019-01-29 17:36:41380 // Computes and returns an insertion point instruction, before which the
381 // the fused <srcId, dstId> loop nest can be inserted while preserving
382 // dependences. Returns nullptr if no such insertion point is found.
MLIR Teama78edcd2019-02-05 14:57:08383 Instruction *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40384 if (outEdges.count(srcId) == 0)
MLIR Teama0f3db402019-01-29 17:36:41385 return getNode(dstId)->inst;
386
387 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
388 SmallPtrSet<Instruction *, 2> srcDepInsts;
389 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08390 if (outEdge.id != dstId)
MLIR Teama0f3db402019-01-29 17:36:41391 srcDepInsts.insert(getNode(outEdge.id)->inst);
392
393 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
394 SmallPtrSet<Instruction *, 2> dstDepInsts;
395 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08396 if (inEdge.id != srcId)
MLIR Teama0f3db402019-01-29 17:36:41397 dstDepInsts.insert(getNode(inEdge.id)->inst);
398
399 Instruction *srcNodeInst = getNode(srcId)->inst;
400 Instruction *dstNodeInst = getNode(dstId)->inst;
401
402 // Computing insertion point:
403 // *) Walk all instruction positions in Block instruction list in the
404 // range (src, dst). For each instruction 'inst' visited in this search:
405 // *) Store in 'firstSrcDepPos' the first position where 'inst' has a
406 // dependence edge from 'srcNode'.
407 // *) Store in 'lastDstDepPost' the last position where 'inst' has a
408 // dependence edge to 'dstNode'.
409 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
410 // instruction insertion point (or return null pointer if no such
411 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
412 SmallVector<Instruction *, 2> depInsts;
413 Optional<unsigned> firstSrcDepPos;
414 Optional<unsigned> lastDstDepPos;
415 unsigned pos = 0;
416 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
417 it != Block::iterator(dstNodeInst); ++it) {
418 Instruction *inst = &(*it);
419 if (srcDepInsts.count(inst) > 0 && firstSrcDepPos == None)
420 firstSrcDepPos = pos;
421 if (dstDepInsts.count(inst) > 0)
422 lastDstDepPos = pos;
423 depInsts.push_back(inst);
424 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40425 }
MLIR Teama0f3db402019-01-29 17:36:41426
427 if (firstSrcDepPos.hasValue()) {
428 if (lastDstDepPos.hasValue()) {
429 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
430 // No valid insertion point exists which preserves dependences.
431 return nullptr;
432 }
433 }
434 // Return the insertion point at 'firstSrcDepPos'.
435 return depInsts[firstSrcDepPos.getValue()];
436 }
437 // No dependence targets in range (or only dst deps in range), return
438 // 'dstNodInst' insertion point.
439 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55440 }
441
MLIR Teama0f3db402019-01-29 17:36:41442 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
443 // has been replaced in node at 'dstId' by a private memref.
444 void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef) {
MLIR Team6892ffb2018-12-20 04:42:55445 // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'.
446 if (inEdges.count(srcId) > 0) {
447 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
448 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41449 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
450 if (inEdge.value != oldMemRef)
451 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55452 }
453 }
MLIR Teamc4237ae2019-01-18 16:56:27454 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55455 if (outEdges.count(srcId) > 0) {
456 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
457 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27458 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
459 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41460 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55461 }
462 }
MLIR Teama0f3db402019-01-29 17:36:41463 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
464 // replaced by a private memref). These edges could come from nodes
465 // other than 'srcId' which were removed in the previous step.
466 if (inEdges.count(dstId) > 0) {
467 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
468 for (auto &inEdge : oldInEdges)
469 if (inEdge.value == oldMemRef)
470 removeEdge(inEdge.id, dstId, inEdge.value);
471 }
MLIR Team6892ffb2018-12-20 04:42:55472 }
473
474 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddleb4992772019-02-04 18:38:47475 void addToNode(unsigned id, const SmallVectorImpl<Instruction *> &loads,
476 const SmallVectorImpl<Instruction *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55477 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35478 for (auto *loadOpInst : loads)
479 node->loads.push_back(loadOpInst);
480 for (auto *storeOpInst : stores)
481 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55482 }
483
MLIR Teamc4237ae2019-01-18 16:56:27484 void clearNodeLoadAndStores(unsigned id) {
485 Node *node = getNode(id);
486 node->loads.clear();
487 node->stores.clear();
488 }
489
MLIR Team6892ffb2018-12-20 04:42:55490 void print(raw_ostream &os) const {
491 os << "\nMemRefDependenceGraph\n";
492 os << "\nNodes:\n";
493 for (auto &idAndNode : nodes) {
494 os << "Node: " << idAndNode.first << "\n";
495 auto it = inEdges.find(idAndNode.first);
496 if (it != inEdges.end()) {
497 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41498 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55499 }
500 it = outEdges.find(idAndNode.first);
501 if (it != outEdges.end()) {
502 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41503 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55504 }
505 }
506 }
507 void dump() const { print(llvm::errs()); }
508};
509
Chris Lattner456ad6a2018-12-29 00:05:35510// Intializes the data dependence graph by walking instructions in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55511// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39512// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55513// dependence graph at a different depth.
Chris Lattner69d9e992018-12-28 16:48:09514bool MemRefDependenceGraph::init(Function *f) {
Chris Lattner3f190312018-12-27 22:35:10515 DenseMap<Value *, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43516
517 // TODO: support multi-block functions.
518 if (f->getBlocks().size() != 1)
519 return false;
520
River Riddle5052bd82019-02-02 00:42:18521 DenseMap<Instruction *, unsigned> forToNodeMap;
Chris Lattnerdffc5892018-12-29 23:33:43522 for (auto &inst : f->front()) {
River Riddleb4992772019-02-04 18:38:47523 if (auto forOp = inst.dyn_cast<AffineForOp>()) {
River Riddle5052bd82019-02-02 00:42:18524 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55525 // all loads and store accesses it contains.
526 LoopNestStateCollector collector;
River Riddlebf9c3812019-02-05 00:24:44527 collector.collect(&inst);
Uday Bondhugula4ba8c912019-02-07 05:54:18528 // Return false if a non 'for' region was found (not currently supported).
River Riddle75553832019-01-29 05:23:53529 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55530 return false;
MLIR Teama0f3db402019-01-29 17:36:41531 Node node(nextNodeId++, &inst);
Chris Lattner456ad6a2018-12-29 00:05:35532 for (auto *opInst : collector.loadOpInsts) {
533 node.loads.push_back(opInst);
534 auto *memref = opInst->cast<LoadOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55535 memrefAccesses[memref].insert(node.id);
536 }
Chris Lattner456ad6a2018-12-29 00:05:35537 for (auto *opInst : collector.storeOpInsts) {
538 node.stores.push_back(opInst);
539 auto *memref = opInst->cast<StoreOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55540 memrefAccesses[memref].insert(node.id);
541 }
River Riddle5052bd82019-02-02 00:42:18542 forToNodeMap[&inst] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55543 nodes.insert({node.id, node});
River Riddleb4992772019-02-04 18:38:47544 } else if (auto loadOp = inst.dyn_cast<LoadOp>()) {
545 // Create graph node for top-level load op.
546 Node node(nextNodeId++, &inst);
547 node.loads.push_back(&inst);
548 auto *memref = inst.cast<LoadOp>()->getMemRef();
549 memrefAccesses[memref].insert(node.id);
550 nodes.insert({node.id, node});
551 } else if (auto storeOp = inst.dyn_cast<StoreOp>()) {
552 // Create graph node for top-level store op.
553 Node node(nextNodeId++, &inst);
554 node.stores.push_back(&inst);
555 auto *memref = inst.cast<StoreOp>()->getMemRef();
556 memrefAccesses[memref].insert(node.id);
557 nodes.insert({node.id, node});
558 } else if (inst.getNumBlockLists() != 0) {
559 // Return false if another region is found (not currently supported).
560 return false;
561 } else if (inst.getNumResults() > 0 && !inst.use_empty()) {
562 // Create graph node for top-level producer of SSA values, which
563 // could be used by loop nest nodes.
564 Node node(nextNodeId++, &inst);
565 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41566 }
567 }
568
569 // Add dependence edges between nodes which produce SSA values and their
570 // users.
571 for (auto &idAndNode : nodes) {
572 const Node &node = idAndNode.second;
573 if (!node.loads.empty() || !node.stores.empty())
574 continue;
River Riddleb4992772019-02-04 18:38:47575 auto *opInst = node.inst;
MLIR Teama0f3db402019-01-29 17:36:41576 for (auto *value : opInst->getResults()) {
577 for (auto &use : value->getUses()) {
River Riddle5052bd82019-02-02 00:42:18578 SmallVector<OpPointer<AffineForOp>, 4> loops;
River Riddleb4992772019-02-04 18:38:47579 getLoopIVs(*use.getOwner(), &loops);
MLIR Teama0f3db402019-01-29 17:36:41580 if (loops.empty())
581 continue;
River Riddle5052bd82019-02-02 00:42:18582 assert(forToNodeMap.count(loops[0]->getInstruction()) > 0);
583 unsigned userLoopNestId = forToNodeMap[loops[0]->getInstruction()];
MLIR Teama0f3db402019-01-29 17:36:41584 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55585 }
586 }
MLIR Team6892ffb2018-12-20 04:42:55587 }
588
589 // Walk memref access lists and add graph edges between dependent nodes.
590 for (auto &memrefAndList : memrefAccesses) {
591 unsigned n = memrefAndList.second.size();
592 for (unsigned i = 0; i < n; ++i) {
593 unsigned srcId = memrefAndList.second[i];
594 bool srcHasStore =
595 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
596 for (unsigned j = i + 1; j < n; ++j) {
597 unsigned dstId = memrefAndList.second[j];
598 bool dstHasStore =
599 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
600 if (srcHasStore || dstHasStore)
601 addEdge(srcId, dstId, memrefAndList.first);
602 }
603 }
604 }
605 return true;
606}
607
MLIR Team38c2fe32019-01-14 19:26:25608namespace {
609
610// LoopNestStats aggregates various per-loop statistics (eg. loop trip count
611// and operation count) for a loop nest up until the innermost loop body.
612struct LoopNestStats {
River Riddle5052bd82019-02-02 00:42:18613 // Map from AffineForOp to immediate child AffineForOps in its loop body.
614 DenseMap<Instruction *, SmallVector<OpPointer<AffineForOp>, 2>> loopMap;
615 // Map from AffineForOp to count of operations in its loop body.
616 DenseMap<Instruction *, uint64_t> opCountMap;
617 // Map from AffineForOp to its constant trip count.
618 DenseMap<Instruction *, uint64_t> tripCountMap;
MLIR Team38c2fe32019-01-14 19:26:25619};
620
621// LoopNestStatsCollector walks a single loop nest and gathers per-loop
622// trip count and operation count statistics and records them in 'stats'.
River Riddlebf9c3812019-02-05 00:24:44623struct LoopNestStatsCollector {
MLIR Team38c2fe32019-01-14 19:26:25624 LoopNestStats *stats;
625 bool hasLoopWithNonConstTripCount = false;
626
627 LoopNestStatsCollector(LoopNestStats *stats) : stats(stats) {}
628
River Riddlebf9c3812019-02-05 00:24:44629 void collect(Instruction *inst) {
630 inst->walk<AffineForOp>([&](OpPointer<AffineForOp> forOp) {
631 auto *forInst = forOp->getInstruction();
632 auto *parentInst = forOp->getInstruction()->getParentInst();
633 if (parentInst != nullptr) {
634 assert(parentInst->isa<AffineForOp>() && "Expected parent AffineForOp");
635 // Add mapping to 'forOp' from its parent AffineForOp.
636 stats->loopMap[parentInst].push_back(forOp);
637 }
River Riddle5052bd82019-02-02 00:42:18638
River Riddlebf9c3812019-02-05 00:24:44639 // Record the number of op instructions in the body of 'forOp'.
640 unsigned count = 0;
641 stats->opCountMap[forInst] = 0;
642 for (auto &inst : *forOp->getBody()) {
Uday Bondhugulad4b3ff12019-02-27 00:10:19643 if (!inst.isa<AffineForOp>() && !inst.isa<AffineIfOp>())
River Riddlebf9c3812019-02-05 00:24:44644 ++count;
645 }
646 stats->opCountMap[forInst] = count;
647 // Record trip count for 'forOp'. Set flag if trip count is not
648 // constant.
649 Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp);
650 if (!maybeConstTripCount.hasValue()) {
651 hasLoopWithNonConstTripCount = true;
652 return;
653 }
654 stats->tripCountMap[forInst] = maybeConstTripCount.getValue();
655 });
MLIR Team38c2fe32019-01-14 19:26:25656 }
657};
658
River Riddle5052bd82019-02-02 00:42:18659// Computes the total cost of the loop nest rooted at 'forOp'.
MLIR Team38c2fe32019-01-14 19:26:25660// Currently, the total cost is computed by counting the total operation
661// instance count (i.e. total number of operations in the loop bodyloop
662// operation count * loop trip count) for the entire loop nest.
663// If 'tripCountOverrideMap' is non-null, overrides the trip count for loops
664// specified in the map when computing the total op instance count.
665// NOTE: this is used to compute the cost of computation slices, which are
666// sliced along the iteration dimension, and thus reduce the trip count.
River Riddle5052bd82019-02-02 00:42:18667// If 'computeCostMap' is non-null, the total op count for forOps specified
MLIR Team38c2fe32019-01-14 19:26:25668// in the map is increased (not overridden) by adding the op count from the
669// map to the existing op count for the for loop. This is done before
670// multiplying by the loop's trip count, and is used to model the cost of
671// inserting a sliced loop nest of known cost into the loop's body.
672// NOTE: this is used to compute the cost of fusing a slice of some loop nest
673// within another loop.
Uday Bondhugula864d9e02019-01-23 17:16:24674static int64_t getComputeCost(
River Riddle5052bd82019-02-02 00:42:18675 Instruction *forInst, LoopNestStats *stats,
676 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountOverrideMap,
677 DenseMap<Instruction *, int64_t> *computeCostMap) {
678 // 'opCount' is the total number operations in one iteration of 'forOp' body
Uday Bondhugula864d9e02019-01-23 17:16:24679 int64_t opCount = stats->opCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25680 if (stats->loopMap.count(forInst) > 0) {
River Riddle5052bd82019-02-02 00:42:18681 for (auto childForOp : stats->loopMap[forInst]) {
682 opCount += getComputeCost(childForOp->getInstruction(), stats,
683 tripCountOverrideMap, computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:25684 }
685 }
686 // Add in additional op instances from slice (if specified in map).
687 if (computeCostMap != nullptr) {
688 auto it = computeCostMap->find(forInst);
689 if (it != computeCostMap->end()) {
690 opCount += it->second;
691 }
692 }
693 // Override trip count (if specified in map).
Uday Bondhugula864d9e02019-01-23 17:16:24694 int64_t tripCount = stats->tripCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25695 if (tripCountOverrideMap != nullptr) {
696 auto it = tripCountOverrideMap->find(forInst);
697 if (it != tripCountOverrideMap->end()) {
698 tripCount = it->second;
699 }
700 }
701 // Returns the total number of dynamic instances of operations in loop body.
702 return tripCount * opCount;
703}
704
705} // end anonymous namespace
706
Uday Bondhugula7aa60a32019-02-27 01:32:47707// TODO(andydavis,b/126426796): extend this to handle multiple result maps.
MLIR Team27d067e2019-01-16 17:55:02708static Optional<uint64_t> getConstDifference(AffineMap lbMap, AffineMap ubMap) {
Uday Bondhugulac1ca23e2019-01-16 21:13:00709 assert(lbMap.getNumResults() == 1 && "expected single result bound map");
710 assert(ubMap.getNumResults() == 1 && "expected single result bound map");
MLIR Team27d067e2019-01-16 17:55:02711 assert(lbMap.getNumDims() == ubMap.getNumDims());
712 assert(lbMap.getNumSymbols() == ubMap.getNumSymbols());
MLIR Team27d067e2019-01-16 17:55:02713 AffineExpr lbExpr(lbMap.getResult(0));
714 AffineExpr ubExpr(ubMap.getResult(0));
715 auto loopSpanExpr = simplifyAffineExpr(ubExpr - lbExpr, lbMap.getNumDims(),
716 lbMap.getNumSymbols());
717 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
718 if (!cExpr)
719 return None;
720 return cExpr.getValue();
721}
722
River Riddle5052bd82019-02-02 00:42:18723// Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop
MLIR Team38c2fe32019-01-14 19:26:25724// nest surrounding 'srcAccess' utilizing slice loop bounds in 'sliceState'.
725// Returns true on success, false otherwise (if a non-constant trip count
726// was encountered).
727// TODO(andydavis) Make this work with non-unit step loops.
MLIR Team27d067e2019-01-16 17:55:02728static bool buildSliceTripCountMap(
River Riddleb4992772019-02-04 18:38:47729 Instruction *srcOpInst, ComputationSliceState *sliceState,
River Riddle5052bd82019-02-02 00:42:18730 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountMap) {
731 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:02732 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:25733 unsigned numSrcLoopIVs = srcLoopIVs.size();
River Riddle5052bd82019-02-02 00:42:18734 // Populate map from AffineForOp -> trip count
MLIR Team38c2fe32019-01-14 19:26:25735 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
736 AffineMap lbMap = sliceState->lbs[i];
737 AffineMap ubMap = sliceState->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17738 if (lbMap == AffineMap() || ubMap == AffineMap()) {
MLIR Team38c2fe32019-01-14 19:26:25739 // The iteration of src loop IV 'i' was not sliced. Use full loop bounds.
740 if (srcLoopIVs[i]->hasConstantLowerBound() &&
741 srcLoopIVs[i]->hasConstantUpperBound()) {
River Riddle5052bd82019-02-02 00:42:18742 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] =
MLIR Team38c2fe32019-01-14 19:26:25743 srcLoopIVs[i]->getConstantUpperBound() -
744 srcLoopIVs[i]->getConstantLowerBound();
745 continue;
746 }
747 return false;
748 }
MLIR Team27d067e2019-01-16 17:55:02749 Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap);
750 if (!tripCount.hasValue())
MLIR Team38c2fe32019-01-14 19:26:25751 return false;
River Riddle5052bd82019-02-02 00:42:18752 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] = tripCount.getValue();
MLIR Team38c2fe32019-01-14 19:26:25753 }
754 return true;
755}
756
MLIR Team27d067e2019-01-16 17:55:02757// Removes load operations from 'srcLoads' which operate on 'memref', and
758// adds them to 'dstLoads'.
759static void
760moveLoadsAccessingMemrefTo(Value *memref,
River Riddleb4992772019-02-04 18:38:47761 SmallVectorImpl<Instruction *> *srcLoads,
762 SmallVectorImpl<Instruction *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02763 dstLoads->clear();
River Riddleb4992772019-02-04 18:38:47764 SmallVector<Instruction *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02765 for (auto *load : *srcLoads) {
766 if (load->cast<LoadOp>()->getMemRef() == memref)
767 dstLoads->push_back(load);
768 else
769 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25770 }
MLIR Team27d067e2019-01-16 17:55:02771 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25772}
773
MLIR Team27d067e2019-01-16 17:55:02774// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddleb4992772019-02-04 18:38:47775static unsigned getInnermostCommonLoopDepth(ArrayRef<Instruction *> ops) {
MLIR Team27d067e2019-01-16 17:55:02776 unsigned numOps = ops.size();
777 assert(numOps > 0);
778
River Riddle5052bd82019-02-02 00:42:18779 std::vector<SmallVector<OpPointer<AffineForOp>, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02780 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
781 for (unsigned i = 0; i < numOps; ++i) {
782 getLoopIVs(*ops[i], &loops[i]);
783 loopDepthLimit =
784 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25785 }
MLIR Team27d067e2019-01-16 17:55:02786
787 unsigned loopDepth = 0;
788 for (unsigned d = 0; d < loopDepthLimit; ++d) {
789 unsigned i;
790 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18791 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02792 break;
MLIR Team27d067e2019-01-16 17:55:02793 }
794 if (i != numOps)
795 break;
796 ++loopDepth;
797 }
798 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25799}
800
MLIR Teamd7c82442019-01-30 23:53:41801// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
802// and 'storeOpInsts' are satisfied.
River Riddleb4992772019-02-04 18:38:47803static unsigned getMaxLoopDepth(ArrayRef<Instruction *> loadOpInsts,
804 ArrayRef<Instruction *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41805 // Merge loads and stores into the same array.
River Riddleb4992772019-02-04 18:38:47806 SmallVector<Instruction *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41807 ops.append(storeOpInsts.begin(), storeOpInsts.end());
808
809 // Compute the innermost common loop depth for loads and stores.
810 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
811
812 // Return common loop depth for loads if there are no store ops.
813 if (storeOpInsts.empty())
814 return loopDepth;
815
816 // Check dependences on all pairs of ops in 'ops' and store the minimum
817 // loop depth at which a dependence is satisfied.
818 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
819 auto *srcOpInst = ops[i];
820 MemRefAccess srcAccess(srcOpInst);
821 for (unsigned j = 0; j < e; ++j) {
822 auto *dstOpInst = ops[j];
823 MemRefAccess dstAccess(dstOpInst);
824
825 unsigned numCommonLoops =
826 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
827 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
828 FlatAffineConstraints dependenceConstraints;
829 // TODO(andydavis) Cache dependence analysis results, check cache here.
830 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
831 &dependenceConstraints,
832 /*dependenceComponents=*/nullptr)) {
833 // Store minimum loop depth and break because we want the min 'd' at
834 // which there is a dependence.
835 loopDepth = std::min(loopDepth, d - 1);
836 break;
837 }
838 }
839 }
840 }
841 return loopDepth;
842}
843
MLIR Team8f5f2c72019-02-15 17:32:18844// Compute loop interchange permutation:
845// *) Computes dependence components between all op pairs in 'ops' for loop
846// depths in range [1, 'maxLoopDepth'].
847// *) Classifies the outermost 'maxLoopDepth' loops surrounding 'ops' as either
848// parallel or sequential.
849// *) Computes the loop permutation which sinks sequential loops deeper into
850// the loop nest, while preserving the relative order between other loops.
851// *) Checks each dependence component against the permutation to see if the
852// desired loop interchange would violated dependences by making the a
853// dependence componenent lexicographically negative.
854// TODO(andydavis) Move this function to LoopUtils.
855static bool
856computeLoopInterchangePermutation(ArrayRef<Instruction *> ops,
857 unsigned maxLoopDepth,
858 SmallVectorImpl<unsigned> *loopPermMap) {
859 // Gather dependence components for dependences between all ops in 'ops'
860 // at loop depths in range [1, maxLoopDepth].
861 // TODO(andydavis) Refactor this loop into a LoopUtil utility function:
862 // mlir::getDependenceComponents().
863 // TODO(andydavis) Split this loop into two: first check all dependences,
864 // and construct dep vectors. Then, scan through them to detect the parallel
865 // ones.
866 std::vector<llvm::SmallVector<DependenceComponent, 2>> depCompsVec;
867 llvm::SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true);
868 unsigned numOps = ops.size();
869 for (unsigned d = 1; d <= maxLoopDepth; ++d) {
870 for (unsigned i = 0; i < numOps; ++i) {
871 auto *srcOpInst = ops[i];
872 MemRefAccess srcAccess(srcOpInst);
873 for (unsigned j = 0; j < numOps; ++j) {
874 auto *dstOpInst = ops[j];
875 MemRefAccess dstAccess(dstOpInst);
876
877 FlatAffineConstraints dependenceConstraints;
878 llvm::SmallVector<DependenceComponent, 2> depComps;
879 // TODO(andydavis,bondhugula) Explore whether it would be profitable
880 // to pre-compute and store deps instead of repeatidly checking.
881 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
882 &dependenceConstraints, &depComps)) {
883 isParallelLoop[d - 1] = false;
884 depCompsVec.push_back(depComps);
885 }
886 }
887 }
888 }
889 // Count the number of parallel loops.
890 unsigned numParallelLoops = 0;
891 for (unsigned i = 0, e = isParallelLoop.size(); i < e; ++i)
892 if (isParallelLoop[i])
893 ++numParallelLoops;
894
895 // Compute permutation of loops that sinks sequential loops (and thus raises
896 // parallel loops) while preserving relative order.
897 llvm::SmallVector<unsigned, 4> loopPermMapInv;
898 loopPermMapInv.resize(maxLoopDepth);
899 loopPermMap->resize(maxLoopDepth);
900 unsigned nextSequentialLoop = numParallelLoops;
901 unsigned nextParallelLoop = 0;
902 for (unsigned i = 0; i < maxLoopDepth; ++i) {
903 if (isParallelLoop[i]) {
904 (*loopPermMap)[i] = nextParallelLoop;
905 loopPermMapInv[nextParallelLoop++] = i;
906 } else {
907 (*loopPermMap)[i] = nextSequentialLoop;
908 loopPermMapInv[nextSequentialLoop++] = i;
909 }
910 }
911
912 // Check each dependence component against the permutation to see if the
913 // desired loop interchange permutation would make the dependence vectors
914 // lexicographically negative.
915 // Example 1: [-1, 1][0, 0]
916 // Example 2: [0, 0][-1, 1]
917 for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) {
918 llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i];
919 assert(depComps.size() >= maxLoopDepth);
920 // Check if the first non-zero dependence component is positive.
921 for (unsigned j = 0; j < maxLoopDepth; ++j) {
922 unsigned permIndex = loopPermMapInv[j];
923 assert(depComps[permIndex].lb.hasValue());
924 int64_t depCompLb = depComps[permIndex].lb.getValue();
925 if (depCompLb > 0)
926 break;
927 if (depCompLb < 0)
928 return false;
929 }
930 }
931 return true;
932}
933
934// Sinks all sequential loops to the innermost levels (while preserving
935// relative order among them) and moves all parallel loops to the
936// outermost (while again preserving relative order among them).
937// This can increase the loop depth at which we can fuse a slice, since we are
938// pushing loop carried dependence to a greater depth in the loop nest.
939static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
940 assert(node->inst->isa<AffineForOp>());
941 // Get perfectly nested sequence of loops starting at root of loop nest.
942 // TODO(andydavis,bondhugula) Share this with similar code in loop tiling.
943 SmallVector<OpPointer<AffineForOp>, 4> loops;
944 OpPointer<AffineForOp> curr = node->inst->cast<AffineForOp>();
945 loops.push_back(curr);
946 auto *currBody = curr->getBody();
947 while (!currBody->empty() &&
948 std::next(currBody->begin()) == currBody->end() &&
949 (curr = curr->getBody()->front().dyn_cast<AffineForOp>())) {
950 loops.push_back(curr);
951 currBody = curr->getBody();
952 }
953 if (loops.size() < 2)
954 return;
955
956 // Merge loads and stores into the same array.
957 SmallVector<Instruction *, 2> memOps(node->loads.begin(), node->loads.end());
958 memOps.append(node->stores.begin(), node->stores.end());
959
960 // Compute loop permutation in 'loopPermMap'.
961 llvm::SmallVector<unsigned, 4> loopPermMap;
962 if (!computeLoopInterchangePermutation(memOps, loops.size(), &loopPermMap))
963 return;
964
965 int loopNestRootIndex = -1;
966 for (int i = loops.size() - 1; i >= 0; --i) {
967 int permIndex = static_cast<int>(loopPermMap[i]);
968 // Store the index of the for loop which will be the new loop nest root.
969 if (permIndex == 0)
970 loopNestRootIndex = i;
971 if (permIndex > i) {
972 // Sink loop 'i' by 'permIndex - i' levels deeper into the loop nest.
973 sinkLoop(loops[i], permIndex - i);
974 }
975 }
976 assert(loopNestRootIndex != -1 && "invalid root index");
977 node->inst = loops[loopNestRootIndex]->getInstruction();
978}
979
Uday Bondhugulac1ca23e2019-01-16 21:13:00980// Returns the slice union of 'sliceStateA' and 'sliceStateB' in 'sliceStateB'
981// using a rectangular bounding box.
MLIR Team27d067e2019-01-16 17:55:02982// TODO(andydavis) This function assumes that lower bounds for 'sliceStateA'
983// and 'sliceStateB' are aligned.
984// Specifically, when taking the union of overlapping intervals, it assumes
985// that both intervals start at zero. Support needs to be added to take into
986// account interval start offset when computing the union.
987// TODO(andydavis) Move this function to an analysis library.
Uday Bondhugulac1ca23e2019-01-16 21:13:00988static bool getSliceUnion(const ComputationSliceState &sliceStateA,
989 ComputationSliceState *sliceStateB) {
MLIR Team27d067e2019-01-16 17:55:02990 assert(sliceStateA.lbs.size() == sliceStateB->lbs.size());
991 assert(sliceStateA.ubs.size() == sliceStateB->ubs.size());
992
993 for (unsigned i = 0, e = sliceStateA.lbs.size(); i < e; ++i) {
994 AffineMap lbMapA = sliceStateA.lbs[i];
995 AffineMap ubMapA = sliceStateA.ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17996 if (lbMapA == AffineMap()) {
997 assert(ubMapA == AffineMap());
MLIR Team27d067e2019-01-16 17:55:02998 continue;
999 }
Uday Bondhugulac1ca23e2019-01-16 21:13:001000 assert(ubMapA && "expected non-null ub map");
MLIR Team27d067e2019-01-16 17:55:021001
1002 AffineMap lbMapB = sliceStateB->lbs[i];
1003 AffineMap ubMapB = sliceStateB->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:171004 if (lbMapB == AffineMap()) {
1005 assert(ubMapB == AffineMap());
MLIR Team27d067e2019-01-16 17:55:021006 // Union 'sliceStateB' does not have a bound for 'i' so copy from A.
1007 sliceStateB->lbs[i] = lbMapA;
1008 sliceStateB->ubs[i] = ubMapA;
1009 continue;
1010 }
Uday Bondhugulac1ca23e2019-01-16 21:13:001011
1012 // TODO(andydavis) Change this code to take the min across all lower bounds
1013 // and max across all upper bounds for each dimension. This code can for
1014 // cases where a unique min or max could not be statically determined.
1015
1016 // Assumption: both lower bounds are the same.
1017 if (lbMapA != lbMapB)
MLIR Team27d067e2019-01-16 17:55:021018 return false;
1019
1020 // Add bound with the largest trip count to union.
1021 Optional<uint64_t> tripCountA = getConstDifference(lbMapA, ubMapA);
1022 Optional<uint64_t> tripCountB = getConstDifference(lbMapB, ubMapB);
1023 if (!tripCountA.hasValue() || !tripCountB.hasValue())
1024 return false;
Uday Bondhugulac1ca23e2019-01-16 21:13:001025
MLIR Team27d067e2019-01-16 17:55:021026 if (tripCountA.getValue() > tripCountB.getValue()) {
1027 sliceStateB->lbs[i] = lbMapA;
1028 sliceStateB->ubs[i] = ubMapA;
1029 }
1030 }
1031 return true;
1032}
1033
Uday Bondhugula8be26272019-02-02 01:06:221034// TODO(mlir-team): improve/complete this when we have target data.
1035unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
1036 auto elementType = memRefType.getElementType();
1037
1038 unsigned sizeInBits;
1039 if (elementType.isIntOrFloat()) {
1040 sizeInBits = elementType.getIntOrFloatBitWidth();
1041 } else {
1042 auto vectorType = elementType.cast<VectorType>();
1043 sizeInBits =
1044 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
1045 }
1046 return llvm::divideCeil(sizeInBits, 8);
1047}
1048
MLIR Teamc4237ae2019-01-18 16:56:271049// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:181050// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:521051// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1052// TODO(bondhugula): consider refactoring the common code from generateDma and
1053// this one.
River Riddle5052bd82019-02-02 00:42:181054static Value *createPrivateMemRef(OpPointer<AffineForOp> forOp,
River Riddleb4992772019-02-04 18:38:471055 Instruction *srcStoreOpInst,
Uday Bondhugula8be26272019-02-02 01:06:221056 unsigned dstLoopDepth,
1057 Optional<unsigned> fastMemorySpace,
Uday Bondhugulad4b3ff12019-02-27 00:10:191058 uint64_t localBufSizeThreshold) {
River Riddle5052bd82019-02-02 00:42:181059 auto *forInst = forOp->getInstruction();
1060
1061 // Create builder to insert alloc op just before 'forOp'.
MLIR Teamc4237ae2019-01-18 16:56:271062 FuncBuilder b(forInst);
1063 // Builder to create constants at the top level.
1064 FuncBuilder top(forInst->getFunction());
1065 // Create new memref type based on slice bounds.
1066 auto *oldMemRef = srcStoreOpInst->cast<StoreOp>()->getMemRef();
1067 auto oldMemRefType = oldMemRef->getType().cast<MemRefType>();
1068 unsigned rank = oldMemRefType.getRank();
1069
Uday Bondhugula94a03f82019-01-22 21:58:521070 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:441071 MemRefRegion region(srcStoreOpInst->getLoc());
1072 region.compute(srcStoreOpInst, dstLoopDepth);
River Riddle6859f332019-01-23 22:39:451073 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:271074 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:521075 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:271076 lbs.reserve(rank);
1077 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:521078 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:271079 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:441080 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:221081 assert(numElements.hasValue() &&
1082 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:271083
Uday Bondhugula0f504142019-02-04 21:48:441084 const FlatAffineConstraints *cst = region.getConstraints();
Uday Bondhugula94a03f82019-01-22 21:58:521085 // 'outerIVs' holds the values that this memory region is symbolic/paramteric
1086 // on; this would correspond to loop IVs surrounding the level at which the
1087 // slice is being materialized.
1088 SmallVector<Value *, 8> outerIVs;
1089 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
1090
1091 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:271092 SmallVector<AffineExpr, 4> offsets;
1093 offsets.reserve(rank);
1094 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:521095 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
1096
MLIR Teamc4237ae2019-01-18 16:56:271097 AffineExpr offset = top.getAffineConstantExpr(0);
1098 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
1099 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
1100 }
Uday Bondhugula94a03f82019-01-22 21:58:521101 assert(lbDivisors[d] > 0);
1102 offset =
1103 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:271104 offsets.push_back(offset);
1105 }
1106
1107 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
1108 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:221109 uint64_t bufSize =
1110 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
1111 unsigned newMemSpace;
Uday Bondhugulad4b3ff12019-02-27 00:10:191112 if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
Uday Bondhugula8be26272019-02-02 01:06:221113 newMemSpace = fastMemorySpace.getValue();
1114 } else {
1115 newMemSpace = oldMemRefType.getMemorySpace();
1116 }
1117 auto newMemRefType = top.getMemRefType(
1118 newShape, oldMemRefType.getElementType(), {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:271119 // Gather alloc operands for the dynamic dimensions of the memref.
1120 SmallVector<Value *, 4> allocOperands;
1121 unsigned dynamicDimCount = 0;
1122 for (auto dimSize : oldMemRefType.getShape()) {
1123 if (dimSize == -1)
1124 allocOperands.push_back(
River Riddle5052bd82019-02-02 00:42:181125 top.create<DimOp>(forOp->getLoc(), oldMemRef, dynamicDimCount++));
MLIR Teamc4237ae2019-01-18 16:56:271126 }
1127
River Riddle5052bd82019-02-02 00:42:181128 // Create new private memref for fused loop 'forOp'.
MLIR Teama0f3db402019-01-29 17:36:411129 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
1130 // consumer loop nests to reduce their live range. Currently they are added
1131 // at the beginning of the function, because loop nests can be reordered
1132 // during the fusion pass.
MLIR Teamc4237ae2019-01-18 16:56:271133 Value *newMemRef =
River Riddle5052bd82019-02-02 00:42:181134 top.create<AllocOp>(forOp->getLoc(), newMemRefType, allocOperands);
MLIR Teamc4237ae2019-01-18 16:56:271135
1136 // Build an AffineMap to remap access functions based on lower bound offsets.
1137 SmallVector<AffineExpr, 4> remapExprs;
1138 remapExprs.reserve(rank);
1139 unsigned zeroOffsetCount = 0;
1140 for (unsigned i = 0; i < rank; i++) {
1141 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
1142 if (constExpr.getValue() == 0)
1143 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:521144 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
1145
1146 auto remapExpr =
1147 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
1148 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:271149 }
Uday Bondhugula94a03f82019-01-22 21:58:521150 auto indexRemap =
1151 zeroOffsetCount == rank
Nicolas Vasilache0e7a8a92019-01-26 18:41:171152 ? AffineMap()
Uday Bondhugula94a03f82019-01-22 21:58:521153 : b.getAffineMap(outerIVs.size() + rank, 0, remapExprs, {});
MLIR Teamc4237ae2019-01-18 16:56:271154 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugula94a03f82019-01-22 21:58:521155 bool ret =
1156 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
1157 /*extraOperands=*/outerIVs,
River Riddle5052bd82019-02-02 00:42:181158 /*domInstFilter=*/&*forOp->getBody()->begin());
Uday Bondhugula94a03f82019-01-22 21:58:521159 assert(ret && "replaceAllMemrefUsesWith should always succeed here");
MLIR Team71495d52019-01-22 21:23:371160 (void)ret;
MLIR Teamc4237ae2019-01-18 16:56:271161 return newMemRef;
1162}
1163
Uday Bondhugula864d9e02019-01-23 17:16:241164// Does the slice have a single iteration?
1165static uint64_t getSliceIterationCount(
River Riddle5052bd82019-02-02 00:42:181166 const llvm::SmallDenseMap<Instruction *, uint64_t, 8> &sliceTripCountMap) {
Uday Bondhugula864d9e02019-01-23 17:16:241167 uint64_t iterCount = 1;
1168 for (const auto &count : sliceTripCountMap) {
1169 iterCount *= count.second;
1170 }
1171 return iterCount;
1172}
1173
MLIR Team58aa3832019-02-16 01:12:191174// Checks if node 'srcId' (which writes to a live out memref), can be safely
1175// fused into node 'dstId'. Returns true if the following conditions are met:
1176// *) 'srcNode' writes only writes to live out 'memref'.
1177// *) 'srcNode' has exaclty one output edge on 'memref' (which is to 'dstId').
1178// *) 'dstNode' does write to 'memref'.
1179// *) 'dstNode's write region to 'memref' is a super set of 'srcNode's write
1180// region to 'memref'.
1181// TODO(andydavis) Generalize this to handle more live in/out cases.
1182static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
1183 Value *memref,
1184 MemRefDependenceGraph *mdg) {
1185 auto *srcNode = mdg->getNode(srcId);
1186 auto *dstNode = mdg->getNode(dstId);
1187
1188 // Return false if any of the following are true:
1189 // *) 'srcNode' writes to a live in/out memref other than 'memref'.
1190 // *) 'srcNode' has more than one output edge on 'memref'.
1191 // *) 'dstNode' does not write to 'memref'.
1192 if (srcNode->getStoreOpCount(memref) != 1 ||
1193 mdg->getOutEdgeCount(srcNode->id, memref) != 1 ||
1194 dstNode->getStoreOpCount(memref) == 0)
1195 return false;
1196 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOpInst' on 'memref'.
1197 auto *srcStoreOpInst = srcNode->stores.front();
1198 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
1199 srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0);
1200 SmallVector<int64_t, 4> srcShape;
1201 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
1202 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1203 Optional<int64_t> srcNumElements =
1204 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1205 if (!srcNumElements.hasValue())
1206 return false;
1207
1208 // Compute MemRefRegion 'dstWriteRegion' for 'dstStoreOpInst' on 'memref'.
1209 SmallVector<Instruction *, 2> dstStoreOps;
1210 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1211 assert(dstStoreOps.size() == 1);
1212 auto *dstStoreOpInst = dstStoreOps[0];
1213 MemRefRegion dstWriteRegion(dstStoreOpInst->getLoc());
1214 dstWriteRegion.compute(dstStoreOpInst, /*loopDepth=*/0);
1215 SmallVector<int64_t, 4> dstShape;
1216 // Query 'dstWriteRegion' for 'dstShape' and 'dstNumElements'.
1217 // by 'dstStoreOpInst' at depth 'dstLoopDepth'.
1218 Optional<int64_t> dstNumElements =
1219 dstWriteRegion.getConstantBoundingSizeAndShape(&dstShape);
1220 if (!dstNumElements.hasValue())
1221 return false;
1222
1223 // Return false if write region is not a superset of 'srcNodes' write
1224 // region to 'memref'.
1225 // TODO(andydavis) Check the shape and lower bounds here too.
1226 if (srcNumElements != dstNumElements)
1227 return false;
1228 return true;
1229}
1230
MLIR Team27d067e2019-01-16 17:55:021231// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411232// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
Uday Bondhugulab4a14432019-01-26 00:00:501233// Returns true if it is profitable to fuse the candidate loop nests. Returns
1234// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1235// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251236// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021237// *) Computes the backward computation slice at 'srcOpInst'. This
1238// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251239// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021240// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251241// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1242// loop nest is the total number of dynamic operation instances in the loop
1243// nest).
1244// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021245// loop nest at various values of dst loop depth, attempting to fuse
1246// the largest compution slice at the maximal dst loop depth (closest to the
1247// load) to minimize reuse distance and potentially enable subsequent
1248// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411249// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021250// the same memref as is written by 'srcOpInst', then the union of slice
1251// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501252// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251253// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021254// NOTE: We attempt to maximize the dst loop depth, but there are cases
1255// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251256// loop (within the src computation slice) at a depth which results in
1257// execessive recomputation (see unit tests for examples).
1258// *) Compares the total cost of the unfused loop nests to the min cost fused
1259// loop nest computed in the previous step, and returns true if the latter
1260// is lower.
River Riddleb4992772019-02-04 18:38:471261static bool isFusionProfitable(Instruction *srcOpInst,
1262 ArrayRef<Instruction *> dstLoadOpInsts,
1263 ArrayRef<Instruction *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251264 ComputationSliceState *sliceState,
MLIR Team27d067e2019-01-16 17:55:021265 unsigned *dstLoopDepth) {
Uday Bondhugula06d21d92019-01-25 01:01:491266 LLVM_DEBUG({
1267 llvm::dbgs() << "Checking whether fusion is profitable between:\n";
Uday Bondhugulaa1dad3a2019-02-20 02:17:191268 llvm::dbgs() << " " << *srcOpInst << " and \n";
MLIR Teamd7c82442019-01-30 23:53:411269 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191270 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491271 };
1272 });
Uday Bondhugula864d9e02019-01-23 17:16:241273
MLIR Team38c2fe32019-01-14 19:26:251274 // Compute cost of sliced and unsliced src loop nest.
River Riddle5052bd82019-02-02 00:42:181275 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021276 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251277 unsigned numSrcLoopIVs = srcLoopIVs.size();
1278
1279 // Walk src loop nest and collect stats.
1280 LoopNestStats srcLoopNestStats;
1281 LoopNestStatsCollector srcStatsCollector(&srcLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441282 srcStatsCollector.collect(srcLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251283 // Currently only constant trip count loop nests are supported.
1284 if (srcStatsCollector.hasLoopWithNonConstTripCount)
1285 return false;
1286
1287 // Compute cost of dst loop nest.
River Riddle5052bd82019-02-02 00:42:181288 SmallVector<OpPointer<AffineForOp>, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411289 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251290
1291 LoopNestStats dstLoopNestStats;
1292 LoopNestStatsCollector dstStatsCollector(&dstLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441293 dstStatsCollector.collect(dstLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251294 // Currently only constant trip count loop nests are supported.
1295 if (dstStatsCollector.hasLoopWithNonConstTripCount)
1296 return false;
1297
MLIR Teamd7c82442019-01-30 23:53:411298 // Compute the maximum loop depth at which we can can insert the src slice
1299 // and still satisfy dest loop nest dependences.
1300 unsigned maxDstLoopDepth = getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts);
MLIR Team27d067e2019-01-16 17:55:021301 if (maxDstLoopDepth == 0)
1302 return false;
1303
1304 // Search for min cost value for 'dstLoopDepth'. At each value of
1305 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1306 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1307 // of these bounds). Next the union slice bounds are used to calculate
1308 // the cost of the slice and the cost of the slice inserted into the dst
1309 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241310 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
1311 uint64_t maxStorageReduction = 0;
1312 Optional<uint64_t> sliceMemEstimate = None;
1313
MLIR Team27d067e2019-01-16 17:55:021314 SmallVector<ComputationSliceState, 4> sliceStates;
1315 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241316 // The best loop depth at which to materialize the slice.
1317 Optional<unsigned> bestDstLoopDepth = None;
1318
1319 // Compute op instance count for the src loop nest without iteration slicing.
River Riddle5052bd82019-02-02 00:42:181320 uint64_t srcLoopNestCost =
1321 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
1322 /*tripCountOverrideMap=*/nullptr,
1323 /*computeCostMap=*/nullptr);
Uday Bondhugula864d9e02019-01-23 17:16:241324
MLIR Teamb9dde912019-02-06 19:01:101325 // Compute src loop nest write region size.
1326 MemRefRegion srcWriteRegion(srcOpInst->getLoc());
1327 srcWriteRegion.compute(srcOpInst, /*loopDepth=*/0);
1328 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1329 srcWriteRegion.getRegionSize();
1330 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1331 return false;
1332 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1333
Uday Bondhugula864d9e02019-01-23 17:16:241334 // Compute op instance count for the src loop nest.
River Riddle5052bd82019-02-02 00:42:181335 uint64_t dstLoopNestCost =
1336 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
1337 /*tripCountOverrideMap=*/nullptr,
1338 /*computeCostMap=*/nullptr);
MLIR Team27d067e2019-01-16 17:55:021339
MLIR Teamb9dde912019-02-06 19:01:101340 // Evaluate all depth choices for materializing the slice in the destination
1341 // loop nest.
River Riddle5052bd82019-02-02 00:42:181342 llvm::SmallDenseMap<Instruction *, uint64_t, 8> sliceTripCountMap;
1343 DenseMap<Instruction *, int64_t> computeCostMap;
MLIR Team27d067e2019-01-16 17:55:021344 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
1345 MemRefAccess srcAccess(srcOpInst);
1346 // Handle the common case of one dst load without a copy.
1347 if (!mlir::getBackwardComputationSliceState(
MLIR Teamd7c82442019-01-30 23:53:411348 srcAccess, MemRefAccess(dstLoadOpInsts[0]), i, &sliceStates[i - 1]))
MLIR Team27d067e2019-01-16 17:55:021349 return false;
MLIR Teamd7c82442019-01-30 23:53:411350 // Compute the union of slice bound of all ops in 'dstLoadOpInsts'.
1351 for (int j = 1, e = dstLoadOpInsts.size(); j < e; ++j) {
1352 MemRefAccess dstAccess(dstLoadOpInsts[j]);
MLIR Team27d067e2019-01-16 17:55:021353 ComputationSliceState tmpSliceState;
1354 if (!mlir::getBackwardComputationSliceState(srcAccess, dstAccess, i,
1355 &tmpSliceState))
1356 return false;
1357 // Compute slice boun dunion of 'tmpSliceState' and 'sliceStates[i - 1]'.
Uday Bondhugulac1ca23e2019-01-16 21:13:001358 getSliceUnion(tmpSliceState, &sliceStates[i - 1]);
MLIR Team38c2fe32019-01-14 19:26:251359 }
Uday Bondhugulab4a14432019-01-26 00:00:501360 // Build trip count map for computation slice. We'll skip cases where the
1361 // trip count was non-constant.
MLIR Team27d067e2019-01-16 17:55:021362 sliceTripCountMap.clear();
1363 if (!buildSliceTripCountMap(srcOpInst, &sliceStates[i - 1],
1364 &sliceTripCountMap))
Uday Bondhugula864d9e02019-01-23 17:16:241365 continue;
1366
1367 // Checks whether a store to load forwarding will happen.
1368 int64_t sliceIterationCount = getSliceIterationCount(sliceTripCountMap);
Uday Bondhugula864d9e02019-01-23 17:16:241369 assert(sliceIterationCount > 0);
Uday Bondhugulab4a14432019-01-26 00:00:501370 bool storeLoadFwdGuaranteed = (sliceIterationCount == 1);
Uday Bondhugula864d9e02019-01-23 17:16:241371
1372 // Compute cost of fusion for this dest loop depth.
1373
1374 computeCostMap.clear();
1375
1376 // The store and loads to this memref will disappear.
1377 if (storeLoadFwdGuaranteed) {
1378 // A single store disappears: -1 for that.
River Riddle5052bd82019-02-02 00:42:181379 computeCostMap[srcLoopIVs[numSrcLoopIVs - 1]->getInstruction()] = -1;
MLIR Teamd7c82442019-01-30 23:53:411380 for (auto *loadOp : dstLoadOpInsts) {
River Riddle5052bd82019-02-02 00:42:181381 auto *parentInst = loadOp->getParentInst();
River Riddleb4992772019-02-04 18:38:471382 if (parentInst && parentInst->isa<AffineForOp>())
River Riddle5052bd82019-02-02 00:42:181383 computeCostMap[parentInst] = -1;
Uday Bondhugula864d9e02019-01-23 17:16:241384 }
1385 }
MLIR Team27d067e2019-01-16 17:55:021386
MLIR Team38c2fe32019-01-14 19:26:251387 // Compute op instance count for the src loop nest with iteration slicing.
Uday Bondhugula864d9e02019-01-23 17:16:241388 int64_t sliceComputeCost =
River Riddle5052bd82019-02-02 00:42:181389 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
Uday Bondhugula864d9e02019-01-23 17:16:241390 /*tripCountOverrideMap=*/&sliceTripCountMap,
1391 /*computeCostMap=*/&computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:251392
Uday Bondhugula864d9e02019-01-23 17:16:241393 // Compute cost of fusion for this depth.
River Riddle5052bd82019-02-02 00:42:181394 computeCostMap[dstLoopIVs[i - 1]->getInstruction()] = sliceComputeCost;
Uday Bondhugula864d9e02019-01-23 17:16:241395
1396 int64_t fusedLoopNestComputeCost =
River Riddle5052bd82019-02-02 00:42:181397 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
MLIR Team27d067e2019-01-16 17:55:021398 /*tripCountOverrideMap=*/nullptr, &computeCostMap);
Uday Bondhugula864d9e02019-01-23 17:16:241399
1400 double additionalComputeFraction =
1401 fusedLoopNestComputeCost /
1402 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1403 1;
1404
MLIR Teamb9dde912019-02-06 19:01:101405 // Compute what the slice write MemRefRegion would be, if the src loop
1406 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1407 // nest at loop depth 'i'
1408 MemRefRegion sliceWriteRegion(srcOpInst->getLoc());
1409 sliceWriteRegion.compute(srcOpInst, /*loopDepth=*/0, &sliceStates[i - 1]);
1410 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1411 sliceWriteRegion.getRegionSize();
1412 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
1413 maybeSliceWriteRegionSizeBytes.getValue() == 0)
1414 continue;
1415 int64_t sliceWriteRegionSizeBytes =
1416 maybeSliceWriteRegionSizeBytes.getValue();
1417
1418 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1419 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241420
Uday Bondhugula06d21d92019-01-25 01:01:491421 LLVM_DEBUG({
1422 std::stringstream msg;
1423 msg << " evaluating fusion profitability at depth : " << i << "\n"
Uday Bondhugulad4b3ff12019-02-27 00:10:191424 << std::fixed << std::setprecision(2)
1425 << " additional compute fraction: "
Uday Bondhugula06d21d92019-01-25 01:01:491426 << 100.0 * additionalComputeFraction << "%\n"
1427 << " storage reduction factor: " << storageReduction << "x\n"
1428 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191429 << " slice iteration count: " << sliceIterationCount << "\n"
1430 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1431 << " slice write region size: " << sliceWriteRegionSizeBytes
1432 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491433 llvm::dbgs() << msg.str();
1434 });
Uday Bondhugula864d9e02019-01-23 17:16:241435
1436 double computeToleranceThreshold =
1437 clFusionAddlComputeTolerance.getNumOccurrences() > 0
1438 ? clFusionAddlComputeTolerance
1439 : LoopFusion::kComputeToleranceThreshold;
1440
1441 // TODO(b/123247369): This is a placeholder cost model.
1442 // Among all choices that add an acceptable amount of redundant computation
1443 // (as per computeToleranceThreshold), we will simply pick the one that
1444 // reduces the intermediary size the most.
1445 if ((storageReduction > maxStorageReduction) &&
1446 (clMaximalLoopFusion ||
1447 (additionalComputeFraction < computeToleranceThreshold))) {
1448 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021449 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241450 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101451 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251452 }
1453 }
1454
Uday Bondhugula864d9e02019-01-23 17:16:241455 // A simple cost model: fuse if it reduces the memory footprint. If
1456 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251457
Uday Bondhugula864d9e02019-01-23 17:16:241458 if (!clMaximalLoopFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191459 LLVM_DEBUG(
1460 llvm::dbgs()
1461 << "All fusion choices involve more than the threshold amount of "
1462 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251463 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241464 }
1465
1466 assert(bestDstLoopDepth.hasValue() &&
1467 "expected to have a value per logic above");
1468
1469 // Set dstLoopDepth based on best values from search.
1470 *dstLoopDepth = bestDstLoopDepth.getValue();
1471
1472 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491473 llvm::dbgs() << " LoopFusion fusion stats:"
1474 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241475 << "\n src loop nest compute cost: " << srcLoopNestCost
1476 << "\n dst loop nest compute cost: " << dstLoopNestCost
1477 << "\n fused loop nest compute cost: "
1478 << minFusedLoopNestComputeCost << "\n");
1479
River Riddle5052bd82019-02-02 00:42:181480 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1481 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241482
1483 Optional<double> storageReduction = None;
1484
1485 if (!clMaximalLoopFusion) {
1486 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1487 LLVM_DEBUG(
1488 llvm::dbgs()
1489 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1490 return false;
1491 }
1492
1493 auto srcMemSizeVal = srcMemSize.getValue();
1494 auto dstMemSizeVal = dstMemSize.getValue();
1495
1496 assert(sliceMemEstimate.hasValue() && "expected value");
1497 // This is an inaccurate estimate since sliceMemEstimate is isaccurate.
1498 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1499
1500 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1501 << " dst mem: " << dstMemSizeVal << "\n"
1502 << " fused mem: " << fusedMem << "\n"
1503 << " slice mem: " << sliceMemEstimate << "\n");
1504
1505 if (fusedMem > srcMemSizeVal + dstMemSizeVal) {
1506 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1507 return false;
1508 }
1509 storageReduction =
1510 100.0 *
1511 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1512 }
1513
1514 double additionalComputeFraction =
1515 100.0 * (minFusedLoopNestComputeCost /
1516 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1517 1);
MLIR Team5c5739d2019-01-25 06:27:401518 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491519 LLVM_DEBUG({
1520 std::stringstream msg;
1521 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591522 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491523 << "% redundant computation and a ";
1524 msg << (storageReduction.hasValue()
1525 ? std::to_string(storageReduction.getValue())
1526 : "<unknown>");
1527 msg << "% storage reduction.\n";
1528 llvm::dbgs() << msg.str();
1529 });
Uday Bondhugula864d9e02019-01-23 17:16:241530
MLIR Team27d067e2019-01-16 17:55:021531 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241532 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021533 sliceState->lbs = bestSliceState->lbs;
1534 sliceState->ubs = bestSliceState->ubs;
1535 sliceState->lbOperands = bestSliceState->lbOperands;
1536 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241537
MLIR Team27d067e2019-01-16 17:55:021538 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251539 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171540 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021541 canonicalizeMapAndOperands(&sliceState->lbs[i],
1542 &sliceState->lbOperands[i]);
1543 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171544 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021545 canonicalizeMapAndOperands(&sliceState->ubs[i],
1546 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251547 }
1548 }
1549 return true;
1550}
1551
MLIR Team6892ffb2018-12-20 04:42:551552// GreedyFusion greedily fuses loop nests which have a producer/consumer
MLIR Team3b692302018-12-17 17:57:141553// relationship on a memref, with the goal of improving locality. Currently,
1554// this the producer/consumer relationship is required to be unique in the
Chris Lattner69d9e992018-12-28 16:48:091555// Function (there are TODOs to relax this constraint in the future).
MLIR Teamf28e4df2018-11-01 14:26:001556//
MLIR Team3b692302018-12-17 17:57:141557// The steps of the algorithm are as follows:
1558//
MLIR Team6892ffb2018-12-20 04:42:551559// *) A worklist is initialized with node ids from the dependence graph.
1560// *) For each node id in the worklist:
River Riddle5052bd82019-02-02 00:42:181561// *) Pop a AffineForOp of the worklist. This 'dstAffineForOp' will be a
1562// candidate destination AffineForOp into which fusion will be attempted.
1563// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141564// *) For each LoadOp in 'dstLoadOps' do:
Chris Lattner69d9e992018-12-28 16:48:091565// *) Lookup dependent loop nests at earlier positions in the Function
MLIR Team3b692302018-12-17 17:57:141566// which have a single store op to the same memref.
1567// *) Check if dependences would be violated by the fusion. For example,
1568// the src loop nest may load from memrefs which are different than
1569// the producer-consumer memref between src and dest loop nests.
MLIR Team6892ffb2018-12-20 04:42:551570// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141571// bounds to be functions of 'dstLoopNest' IVs and symbols.
1572// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
1573// just before the dst load op user.
Chris Lattner456ad6a2018-12-29 00:05:351574// *) Add the newly fused load/store operation instructions to the state,
MLIR Team3b692302018-12-17 17:57:141575// and also add newly fuse load ops to 'dstLoopOps' to be considered
1576// as fusion dst load ops in another iteration.
1577// *) Remove old src loop nest and its associated state.
1578//
Chris Lattner456ad6a2018-12-29 00:05:351579// Given a graph where top-level instructions are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141580// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551581// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141582//
MLIR Team6892ffb2018-12-20 04:42:551583// This greedy algorithm is not 'maximal' due to the current restriction of
1584// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141585//
1586// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551587// TODO(andydavis) Add support for fusing for input reuse (perhaps by
1588// constructing a graph with edges which represent loads from the same memref
MLIR Team5c5739d2019-01-25 06:27:401589// in two different loop nests.
MLIR Team6892ffb2018-12-20 04:42:551590struct GreedyFusion {
1591public:
1592 MemRefDependenceGraph *mdg;
MLIR Teama78edcd2019-02-05 14:57:081593 SmallVector<unsigned, 8> worklist;
1594 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamf28e4df2018-11-01 14:26:001595
MLIR Team6892ffb2018-12-20 04:42:551596 GreedyFusion(MemRefDependenceGraph *mdg) : mdg(mdg) {
1597 // Initialize worklist with nodes from 'mdg'.
MLIR Teama78edcd2019-02-05 14:57:081598 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1599 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Team6892ffb2018-12-20 04:42:551600 worklist.resize(mdg->nodes.size());
1601 std::iota(worklist.begin(), worklist.end(), 0);
MLIR Teama78edcd2019-02-05 14:57:081602 worklistSet.insert(worklist.begin(), worklist.end());
MLIR Team6892ffb2018-12-20 04:42:551603 }
MLIR Team3b692302018-12-17 17:57:141604
Uday Bondhugula8be26272019-02-02 01:06:221605 void run(unsigned localBufSizeThreshold, Optional<unsigned> fastMemorySpace) {
MLIR Team3b692302018-12-17 17:57:141606 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551607 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141608 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081609 worklistSet.erase(dstId);
1610
MLIR Team6892ffb2018-12-20 04:42:551611 // Skip if this node was removed (fused into another node).
1612 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141613 continue;
MLIR Team6892ffb2018-12-20 04:42:551614 // Get 'dstNode' into which to attempt fusion.
1615 auto *dstNode = mdg->getNode(dstId);
1616 // Skip if 'dstNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471617 if (!dstNode->inst->isa<AffineForOp>())
MLIR Team3b692302018-12-17 17:57:141618 continue;
MLIR Team8f5f2c72019-02-15 17:32:181619 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1620 // while preserving relative order. This can increase the maximum loop
1621 // depth at which we can fuse a slice of a producer loop nest into a
1622 // consumer loop nest.
1623 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141624
River Riddleb4992772019-02-04 18:38:471625 SmallVector<Instruction *, 4> loads = dstNode->loads;
1626 SmallVector<Instruction *, 4> dstLoadOpInsts;
MLIR Teamc4237ae2019-01-18 16:56:271627 DenseSet<Value *> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551628 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021629 // Get memref of load on top of the stack.
1630 auto *memref = loads.back()->cast<LoadOp>()->getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271631 if (visitedMemrefs.count(memref) > 0)
1632 continue;
1633 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021634 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1635 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551636 // Skip if no input edges along which to fuse.
1637 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141638 continue;
MLIR Team1e851912019-01-31 00:01:461639 // Iterate through in edges for 'dstId' and src node id for any
1640 // edges on 'memref'.
1641 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551642 for (auto &srcEdge : mdg->inEdges[dstId]) {
1643 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411644 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551645 continue;
MLIR Team1e851912019-01-31 00:01:461646 srcNodeIds.push_back(srcEdge.id);
1647 }
1648 for (unsigned srcId : srcNodeIds) {
1649 // Skip if this node was removed (fused into another node).
1650 if (mdg->nodes.count(srcId) == 0)
1651 continue;
1652 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1653 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551654 // Skip if 'srcNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471655 if (!srcNode->inst->isa<AffineForOp>())
MLIR Team6892ffb2018-12-20 04:42:551656 continue;
MLIR Teamb28009b2019-01-23 19:11:431657 // Skip if 'srcNode' has more than one store to any memref.
1658 // TODO(andydavis) Support fusing multi-output src loop nests.
1659 if (srcNode->stores.size() != 1)
MLIR Team6892ffb2018-12-20 04:42:551660 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241661
MLIR Teama0f3db402019-01-29 17:36:411662 // Skip 'srcNode' if it has in edges on 'memref'.
MLIR Team6892ffb2018-12-20 04:42:551663 // TODO(andydavis) Track dependence type with edges, and just check
MLIR Teama0f3db402019-01-29 17:36:411664 // for WAW dependence edge here. Note that this check is overly
1665 // conservative and will be removed in the future.
1666 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) != 0)
MLIR Team6892ffb2018-12-20 04:42:551667 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241668
MLIR Team58aa3832019-02-16 01:12:191669 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1670 // and cannot be fused.
1671 bool writesToLiveInOrOut =
1672 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1673 if (writesToLiveInOrOut &&
1674 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, memref, mdg))
MLIR Teamd7c82442019-01-30 23:53:411675 continue;
1676
MLIR Teama0f3db402019-01-29 17:36:411677 // Compute an instruction list insertion point for the fused loop
1678 // nest which preserves dependences.
MLIR Teama78edcd2019-02-05 14:57:081679 Instruction *insertPointInst =
1680 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411681 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551682 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241683
MLIR Team6892ffb2018-12-20 04:42:551684 // Get unique 'srcNode' store op.
Chris Lattner456ad6a2018-12-29 00:05:351685 auto *srcStoreOpInst = srcNode->stores.front();
MLIR Teamd7c82442019-01-30 23:53:411686 // Gather 'dstNode' store ops to 'memref'.
River Riddleb4992772019-02-04 18:38:471687 SmallVector<Instruction *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411688 for (auto *storeOpInst : dstNode->stores)
1689 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1690 dstStoreOpInsts.push_back(storeOpInst);
1691
Uday Bondhugulab4a14432019-01-26 00:00:501692 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251693 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411694 // Check if fusion would be profitable.
MLIR Teamd7c82442019-01-30 23:53:411695 if (!isFusionProfitable(srcStoreOpInst, dstLoadOpInsts,
1696 dstStoreOpInsts, &sliceState,
Uday Bondhugulab4a14432019-01-26 00:00:501697 &bestDstLoopDepth))
MLIR Team38c2fe32019-01-14 19:26:251698 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241699
MLIR Team6892ffb2018-12-20 04:42:551700 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181701 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Uday Bondhugulab4a14432019-01-26 00:00:501702 srcStoreOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
MLIR Team6892ffb2018-12-20 04:42:551703 if (sliceLoopNest != nullptr) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191704 LLVM_DEBUG(llvm::dbgs()
1705 << "\tslice loop nest:\n"
1706 << *sliceLoopNest->getInstruction() << "\n");
River Riddle5052bd82019-02-02 00:42:181707 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleb4992772019-02-04 18:38:471708 auto dstAffineForOp = dstNode->inst->cast<AffineForOp>();
River Riddle5052bd82019-02-02 00:42:181709 if (insertPointInst != dstAffineForOp->getInstruction()) {
1710 dstAffineForOp->getInstruction()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411711 }
MLIR Teamc4237ae2019-01-18 16:56:271712 // Update edges between 'srcNode' and 'dstNode'.
MLIR Teama0f3db402019-01-29 17:36:411713 mdg->updateEdges(srcNode->id, dstNode->id, memref);
MLIR Teamc4237ae2019-01-18 16:56:271714
1715 // Collect slice loop stats.
1716 LoopNestStateCollector sliceCollector;
River Riddlebf9c3812019-02-05 00:24:441717 sliceCollector.collect(sliceLoopNest->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271718 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181719 for (auto forOp : sliceCollector.forOps) {
1720 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551721 }
MLIR Team58aa3832019-02-16 01:12:191722 if (!writesToLiveInOrOut) {
1723 // Create private memref for 'memref' in 'dstAffineForOp'.
1724 SmallVector<Instruction *, 4> storesForMemref;
1725 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
1726 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1727 storesForMemref.push_back(storeOpInst);
1728 }
1729 assert(storesForMemref.size() == 1);
1730 auto *newMemRef = createPrivateMemRef(
1731 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1732 fastMemorySpace, localBufSizeThreshold);
1733 visitedMemrefs.insert(newMemRef);
1734 // Create new node in dependence graph for 'newMemRef' alloc op.
1735 unsigned newMemRefNodeId =
1736 mdg->addNode(newMemRef->getDefiningInst());
1737 // Add edge from 'newMemRef' node to dstNode.
1738 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271739 }
MLIR Teamc4237ae2019-01-18 16:56:271740
1741 // Collect dst loop stats after memref privatizaton transformation.
1742 LoopNestStateCollector dstLoopCollector;
River Riddlebf9c3812019-02-05 00:24:441743 dstLoopCollector.collect(dstAffineForOp->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271744
1745 // Add new load ops to current Node load op list 'loads' to
1746 // continue fusing based on new operands.
1747 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
1748 auto *loadMemRef = loadOpInst->cast<LoadOp>()->getMemRef();
1749 if (visitedMemrefs.count(loadMemRef) == 0)
1750 loads.push_back(loadOpInst);
1751 }
1752
1753 // Clear and add back loads and stores
1754 mdg->clearNodeLoadAndStores(dstNode->id);
1755 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1756 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371757 // Remove old src loop nest if it no longer has outgoing dependence
1758 // edges, and it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191759 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1760 // been fused into 'dstNode' and write region of 'dstNode' covers
1761 // the write region of 'srcNode', and 'srcNode' has no other users
1762 // so it is safe to remove.
1763 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271764 mdg->removeNode(srcNode->id);
River Riddle5052bd82019-02-02 00:42:181765 srcNode->inst->erase();
MLIR Teama78edcd2019-02-05 14:57:081766 } else {
1767 // Add remaining users of 'oldMemRef' back on the worklist (if not
1768 // already there), as its replacement with a local/private memref
1769 // has reduced dependences on 'oldMemRef' which may have created
1770 // new fusion opportunities.
1771 if (mdg->outEdges.count(srcNode->id) > 0) {
1772 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1773 mdg->outEdges[srcNode->id];
1774 for (auto &outEdge : oldOutEdges) {
1775 if (outEdge.value == memref &&
1776 worklistSet.count(outEdge.id) == 0) {
1777 worklist.push_back(outEdge.id);
1778 worklistSet.insert(outEdge.id);
1779 }
1780 }
1781 }
MLIR Teamc4237ae2019-01-18 16:56:271782 }
MLIR Team3b692302018-12-17 17:57:141783 }
MLIR Team3b692302018-12-17 17:57:141784 }
1785 }
1786 }
MLIR Teamc4237ae2019-01-18 16:56:271787 // Clean up any allocs with no users.
1788 for (auto &pair : mdg->memrefEdgeCount) {
1789 if (pair.second > 0)
1790 continue;
1791 auto *memref = pair.first;
MLIR Team71495d52019-01-22 21:23:371792 // Skip if there exist other uses (return instruction or function calls).
1793 if (!memref->use_empty())
1794 continue;
MLIR Teamc4237ae2019-01-18 16:56:271795 // Use list expected to match the dep graph info.
MLIR Teamc4237ae2019-01-18 16:56:271796 auto *inst = memref->getDefiningInst();
River Riddleb4992772019-02-04 18:38:471797 if (inst && inst->isa<AllocOp>())
1798 inst->erase();
MLIR Teamc4237ae2019-01-18 16:56:271799 }
MLIR Teamf28e4df2018-11-01 14:26:001800 }
MLIR Team3b692302018-12-17 17:57:141801};
1802
1803} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001804
Chris Lattner79748892018-12-31 07:10:351805PassResult LoopFusion::runOnFunction(Function *f) {
Uday Bondhugulad4b3ff12019-02-27 00:10:191806 // Override if a command line argument was provided.
Uday Bondhugula8be26272019-02-02 01:06:221807 if (clFusionFastMemorySpace.getNumOccurrences() > 0) {
1808 fastMemorySpace = clFusionFastMemorySpace.getValue();
1809 }
1810
Uday Bondhugulad4b3ff12019-02-27 00:10:191811 // Override if a command line argument was provided.
1812 if (clFusionLocalBufThreshold.getNumOccurrences() > 0) {
1813 localBufSizeThreshold = clFusionLocalBufThreshold * 1024;
1814 }
1815
MLIR Team6892ffb2018-12-20 04:42:551816 MemRefDependenceGraph g;
1817 if (g.init(f))
Uday Bondhugula8be26272019-02-02 01:06:221818 GreedyFusion(&g).run(localBufSizeThreshold, fastMemorySpace);
MLIR Teamf28e4df2018-11-01 14:26:001819 return success();
1820}
Jacques Pienaar6f0fb222018-11-07 02:34:181821
1822static PassRegistration<LoopFusion> pass("loop-fusion", "Fuse loop nests");