blob: 5dbefb875da0a9d508975739e62007099c040683 [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"
MLIR Teamf28e4df2018-11-01 14:26:0024#include "mlir/Analysis/LoopAnalysis.h"
MLIR Team3b692302018-12-17 17:57:1425#include "mlir/Analysis/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0026#include "mlir/IR/AffineExpr.h"
27#include "mlir/IR/AffineMap.h"
River Riddle10237de2019-02-06 01:00:1328#include "mlir/IR/AffineStructures.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
70static llvm::cl::opt<unsigned> clFusionLocalBufThreshold(
71 "fusion-local-buf-threshold", llvm::cl::Hidden,
72 llvm::cl::desc("Threshold size (bytes) for promoting local buffers to fast "
73 "memory space"),
74 llvm::cl::cat(clOptionsCategory));
75
MLIR Teamf28e4df2018-11-01 14:26:0076namespace {
77
MLIR Team3b692302018-12-17 17:57:1478/// Loop fusion pass. This pass currently supports a greedy fusion policy,
79/// which fuses loop nests with single-writer/single-reader memref dependences
80/// with the goal of improving locality.
81
82// TODO(andydavis) Support fusion of source loop nests which write to multiple
83// memrefs, where each memref can have multiple users (if profitable).
MLIR Teamf28e4df2018-11-01 14:26:0084// TODO(andydavis) Extend this pass to check for fusion preventing dependences,
85// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1486
MLIR Teamf28e4df2018-11-01 14:26:0087struct LoopFusion : public FunctionPass {
Jacques Pienaarcc9a6ed2018-11-07 18:24:0388 LoopFusion() : FunctionPass(&LoopFusion::passID) {}
MLIR Teamf28e4df2018-11-01 14:26:0089
Chris Lattner79748892018-12-31 07:10:3590 PassResult runOnFunction(Function *f) override;
River Riddle3e656592019-02-22 02:01:0991 constexpr static PassID passID = {};
Uday Bondhugula864d9e02019-01-23 17:16:2492
Uday Bondhugula8be26272019-02-02 01:06:2293 // Any local buffers smaller than this size will be created in
94 // `fastMemorySpace` if provided.
95 unsigned localBufSizeThreshold = 1024;
96 Optional<unsigned> fastMemorySpace = None;
97
Uday Bondhugula864d9e02019-01-23 17:16:2498 // The amount of additional computation that is tolerated while fusing
99 // pair-wise as a fraction of the total computation.
100 constexpr static double kComputeToleranceThreshold = 0.30f;
MLIR Teamf28e4df2018-11-01 14:26:00101};
102
MLIR Teamf28e4df2018-11-01 14:26:00103} // end anonymous namespace
104
MLIR Teamf28e4df2018-11-01 14:26:00105FunctionPass *mlir::createLoopFusionPass() { return new LoopFusion; }
106
MLIR Team3b692302018-12-17 17:57:14107namespace {
MLIR Teamf28e4df2018-11-01 14:26:00108
MLIR Team3b692302018-12-17 17:57:14109// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:35110// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:44111struct LoopNestStateCollector {
River Riddle5052bd82019-02-02 00:42:18112 SmallVector<OpPointer<AffineForOp>, 4> forOps;
River Riddleb4992772019-02-04 18:38:47113 SmallVector<Instruction *, 4> loadOpInsts;
114 SmallVector<Instruction *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:53115 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:14116
River Riddlebf9c3812019-02-05 00:24:44117 void collect(Instruction *instToWalk) {
118 instToWalk->walk([&](Instruction *opInst) {
119 if (opInst->isa<AffineForOp>())
120 forOps.push_back(opInst->cast<AffineForOp>());
121 else if (opInst->getNumBlockLists() != 0)
122 hasNonForRegion = true;
123 else if (opInst->isa<LoadOp>())
124 loadOpInsts.push_back(opInst);
125 else if (opInst->isa<StoreOp>())
126 storeOpInsts.push_back(opInst);
127 });
MLIR Team3b692302018-12-17 17:57:14128 }
129};
130
MLIR Team71495d52019-01-22 21:23:37131// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
River Riddleb4992772019-02-04 18:38:47132static bool isMemRefDereferencingOp(const Instruction &op) {
MLIR Team71495d52019-01-22 21:23:37133 if (op.isa<LoadOp>() || op.isa<StoreOp>() || op.isa<DmaStartOp>() ||
134 op.isa<DmaWaitOp>())
135 return true;
136 return false;
137}
MLIR Team6892ffb2018-12-20 04:42:55138// MemRefDependenceGraph is a graph data structure where graph nodes are
Chris Lattner456ad6a2018-12-29 00:05:35139// top-level instructions in a Function which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55140// are memref dependences between the nodes.
MLIR Teamc4237ae2019-01-18 16:56:27141// TODO(andydavis) Add a more flexible dependece graph representation.
MLIR Team6892ffb2018-12-20 04:42:55142// TODO(andydavis) Add a depth parameter to dependence graph construction.
143struct MemRefDependenceGraph {
144public:
145 // Node represents a node in the graph. A Node is either an entire loop nest
146 // rooted at the top level which contains loads/stores, or a top level
147 // load/store.
148 struct Node {
149 // The unique identifier of this node in the graph.
150 unsigned id;
151 // The top-level statment which is (or contains) loads/stores.
Chris Lattner456ad6a2018-12-29 00:05:35152 Instruction *inst;
Chris Lattner5187cfc2018-12-28 05:21:41153 // List of load operations.
River Riddleb4992772019-02-04 18:38:47154 SmallVector<Instruction *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35155 // List of store op insts.
River Riddleb4992772019-02-04 18:38:47156 SmallVector<Instruction *, 4> stores;
Chris Lattner456ad6a2018-12-29 00:05:35157 Node(unsigned id, Instruction *inst) : id(id), inst(inst) {}
MLIR Team6892ffb2018-12-20 04:42:55158
159 // Returns the load op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10160 unsigned getLoadOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55161 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35162 for (auto *loadOpInst : loads) {
163 if (memref == loadOpInst->cast<LoadOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55164 ++loadOpCount;
165 }
166 return loadOpCount;
167 }
168
169 // Returns the store op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10170 unsigned getStoreOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55171 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35172 for (auto *storeOpInst : stores) {
173 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55174 ++storeOpCount;
175 }
176 return storeOpCount;
177 }
MLIR Team58aa3832019-02-16 01:12:19178
179 // Returns all store ups in 'storeOps' which access 'memref'.
180 void getStoreOpsForMemref(Value *memref,
181 SmallVectorImpl<Instruction *> *storeOps) {
182 for (auto *storeOpInst : stores) {
183 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
184 storeOps->push_back(storeOpInst);
185 }
186 }
MLIR Team6892ffb2018-12-20 04:42:55187 };
188
MLIR Teama0f3db402019-01-29 17:36:41189 // Edge represents a data dependece between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55190 struct Edge {
191 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46192 // If this edge is stored in Edge = Node.inEdges[i], then
193 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
194 // If this edge is stored in Edge = Node.outEdges[i], then
195 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55196 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41197 // The SSA value on which this edge represents a dependence.
198 // If the value is a memref, then the dependence is between graph nodes
199 // which contain accesses to the same memref 'value'. If the value is a
200 // non-memref value, then the dependence is between a graph node which
201 // defines an SSA value and another graph node which uses the SSA value
202 // (e.g. a constant instruction defining a value which is used inside a loop
203 // nest).
204 Value *value;
MLIR Team6892ffb2018-12-20 04:42:55205 };
206
207 // Map from node id to Node.
208 DenseMap<unsigned, Node> nodes;
209 // Map from node id to list of input edges.
210 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
211 // Map from node id to list of output edges.
212 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27213 // Map from memref to a count on the dependence edges associated with that
214 // memref.
215 DenseMap<Value *, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41216 // The next unique identifier to use for newly created graph nodes.
217 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55218
219 MemRefDependenceGraph() {}
220
221 // Initializes the dependence graph based on operations in 'f'.
222 // Returns true on success, false otherwise.
Chris Lattner69d9e992018-12-28 16:48:09223 bool init(Function *f);
MLIR Team6892ffb2018-12-20 04:42:55224
225 // Returns the graph node for 'id'.
226 Node *getNode(unsigned id) {
227 auto it = nodes.find(id);
228 assert(it != nodes.end());
229 return &it->second;
230 }
231
MLIR Teama0f3db402019-01-29 17:36:41232 // Adds a node with 'inst' to the graph and returns its unique identifier.
233 unsigned addNode(Instruction *inst) {
234 Node node(nextNodeId++, inst);
235 nodes.insert({node.id, node});
236 return node.id;
237 }
238
MLIR Teamc4237ae2019-01-18 16:56:27239 // Remove node 'id' (and its associated edges) from graph.
240 void removeNode(unsigned id) {
241 // Remove each edge in 'inEdges[id]'.
242 if (inEdges.count(id) > 0) {
243 SmallVector<Edge, 2> oldInEdges = inEdges[id];
244 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41245 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27246 }
247 }
248 // Remove each edge in 'outEdges[id]'.
249 if (outEdges.count(id) > 0) {
250 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
251 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41252 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27253 }
254 }
255 // Erase remaining node state.
256 inEdges.erase(id);
257 outEdges.erase(id);
258 nodes.erase(id);
259 }
260
MLIR Teamd7c82442019-01-30 23:53:41261 // Returns true if node 'id' writes to any memref which escapes (or is an
262 // argument to) the function/block. Returns false otherwise.
263 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37264 Node *node = getNode(id);
265 for (auto *storeOpInst : node->stores) {
266 auto *memref = storeOpInst->cast<StoreOp>()->getMemRef();
267 auto *inst = memref->getDefiningInst();
MLIR Team58aa3832019-02-16 01:12:19268 // Return true if 'memref' is a block argument.
River Riddleb4992772019-02-04 18:38:47269 if (!inst)
MLIR Teamd7c82442019-01-30 23:53:41270 return true;
MLIR Team58aa3832019-02-16 01:12:19271 // Return true if any use of 'memref' escapes the function.
River Riddleb4992772019-02-04 18:38:47272 for (auto &use : memref->getUses())
273 if (!isMemRefDereferencingOp(*use.getOwner()))
MLIR Teamd7c82442019-01-30 23:53:41274 return true;
MLIR Teamd7c82442019-01-30 23:53:41275 }
276 return false;
277 }
278
279 // Returns true if node 'id' can be removed from the graph. Returns false
280 // otherwise. A node can be removed from the graph iff the following
281 // conditions are met:
282 // *) The node does not write to any memref which escapes (or is a
283 // function/block argument).
284 // *) The node has no successors in the dependence graph.
285 bool canRemoveNode(unsigned id) {
286 if (writesToLiveInOrEscapingMemrefs(id))
287 return false;
288 Node *node = getNode(id);
289 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41290 // Return false if there exist out edges from 'id' on 'memref'.
MLIR Teamd7c82442019-01-30 23:53:41291 if (getOutEdgeCount(id, storeOpInst->cast<StoreOp>()->getMemRef()) > 0)
MLIR Teama0f3db402019-01-29 17:36:41292 return false;
MLIR Team71495d52019-01-22 21:23:37293 }
MLIR Teama0f3db402019-01-29 17:36:41294 return true;
MLIR Team71495d52019-01-22 21:23:37295 }
296
MLIR Team27d067e2019-01-16 17:55:02297 // Returns true iff there is an edge from node 'srcId' to node 'dstId' for
MLIR Teama0f3db402019-01-29 17:36:41298 // 'value'. Returns false otherwise.
299 bool hasEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team27d067e2019-01-16 17:55:02300 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
301 return false;
302 }
303 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41304 return edge.id == dstId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02305 });
306 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41307 return edge.id == srcId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02308 });
309 return hasOutEdge && hasInEdge;
310 }
311
MLIR Teama0f3db402019-01-29 17:36:41312 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
313 void addEdge(unsigned srcId, unsigned dstId, Value *value) {
314 if (!hasEdge(srcId, dstId, value)) {
315 outEdges[srcId].push_back({dstId, value});
316 inEdges[dstId].push_back({srcId, value});
317 if (value->getType().isa<MemRefType>())
318 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02319 }
MLIR Team6892ffb2018-12-20 04:42:55320 }
321
MLIR Teama0f3db402019-01-29 17:36:41322 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
323 void removeEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team6892ffb2018-12-20 04:42:55324 assert(inEdges.count(dstId) > 0);
325 assert(outEdges.count(srcId) > 0);
MLIR Teama0f3db402019-01-29 17:36:41326 if (value->getType().isa<MemRefType>()) {
327 assert(memrefEdgeCount.count(value) > 0);
328 memrefEdgeCount[value]--;
329 }
MLIR Team6892ffb2018-12-20 04:42:55330 // Remove 'srcId' from 'inEdges[dstId]'.
331 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41332 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55333 inEdges[dstId].erase(it);
334 break;
335 }
336 }
337 // Remove 'dstId' from 'outEdges[srcId]'.
338 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41339 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55340 outEdges[srcId].erase(it);
341 break;
342 }
343 }
344 }
345
MLIR Teama0f3db402019-01-29 17:36:41346 // Returns the input edge count for node 'id' and 'memref' from src nodes
347 // which access 'memref'.
348 unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55349 unsigned inEdgeCount = 0;
350 if (inEdges.count(id) > 0)
351 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41352 if (inEdge.value == memref) {
353 Node *srcNode = getNode(inEdge.id);
354 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
355 if (srcNode->getLoadOpCount(memref) > 0 ||
356 srcNode->getStoreOpCount(memref) > 0)
357 ++inEdgeCount;
358 }
MLIR Team6892ffb2018-12-20 04:42:55359 return inEdgeCount;
360 }
361
362 // Returns the output edge count for node 'id' and 'memref'.
Chris Lattner3f190312018-12-27 22:35:10363 unsigned getOutEdgeCount(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55364 unsigned outEdgeCount = 0;
365 if (outEdges.count(id) > 0)
366 for (auto &outEdge : outEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41367 if (outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55368 ++outEdgeCount;
369 return outEdgeCount;
370 }
371
MLIR Teama0f3db402019-01-29 17:36:41372 // Computes and returns an insertion point instruction, before which the
373 // the fused <srcId, dstId> loop nest can be inserted while preserving
374 // dependences. Returns nullptr if no such insertion point is found.
MLIR Teama78edcd2019-02-05 14:57:08375 Instruction *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40376 if (outEdges.count(srcId) == 0)
MLIR Teama0f3db402019-01-29 17:36:41377 return getNode(dstId)->inst;
378
379 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
380 SmallPtrSet<Instruction *, 2> srcDepInsts;
381 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08382 if (outEdge.id != dstId)
MLIR Teama0f3db402019-01-29 17:36:41383 srcDepInsts.insert(getNode(outEdge.id)->inst);
384
385 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
386 SmallPtrSet<Instruction *, 2> dstDepInsts;
387 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08388 if (inEdge.id != srcId)
MLIR Teama0f3db402019-01-29 17:36:41389 dstDepInsts.insert(getNode(inEdge.id)->inst);
390
391 Instruction *srcNodeInst = getNode(srcId)->inst;
392 Instruction *dstNodeInst = getNode(dstId)->inst;
393
394 // Computing insertion point:
395 // *) Walk all instruction positions in Block instruction list in the
396 // range (src, dst). For each instruction 'inst' visited in this search:
397 // *) Store in 'firstSrcDepPos' the first position where 'inst' has a
398 // dependence edge from 'srcNode'.
399 // *) Store in 'lastDstDepPost' the last position where 'inst' has a
400 // dependence edge to 'dstNode'.
401 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
402 // instruction insertion point (or return null pointer if no such
403 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
404 SmallVector<Instruction *, 2> depInsts;
405 Optional<unsigned> firstSrcDepPos;
406 Optional<unsigned> lastDstDepPos;
407 unsigned pos = 0;
408 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
409 it != Block::iterator(dstNodeInst); ++it) {
410 Instruction *inst = &(*it);
411 if (srcDepInsts.count(inst) > 0 && firstSrcDepPos == None)
412 firstSrcDepPos = pos;
413 if (dstDepInsts.count(inst) > 0)
414 lastDstDepPos = pos;
415 depInsts.push_back(inst);
416 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40417 }
MLIR Teama0f3db402019-01-29 17:36:41418
419 if (firstSrcDepPos.hasValue()) {
420 if (lastDstDepPos.hasValue()) {
421 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
422 // No valid insertion point exists which preserves dependences.
423 return nullptr;
424 }
425 }
426 // Return the insertion point at 'firstSrcDepPos'.
427 return depInsts[firstSrcDepPos.getValue()];
428 }
429 // No dependence targets in range (or only dst deps in range), return
430 // 'dstNodInst' insertion point.
431 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55432 }
433
MLIR Teama0f3db402019-01-29 17:36:41434 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
435 // has been replaced in node at 'dstId' by a private memref.
436 void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef) {
MLIR Team6892ffb2018-12-20 04:42:55437 // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'.
438 if (inEdges.count(srcId) > 0) {
439 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
440 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41441 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
442 if (inEdge.value != oldMemRef)
443 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55444 }
445 }
MLIR Teamc4237ae2019-01-18 16:56:27446 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55447 if (outEdges.count(srcId) > 0) {
448 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
449 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27450 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
451 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41452 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55453 }
454 }
MLIR Teama0f3db402019-01-29 17:36:41455 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
456 // replaced by a private memref). These edges could come from nodes
457 // other than 'srcId' which were removed in the previous step.
458 if (inEdges.count(dstId) > 0) {
459 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
460 for (auto &inEdge : oldInEdges)
461 if (inEdge.value == oldMemRef)
462 removeEdge(inEdge.id, dstId, inEdge.value);
463 }
MLIR Team6892ffb2018-12-20 04:42:55464 }
465
466 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddleb4992772019-02-04 18:38:47467 void addToNode(unsigned id, const SmallVectorImpl<Instruction *> &loads,
468 const SmallVectorImpl<Instruction *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55469 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35470 for (auto *loadOpInst : loads)
471 node->loads.push_back(loadOpInst);
472 for (auto *storeOpInst : stores)
473 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55474 }
475
MLIR Teamc4237ae2019-01-18 16:56:27476 void clearNodeLoadAndStores(unsigned id) {
477 Node *node = getNode(id);
478 node->loads.clear();
479 node->stores.clear();
480 }
481
MLIR Team6892ffb2018-12-20 04:42:55482 void print(raw_ostream &os) const {
483 os << "\nMemRefDependenceGraph\n";
484 os << "\nNodes:\n";
485 for (auto &idAndNode : nodes) {
486 os << "Node: " << idAndNode.first << "\n";
487 auto it = inEdges.find(idAndNode.first);
488 if (it != inEdges.end()) {
489 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41490 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55491 }
492 it = outEdges.find(idAndNode.first);
493 if (it != outEdges.end()) {
494 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41495 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55496 }
497 }
498 }
499 void dump() const { print(llvm::errs()); }
500};
501
Chris Lattner456ad6a2018-12-29 00:05:35502// Intializes the data dependence graph by walking instructions in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55503// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39504// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55505// dependence graph at a different depth.
Chris Lattner69d9e992018-12-28 16:48:09506bool MemRefDependenceGraph::init(Function *f) {
Chris Lattner3f190312018-12-27 22:35:10507 DenseMap<Value *, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43508
509 // TODO: support multi-block functions.
510 if (f->getBlocks().size() != 1)
511 return false;
512
River Riddle5052bd82019-02-02 00:42:18513 DenseMap<Instruction *, unsigned> forToNodeMap;
Chris Lattnerdffc5892018-12-29 23:33:43514 for (auto &inst : f->front()) {
River Riddleb4992772019-02-04 18:38:47515 if (auto forOp = inst.dyn_cast<AffineForOp>()) {
River Riddle5052bd82019-02-02 00:42:18516 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55517 // all loads and store accesses it contains.
518 LoopNestStateCollector collector;
River Riddlebf9c3812019-02-05 00:24:44519 collector.collect(&inst);
Uday Bondhugula4ba8c912019-02-07 05:54:18520 // Return false if a non 'for' region was found (not currently supported).
River Riddle75553832019-01-29 05:23:53521 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55522 return false;
MLIR Teama0f3db402019-01-29 17:36:41523 Node node(nextNodeId++, &inst);
Chris Lattner456ad6a2018-12-29 00:05:35524 for (auto *opInst : collector.loadOpInsts) {
525 node.loads.push_back(opInst);
526 auto *memref = opInst->cast<LoadOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55527 memrefAccesses[memref].insert(node.id);
528 }
Chris Lattner456ad6a2018-12-29 00:05:35529 for (auto *opInst : collector.storeOpInsts) {
530 node.stores.push_back(opInst);
531 auto *memref = opInst->cast<StoreOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55532 memrefAccesses[memref].insert(node.id);
533 }
River Riddle5052bd82019-02-02 00:42:18534 forToNodeMap[&inst] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55535 nodes.insert({node.id, node});
River Riddleb4992772019-02-04 18:38:47536 } else if (auto loadOp = inst.dyn_cast<LoadOp>()) {
537 // Create graph node for top-level load op.
538 Node node(nextNodeId++, &inst);
539 node.loads.push_back(&inst);
540 auto *memref = inst.cast<LoadOp>()->getMemRef();
541 memrefAccesses[memref].insert(node.id);
542 nodes.insert({node.id, node});
543 } else if (auto storeOp = inst.dyn_cast<StoreOp>()) {
544 // Create graph node for top-level store op.
545 Node node(nextNodeId++, &inst);
546 node.stores.push_back(&inst);
547 auto *memref = inst.cast<StoreOp>()->getMemRef();
548 memrefAccesses[memref].insert(node.id);
549 nodes.insert({node.id, node});
550 } else if (inst.getNumBlockLists() != 0) {
551 // Return false if another region is found (not currently supported).
552 return false;
553 } else if (inst.getNumResults() > 0 && !inst.use_empty()) {
554 // Create graph node for top-level producer of SSA values, which
555 // could be used by loop nest nodes.
556 Node node(nextNodeId++, &inst);
557 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41558 }
559 }
560
561 // Add dependence edges between nodes which produce SSA values and their
562 // users.
563 for (auto &idAndNode : nodes) {
564 const Node &node = idAndNode.second;
565 if (!node.loads.empty() || !node.stores.empty())
566 continue;
River Riddleb4992772019-02-04 18:38:47567 auto *opInst = node.inst;
MLIR Teama0f3db402019-01-29 17:36:41568 for (auto *value : opInst->getResults()) {
569 for (auto &use : value->getUses()) {
River Riddle5052bd82019-02-02 00:42:18570 SmallVector<OpPointer<AffineForOp>, 4> loops;
River Riddleb4992772019-02-04 18:38:47571 getLoopIVs(*use.getOwner(), &loops);
MLIR Teama0f3db402019-01-29 17:36:41572 if (loops.empty())
573 continue;
River Riddle5052bd82019-02-02 00:42:18574 assert(forToNodeMap.count(loops[0]->getInstruction()) > 0);
575 unsigned userLoopNestId = forToNodeMap[loops[0]->getInstruction()];
MLIR Teama0f3db402019-01-29 17:36:41576 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55577 }
578 }
MLIR Team6892ffb2018-12-20 04:42:55579 }
580
581 // Walk memref access lists and add graph edges between dependent nodes.
582 for (auto &memrefAndList : memrefAccesses) {
583 unsigned n = memrefAndList.second.size();
584 for (unsigned i = 0; i < n; ++i) {
585 unsigned srcId = memrefAndList.second[i];
586 bool srcHasStore =
587 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
588 for (unsigned j = i + 1; j < n; ++j) {
589 unsigned dstId = memrefAndList.second[j];
590 bool dstHasStore =
591 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
592 if (srcHasStore || dstHasStore)
593 addEdge(srcId, dstId, memrefAndList.first);
594 }
595 }
596 }
597 return true;
598}
599
MLIR Team38c2fe32019-01-14 19:26:25600namespace {
601
602// LoopNestStats aggregates various per-loop statistics (eg. loop trip count
603// and operation count) for a loop nest up until the innermost loop body.
604struct LoopNestStats {
River Riddle5052bd82019-02-02 00:42:18605 // Map from AffineForOp to immediate child AffineForOps in its loop body.
606 DenseMap<Instruction *, SmallVector<OpPointer<AffineForOp>, 2>> loopMap;
607 // Map from AffineForOp to count of operations in its loop body.
608 DenseMap<Instruction *, uint64_t> opCountMap;
609 // Map from AffineForOp to its constant trip count.
610 DenseMap<Instruction *, uint64_t> tripCountMap;
MLIR Team38c2fe32019-01-14 19:26:25611};
612
613// LoopNestStatsCollector walks a single loop nest and gathers per-loop
614// trip count and operation count statistics and records them in 'stats'.
River Riddlebf9c3812019-02-05 00:24:44615struct LoopNestStatsCollector {
MLIR Team38c2fe32019-01-14 19:26:25616 LoopNestStats *stats;
617 bool hasLoopWithNonConstTripCount = false;
618
619 LoopNestStatsCollector(LoopNestStats *stats) : stats(stats) {}
620
River Riddlebf9c3812019-02-05 00:24:44621 void collect(Instruction *inst) {
622 inst->walk<AffineForOp>([&](OpPointer<AffineForOp> forOp) {
623 auto *forInst = forOp->getInstruction();
624 auto *parentInst = forOp->getInstruction()->getParentInst();
625 if (parentInst != nullptr) {
626 assert(parentInst->isa<AffineForOp>() && "Expected parent AffineForOp");
627 // Add mapping to 'forOp' from its parent AffineForOp.
628 stats->loopMap[parentInst].push_back(forOp);
629 }
River Riddle5052bd82019-02-02 00:42:18630
River Riddlebf9c3812019-02-05 00:24:44631 // Record the number of op instructions in the body of 'forOp'.
632 unsigned count = 0;
633 stats->opCountMap[forInst] = 0;
634 for (auto &inst : *forOp->getBody()) {
635 if (!(inst.isa<AffineForOp>() || inst.isa<AffineIfOp>()))
636 ++count;
637 }
638 stats->opCountMap[forInst] = count;
639 // Record trip count for 'forOp'. Set flag if trip count is not
640 // constant.
641 Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp);
642 if (!maybeConstTripCount.hasValue()) {
643 hasLoopWithNonConstTripCount = true;
644 return;
645 }
646 stats->tripCountMap[forInst] = maybeConstTripCount.getValue();
647 });
MLIR Team38c2fe32019-01-14 19:26:25648 }
649};
650
River Riddle5052bd82019-02-02 00:42:18651// Computes the total cost of the loop nest rooted at 'forOp'.
MLIR Team38c2fe32019-01-14 19:26:25652// Currently, the total cost is computed by counting the total operation
653// instance count (i.e. total number of operations in the loop bodyloop
654// operation count * loop trip count) for the entire loop nest.
655// If 'tripCountOverrideMap' is non-null, overrides the trip count for loops
656// specified in the map when computing the total op instance count.
657// NOTE: this is used to compute the cost of computation slices, which are
658// sliced along the iteration dimension, and thus reduce the trip count.
River Riddle5052bd82019-02-02 00:42:18659// If 'computeCostMap' is non-null, the total op count for forOps specified
MLIR Team38c2fe32019-01-14 19:26:25660// in the map is increased (not overridden) by adding the op count from the
661// map to the existing op count for the for loop. This is done before
662// multiplying by the loop's trip count, and is used to model the cost of
663// inserting a sliced loop nest of known cost into the loop's body.
664// NOTE: this is used to compute the cost of fusing a slice of some loop nest
665// within another loop.
Uday Bondhugula864d9e02019-01-23 17:16:24666static int64_t getComputeCost(
River Riddle5052bd82019-02-02 00:42:18667 Instruction *forInst, LoopNestStats *stats,
668 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountOverrideMap,
669 DenseMap<Instruction *, int64_t> *computeCostMap) {
670 // 'opCount' is the total number operations in one iteration of 'forOp' body
Uday Bondhugula864d9e02019-01-23 17:16:24671 int64_t opCount = stats->opCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25672 if (stats->loopMap.count(forInst) > 0) {
River Riddle5052bd82019-02-02 00:42:18673 for (auto childForOp : stats->loopMap[forInst]) {
674 opCount += getComputeCost(childForOp->getInstruction(), stats,
675 tripCountOverrideMap, computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:25676 }
677 }
678 // Add in additional op instances from slice (if specified in map).
679 if (computeCostMap != nullptr) {
680 auto it = computeCostMap->find(forInst);
681 if (it != computeCostMap->end()) {
682 opCount += it->second;
683 }
684 }
685 // Override trip count (if specified in map).
Uday Bondhugula864d9e02019-01-23 17:16:24686 int64_t tripCount = stats->tripCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25687 if (tripCountOverrideMap != nullptr) {
688 auto it = tripCountOverrideMap->find(forInst);
689 if (it != tripCountOverrideMap->end()) {
690 tripCount = it->second;
691 }
692 }
693 // Returns the total number of dynamic instances of operations in loop body.
694 return tripCount * opCount;
695}
696
697} // end anonymous namespace
698
MLIR Team27d067e2019-01-16 17:55:02699static Optional<uint64_t> getConstDifference(AffineMap lbMap, AffineMap ubMap) {
Uday Bondhugulac1ca23e2019-01-16 21:13:00700 assert(lbMap.getNumResults() == 1 && "expected single result bound map");
701 assert(ubMap.getNumResults() == 1 && "expected single result bound map");
MLIR Team27d067e2019-01-16 17:55:02702 assert(lbMap.getNumDims() == ubMap.getNumDims());
703 assert(lbMap.getNumSymbols() == ubMap.getNumSymbols());
704 // TODO(andydavis) Merge this code with 'mlir::getTripCountExpr'.
705 // ub_expr - lb_expr
706 AffineExpr lbExpr(lbMap.getResult(0));
707 AffineExpr ubExpr(ubMap.getResult(0));
708 auto loopSpanExpr = simplifyAffineExpr(ubExpr - lbExpr, lbMap.getNumDims(),
709 lbMap.getNumSymbols());
710 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
711 if (!cExpr)
712 return None;
713 return cExpr.getValue();
714}
715
River Riddle5052bd82019-02-02 00:42:18716// Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop
MLIR Team38c2fe32019-01-14 19:26:25717// nest surrounding 'srcAccess' utilizing slice loop bounds in 'sliceState'.
718// Returns true on success, false otherwise (if a non-constant trip count
719// was encountered).
720// TODO(andydavis) Make this work with non-unit step loops.
MLIR Team27d067e2019-01-16 17:55:02721static bool buildSliceTripCountMap(
River Riddleb4992772019-02-04 18:38:47722 Instruction *srcOpInst, ComputationSliceState *sliceState,
River Riddle5052bd82019-02-02 00:42:18723 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountMap) {
724 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:02725 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:25726 unsigned numSrcLoopIVs = srcLoopIVs.size();
River Riddle5052bd82019-02-02 00:42:18727 // Populate map from AffineForOp -> trip count
MLIR Team38c2fe32019-01-14 19:26:25728 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
729 AffineMap lbMap = sliceState->lbs[i];
730 AffineMap ubMap = sliceState->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17731 if (lbMap == AffineMap() || ubMap == AffineMap()) {
MLIR Team38c2fe32019-01-14 19:26:25732 // The iteration of src loop IV 'i' was not sliced. Use full loop bounds.
733 if (srcLoopIVs[i]->hasConstantLowerBound() &&
734 srcLoopIVs[i]->hasConstantUpperBound()) {
River Riddle5052bd82019-02-02 00:42:18735 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] =
MLIR Team38c2fe32019-01-14 19:26:25736 srcLoopIVs[i]->getConstantUpperBound() -
737 srcLoopIVs[i]->getConstantLowerBound();
738 continue;
739 }
740 return false;
741 }
MLIR Team27d067e2019-01-16 17:55:02742 Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap);
743 if (!tripCount.hasValue())
MLIR Team38c2fe32019-01-14 19:26:25744 return false;
River Riddle5052bd82019-02-02 00:42:18745 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] = tripCount.getValue();
MLIR Team38c2fe32019-01-14 19:26:25746 }
747 return true;
748}
749
MLIR Team27d067e2019-01-16 17:55:02750// Removes load operations from 'srcLoads' which operate on 'memref', and
751// adds them to 'dstLoads'.
752static void
753moveLoadsAccessingMemrefTo(Value *memref,
River Riddleb4992772019-02-04 18:38:47754 SmallVectorImpl<Instruction *> *srcLoads,
755 SmallVectorImpl<Instruction *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02756 dstLoads->clear();
River Riddleb4992772019-02-04 18:38:47757 SmallVector<Instruction *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02758 for (auto *load : *srcLoads) {
759 if (load->cast<LoadOp>()->getMemRef() == memref)
760 dstLoads->push_back(load);
761 else
762 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25763 }
MLIR Team27d067e2019-01-16 17:55:02764 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25765}
766
MLIR Team27d067e2019-01-16 17:55:02767// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddleb4992772019-02-04 18:38:47768static unsigned getInnermostCommonLoopDepth(ArrayRef<Instruction *> ops) {
MLIR Team27d067e2019-01-16 17:55:02769 unsigned numOps = ops.size();
770 assert(numOps > 0);
771
River Riddle5052bd82019-02-02 00:42:18772 std::vector<SmallVector<OpPointer<AffineForOp>, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02773 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
774 for (unsigned i = 0; i < numOps; ++i) {
775 getLoopIVs(*ops[i], &loops[i]);
776 loopDepthLimit =
777 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25778 }
MLIR Team27d067e2019-01-16 17:55:02779
780 unsigned loopDepth = 0;
781 for (unsigned d = 0; d < loopDepthLimit; ++d) {
782 unsigned i;
783 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18784 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02785 break;
MLIR Team27d067e2019-01-16 17:55:02786 }
787 if (i != numOps)
788 break;
789 ++loopDepth;
790 }
791 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25792}
793
MLIR Teamd7c82442019-01-30 23:53:41794// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
795// and 'storeOpInsts' are satisfied.
River Riddleb4992772019-02-04 18:38:47796static unsigned getMaxLoopDepth(ArrayRef<Instruction *> loadOpInsts,
797 ArrayRef<Instruction *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41798 // Merge loads and stores into the same array.
River Riddleb4992772019-02-04 18:38:47799 SmallVector<Instruction *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41800 ops.append(storeOpInsts.begin(), storeOpInsts.end());
801
802 // Compute the innermost common loop depth for loads and stores.
803 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
804
805 // Return common loop depth for loads if there are no store ops.
806 if (storeOpInsts.empty())
807 return loopDepth;
808
809 // Check dependences on all pairs of ops in 'ops' and store the minimum
810 // loop depth at which a dependence is satisfied.
811 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
812 auto *srcOpInst = ops[i];
813 MemRefAccess srcAccess(srcOpInst);
814 for (unsigned j = 0; j < e; ++j) {
815 auto *dstOpInst = ops[j];
816 MemRefAccess dstAccess(dstOpInst);
817
818 unsigned numCommonLoops =
819 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
820 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
821 FlatAffineConstraints dependenceConstraints;
822 // TODO(andydavis) Cache dependence analysis results, check cache here.
823 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
824 &dependenceConstraints,
825 /*dependenceComponents=*/nullptr)) {
826 // Store minimum loop depth and break because we want the min 'd' at
827 // which there is a dependence.
828 loopDepth = std::min(loopDepth, d - 1);
829 break;
830 }
831 }
832 }
833 }
834 return loopDepth;
835}
836
MLIR Team8f5f2c72019-02-15 17:32:18837// Compute loop interchange permutation:
838// *) Computes dependence components between all op pairs in 'ops' for loop
839// depths in range [1, 'maxLoopDepth'].
840// *) Classifies the outermost 'maxLoopDepth' loops surrounding 'ops' as either
841// parallel or sequential.
842// *) Computes the loop permutation which sinks sequential loops deeper into
843// the loop nest, while preserving the relative order between other loops.
844// *) Checks each dependence component against the permutation to see if the
845// desired loop interchange would violated dependences by making the a
846// dependence componenent lexicographically negative.
847// TODO(andydavis) Move this function to LoopUtils.
848static bool
849computeLoopInterchangePermutation(ArrayRef<Instruction *> ops,
850 unsigned maxLoopDepth,
851 SmallVectorImpl<unsigned> *loopPermMap) {
852 // Gather dependence components for dependences between all ops in 'ops'
853 // at loop depths in range [1, maxLoopDepth].
854 // TODO(andydavis) Refactor this loop into a LoopUtil utility function:
855 // mlir::getDependenceComponents().
856 // TODO(andydavis) Split this loop into two: first check all dependences,
857 // and construct dep vectors. Then, scan through them to detect the parallel
858 // ones.
859 std::vector<llvm::SmallVector<DependenceComponent, 2>> depCompsVec;
860 llvm::SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true);
861 unsigned numOps = ops.size();
862 for (unsigned d = 1; d <= maxLoopDepth; ++d) {
863 for (unsigned i = 0; i < numOps; ++i) {
864 auto *srcOpInst = ops[i];
865 MemRefAccess srcAccess(srcOpInst);
866 for (unsigned j = 0; j < numOps; ++j) {
867 auto *dstOpInst = ops[j];
868 MemRefAccess dstAccess(dstOpInst);
869
870 FlatAffineConstraints dependenceConstraints;
871 llvm::SmallVector<DependenceComponent, 2> depComps;
872 // TODO(andydavis,bondhugula) Explore whether it would be profitable
873 // to pre-compute and store deps instead of repeatidly checking.
874 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
875 &dependenceConstraints, &depComps)) {
876 isParallelLoop[d - 1] = false;
877 depCompsVec.push_back(depComps);
878 }
879 }
880 }
881 }
882 // Count the number of parallel loops.
883 unsigned numParallelLoops = 0;
884 for (unsigned i = 0, e = isParallelLoop.size(); i < e; ++i)
885 if (isParallelLoop[i])
886 ++numParallelLoops;
887
888 // Compute permutation of loops that sinks sequential loops (and thus raises
889 // parallel loops) while preserving relative order.
890 llvm::SmallVector<unsigned, 4> loopPermMapInv;
891 loopPermMapInv.resize(maxLoopDepth);
892 loopPermMap->resize(maxLoopDepth);
893 unsigned nextSequentialLoop = numParallelLoops;
894 unsigned nextParallelLoop = 0;
895 for (unsigned i = 0; i < maxLoopDepth; ++i) {
896 if (isParallelLoop[i]) {
897 (*loopPermMap)[i] = nextParallelLoop;
898 loopPermMapInv[nextParallelLoop++] = i;
899 } else {
900 (*loopPermMap)[i] = nextSequentialLoop;
901 loopPermMapInv[nextSequentialLoop++] = i;
902 }
903 }
904
905 // Check each dependence component against the permutation to see if the
906 // desired loop interchange permutation would make the dependence vectors
907 // lexicographically negative.
908 // Example 1: [-1, 1][0, 0]
909 // Example 2: [0, 0][-1, 1]
910 for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) {
911 llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i];
912 assert(depComps.size() >= maxLoopDepth);
913 // Check if the first non-zero dependence component is positive.
914 for (unsigned j = 0; j < maxLoopDepth; ++j) {
915 unsigned permIndex = loopPermMapInv[j];
916 assert(depComps[permIndex].lb.hasValue());
917 int64_t depCompLb = depComps[permIndex].lb.getValue();
918 if (depCompLb > 0)
919 break;
920 if (depCompLb < 0)
921 return false;
922 }
923 }
924 return true;
925}
926
927// Sinks all sequential loops to the innermost levels (while preserving
928// relative order among them) and moves all parallel loops to the
929// outermost (while again preserving relative order among them).
930// This can increase the loop depth at which we can fuse a slice, since we are
931// pushing loop carried dependence to a greater depth in the loop nest.
932static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
933 assert(node->inst->isa<AffineForOp>());
934 // Get perfectly nested sequence of loops starting at root of loop nest.
935 // TODO(andydavis,bondhugula) Share this with similar code in loop tiling.
936 SmallVector<OpPointer<AffineForOp>, 4> loops;
937 OpPointer<AffineForOp> curr = node->inst->cast<AffineForOp>();
938 loops.push_back(curr);
939 auto *currBody = curr->getBody();
940 while (!currBody->empty() &&
941 std::next(currBody->begin()) == currBody->end() &&
942 (curr = curr->getBody()->front().dyn_cast<AffineForOp>())) {
943 loops.push_back(curr);
944 currBody = curr->getBody();
945 }
946 if (loops.size() < 2)
947 return;
948
949 // Merge loads and stores into the same array.
950 SmallVector<Instruction *, 2> memOps(node->loads.begin(), node->loads.end());
951 memOps.append(node->stores.begin(), node->stores.end());
952
953 // Compute loop permutation in 'loopPermMap'.
954 llvm::SmallVector<unsigned, 4> loopPermMap;
955 if (!computeLoopInterchangePermutation(memOps, loops.size(), &loopPermMap))
956 return;
957
958 int loopNestRootIndex = -1;
959 for (int i = loops.size() - 1; i >= 0; --i) {
960 int permIndex = static_cast<int>(loopPermMap[i]);
961 // Store the index of the for loop which will be the new loop nest root.
962 if (permIndex == 0)
963 loopNestRootIndex = i;
964 if (permIndex > i) {
965 // Sink loop 'i' by 'permIndex - i' levels deeper into the loop nest.
966 sinkLoop(loops[i], permIndex - i);
967 }
968 }
969 assert(loopNestRootIndex != -1 && "invalid root index");
970 node->inst = loops[loopNestRootIndex]->getInstruction();
971}
972
Uday Bondhugulac1ca23e2019-01-16 21:13:00973// Returns the slice union of 'sliceStateA' and 'sliceStateB' in 'sliceStateB'
974// using a rectangular bounding box.
MLIR Team27d067e2019-01-16 17:55:02975// TODO(andydavis) This function assumes that lower bounds for 'sliceStateA'
976// and 'sliceStateB' are aligned.
977// Specifically, when taking the union of overlapping intervals, it assumes
978// that both intervals start at zero. Support needs to be added to take into
979// account interval start offset when computing the union.
980// TODO(andydavis) Move this function to an analysis library.
Uday Bondhugulac1ca23e2019-01-16 21:13:00981static bool getSliceUnion(const ComputationSliceState &sliceStateA,
982 ComputationSliceState *sliceStateB) {
MLIR Team27d067e2019-01-16 17:55:02983 assert(sliceStateA.lbs.size() == sliceStateB->lbs.size());
984 assert(sliceStateA.ubs.size() == sliceStateB->ubs.size());
985
986 for (unsigned i = 0, e = sliceStateA.lbs.size(); i < e; ++i) {
987 AffineMap lbMapA = sliceStateA.lbs[i];
988 AffineMap ubMapA = sliceStateA.ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17989 if (lbMapA == AffineMap()) {
990 assert(ubMapA == AffineMap());
MLIR Team27d067e2019-01-16 17:55:02991 continue;
992 }
Uday Bondhugulac1ca23e2019-01-16 21:13:00993 assert(ubMapA && "expected non-null ub map");
MLIR Team27d067e2019-01-16 17:55:02994
995 AffineMap lbMapB = sliceStateB->lbs[i];
996 AffineMap ubMapB = sliceStateB->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17997 if (lbMapB == AffineMap()) {
998 assert(ubMapB == AffineMap());
MLIR Team27d067e2019-01-16 17:55:02999 // Union 'sliceStateB' does not have a bound for 'i' so copy from A.
1000 sliceStateB->lbs[i] = lbMapA;
1001 sliceStateB->ubs[i] = ubMapA;
1002 continue;
1003 }
Uday Bondhugulac1ca23e2019-01-16 21:13:001004
1005 // TODO(andydavis) Change this code to take the min across all lower bounds
1006 // and max across all upper bounds for each dimension. This code can for
1007 // cases where a unique min or max could not be statically determined.
1008
1009 // Assumption: both lower bounds are the same.
1010 if (lbMapA != lbMapB)
MLIR Team27d067e2019-01-16 17:55:021011 return false;
1012
1013 // Add bound with the largest trip count to union.
1014 Optional<uint64_t> tripCountA = getConstDifference(lbMapA, ubMapA);
1015 Optional<uint64_t> tripCountB = getConstDifference(lbMapB, ubMapB);
1016 if (!tripCountA.hasValue() || !tripCountB.hasValue())
1017 return false;
Uday Bondhugulac1ca23e2019-01-16 21:13:001018
MLIR Team27d067e2019-01-16 17:55:021019 if (tripCountA.getValue() > tripCountB.getValue()) {
1020 sliceStateB->lbs[i] = lbMapA;
1021 sliceStateB->ubs[i] = ubMapA;
1022 }
1023 }
1024 return true;
1025}
1026
Uday Bondhugula8be26272019-02-02 01:06:221027// TODO(mlir-team): improve/complete this when we have target data.
1028unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
1029 auto elementType = memRefType.getElementType();
1030
1031 unsigned sizeInBits;
1032 if (elementType.isIntOrFloat()) {
1033 sizeInBits = elementType.getIntOrFloatBitWidth();
1034 } else {
1035 auto vectorType = elementType.cast<VectorType>();
1036 sizeInBits =
1037 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
1038 }
1039 return llvm::divideCeil(sizeInBits, 8);
1040}
1041
MLIR Teamc4237ae2019-01-18 16:56:271042// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:181043// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:521044// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1045// TODO(bondhugula): consider refactoring the common code from generateDma and
1046// this one.
River Riddle5052bd82019-02-02 00:42:181047static Value *createPrivateMemRef(OpPointer<AffineForOp> forOp,
River Riddleb4992772019-02-04 18:38:471048 Instruction *srcStoreOpInst,
Uday Bondhugula8be26272019-02-02 01:06:221049 unsigned dstLoopDepth,
1050 Optional<unsigned> fastMemorySpace,
1051 unsigned localBufSizeThreshold) {
River Riddle5052bd82019-02-02 00:42:181052 auto *forInst = forOp->getInstruction();
1053
1054 // Create builder to insert alloc op just before 'forOp'.
MLIR Teamc4237ae2019-01-18 16:56:271055 FuncBuilder b(forInst);
1056 // Builder to create constants at the top level.
1057 FuncBuilder top(forInst->getFunction());
1058 // Create new memref type based on slice bounds.
1059 auto *oldMemRef = srcStoreOpInst->cast<StoreOp>()->getMemRef();
1060 auto oldMemRefType = oldMemRef->getType().cast<MemRefType>();
1061 unsigned rank = oldMemRefType.getRank();
1062
Uday Bondhugula94a03f82019-01-22 21:58:521063 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:441064 MemRefRegion region(srcStoreOpInst->getLoc());
1065 region.compute(srcStoreOpInst, dstLoopDepth);
River Riddle6859f332019-01-23 22:39:451066 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:271067 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:521068 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:271069 lbs.reserve(rank);
1070 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:521071 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:271072 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:441073 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:221074 assert(numElements.hasValue() &&
1075 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:271076
Uday Bondhugula0f504142019-02-04 21:48:441077 const FlatAffineConstraints *cst = region.getConstraints();
Uday Bondhugula94a03f82019-01-22 21:58:521078 // 'outerIVs' holds the values that this memory region is symbolic/paramteric
1079 // on; this would correspond to loop IVs surrounding the level at which the
1080 // slice is being materialized.
1081 SmallVector<Value *, 8> outerIVs;
1082 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
1083
1084 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:271085 SmallVector<AffineExpr, 4> offsets;
1086 offsets.reserve(rank);
1087 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:521088 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
1089
MLIR Teamc4237ae2019-01-18 16:56:271090 AffineExpr offset = top.getAffineConstantExpr(0);
1091 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
1092 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
1093 }
Uday Bondhugula94a03f82019-01-22 21:58:521094 assert(lbDivisors[d] > 0);
1095 offset =
1096 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:271097 offsets.push_back(offset);
1098 }
1099
1100 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
1101 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:221102 uint64_t bufSize =
1103 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
1104 unsigned newMemSpace;
1105 if (bufSize < localBufSizeThreshold && fastMemorySpace.hasValue()) {
1106 newMemSpace = fastMemorySpace.getValue();
1107 } else {
1108 newMemSpace = oldMemRefType.getMemorySpace();
1109 }
1110 auto newMemRefType = top.getMemRefType(
1111 newShape, oldMemRefType.getElementType(), {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:271112 // Gather alloc operands for the dynamic dimensions of the memref.
1113 SmallVector<Value *, 4> allocOperands;
1114 unsigned dynamicDimCount = 0;
1115 for (auto dimSize : oldMemRefType.getShape()) {
1116 if (dimSize == -1)
1117 allocOperands.push_back(
River Riddle5052bd82019-02-02 00:42:181118 top.create<DimOp>(forOp->getLoc(), oldMemRef, dynamicDimCount++));
MLIR Teamc4237ae2019-01-18 16:56:271119 }
1120
River Riddle5052bd82019-02-02 00:42:181121 // Create new private memref for fused loop 'forOp'.
MLIR Teama0f3db402019-01-29 17:36:411122 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
1123 // consumer loop nests to reduce their live range. Currently they are added
1124 // at the beginning of the function, because loop nests can be reordered
1125 // during the fusion pass.
MLIR Teamc4237ae2019-01-18 16:56:271126 Value *newMemRef =
River Riddle5052bd82019-02-02 00:42:181127 top.create<AllocOp>(forOp->getLoc(), newMemRefType, allocOperands);
MLIR Teamc4237ae2019-01-18 16:56:271128
1129 // Build an AffineMap to remap access functions based on lower bound offsets.
1130 SmallVector<AffineExpr, 4> remapExprs;
1131 remapExprs.reserve(rank);
1132 unsigned zeroOffsetCount = 0;
1133 for (unsigned i = 0; i < rank; i++) {
1134 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
1135 if (constExpr.getValue() == 0)
1136 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:521137 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
1138
1139 auto remapExpr =
1140 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
1141 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:271142 }
Uday Bondhugula94a03f82019-01-22 21:58:521143 auto indexRemap =
1144 zeroOffsetCount == rank
Nicolas Vasilache0e7a8a92019-01-26 18:41:171145 ? AffineMap()
Uday Bondhugula94a03f82019-01-22 21:58:521146 : b.getAffineMap(outerIVs.size() + rank, 0, remapExprs, {});
MLIR Teamc4237ae2019-01-18 16:56:271147 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugula94a03f82019-01-22 21:58:521148 bool ret =
1149 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
1150 /*extraOperands=*/outerIVs,
River Riddle5052bd82019-02-02 00:42:181151 /*domInstFilter=*/&*forOp->getBody()->begin());
Uday Bondhugula94a03f82019-01-22 21:58:521152 assert(ret && "replaceAllMemrefUsesWith should always succeed here");
MLIR Team71495d52019-01-22 21:23:371153 (void)ret;
MLIR Teamc4237ae2019-01-18 16:56:271154 return newMemRef;
1155}
1156
Uday Bondhugula864d9e02019-01-23 17:16:241157// Does the slice have a single iteration?
1158static uint64_t getSliceIterationCount(
River Riddle5052bd82019-02-02 00:42:181159 const llvm::SmallDenseMap<Instruction *, uint64_t, 8> &sliceTripCountMap) {
Uday Bondhugula864d9e02019-01-23 17:16:241160 uint64_t iterCount = 1;
1161 for (const auto &count : sliceTripCountMap) {
1162 iterCount *= count.second;
1163 }
1164 return iterCount;
1165}
1166
MLIR Team58aa3832019-02-16 01:12:191167// Checks if node 'srcId' (which writes to a live out memref), can be safely
1168// fused into node 'dstId'. Returns true if the following conditions are met:
1169// *) 'srcNode' writes only writes to live out 'memref'.
1170// *) 'srcNode' has exaclty one output edge on 'memref' (which is to 'dstId').
1171// *) 'dstNode' does write to 'memref'.
1172// *) 'dstNode's write region to 'memref' is a super set of 'srcNode's write
1173// region to 'memref'.
1174// TODO(andydavis) Generalize this to handle more live in/out cases.
1175static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
1176 Value *memref,
1177 MemRefDependenceGraph *mdg) {
1178 auto *srcNode = mdg->getNode(srcId);
1179 auto *dstNode = mdg->getNode(dstId);
1180
1181 // Return false if any of the following are true:
1182 // *) 'srcNode' writes to a live in/out memref other than 'memref'.
1183 // *) 'srcNode' has more than one output edge on 'memref'.
1184 // *) 'dstNode' does not write to 'memref'.
1185 if (srcNode->getStoreOpCount(memref) != 1 ||
1186 mdg->getOutEdgeCount(srcNode->id, memref) != 1 ||
1187 dstNode->getStoreOpCount(memref) == 0)
1188 return false;
1189 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOpInst' on 'memref'.
1190 auto *srcStoreOpInst = srcNode->stores.front();
1191 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
1192 srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0);
1193 SmallVector<int64_t, 4> srcShape;
1194 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
1195 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1196 Optional<int64_t> srcNumElements =
1197 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1198 if (!srcNumElements.hasValue())
1199 return false;
1200
1201 // Compute MemRefRegion 'dstWriteRegion' for 'dstStoreOpInst' on 'memref'.
1202 SmallVector<Instruction *, 2> dstStoreOps;
1203 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1204 assert(dstStoreOps.size() == 1);
1205 auto *dstStoreOpInst = dstStoreOps[0];
1206 MemRefRegion dstWriteRegion(dstStoreOpInst->getLoc());
1207 dstWriteRegion.compute(dstStoreOpInst, /*loopDepth=*/0);
1208 SmallVector<int64_t, 4> dstShape;
1209 // Query 'dstWriteRegion' for 'dstShape' and 'dstNumElements'.
1210 // by 'dstStoreOpInst' at depth 'dstLoopDepth'.
1211 Optional<int64_t> dstNumElements =
1212 dstWriteRegion.getConstantBoundingSizeAndShape(&dstShape);
1213 if (!dstNumElements.hasValue())
1214 return false;
1215
1216 // Return false if write region is not a superset of 'srcNodes' write
1217 // region to 'memref'.
1218 // TODO(andydavis) Check the shape and lower bounds here too.
1219 if (srcNumElements != dstNumElements)
1220 return false;
1221 return true;
1222}
1223
MLIR Team27d067e2019-01-16 17:55:021224// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411225// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
Uday Bondhugulab4a14432019-01-26 00:00:501226// Returns true if it is profitable to fuse the candidate loop nests. Returns
1227// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1228// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251229// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021230// *) Computes the backward computation slice at 'srcOpInst'. This
1231// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251232// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021233// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251234// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1235// loop nest is the total number of dynamic operation instances in the loop
1236// nest).
1237// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021238// loop nest at various values of dst loop depth, attempting to fuse
1239// the largest compution slice at the maximal dst loop depth (closest to the
1240// load) to minimize reuse distance and potentially enable subsequent
1241// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411242// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021243// the same memref as is written by 'srcOpInst', then the union of slice
1244// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501245// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251246// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021247// NOTE: We attempt to maximize the dst loop depth, but there are cases
1248// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251249// loop (within the src computation slice) at a depth which results in
1250// execessive recomputation (see unit tests for examples).
1251// *) Compares the total cost of the unfused loop nests to the min cost fused
1252// loop nest computed in the previous step, and returns true if the latter
1253// is lower.
River Riddleb4992772019-02-04 18:38:471254static bool isFusionProfitable(Instruction *srcOpInst,
1255 ArrayRef<Instruction *> dstLoadOpInsts,
1256 ArrayRef<Instruction *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251257 ComputationSliceState *sliceState,
MLIR Team27d067e2019-01-16 17:55:021258 unsigned *dstLoopDepth) {
Uday Bondhugula06d21d92019-01-25 01:01:491259 LLVM_DEBUG({
1260 llvm::dbgs() << "Checking whether fusion is profitable between:\n";
Uday Bondhugulaa1dad3a2019-02-20 02:17:191261 llvm::dbgs() << " " << *srcOpInst << " and \n";
MLIR Teamd7c82442019-01-30 23:53:411262 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191263 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491264 };
1265 });
Uday Bondhugula864d9e02019-01-23 17:16:241266
MLIR Team38c2fe32019-01-14 19:26:251267 // Compute cost of sliced and unsliced src loop nest.
River Riddle5052bd82019-02-02 00:42:181268 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021269 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251270 unsigned numSrcLoopIVs = srcLoopIVs.size();
1271
1272 // Walk src loop nest and collect stats.
1273 LoopNestStats srcLoopNestStats;
1274 LoopNestStatsCollector srcStatsCollector(&srcLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441275 srcStatsCollector.collect(srcLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251276 // Currently only constant trip count loop nests are supported.
1277 if (srcStatsCollector.hasLoopWithNonConstTripCount)
1278 return false;
1279
1280 // Compute cost of dst loop nest.
River Riddle5052bd82019-02-02 00:42:181281 SmallVector<OpPointer<AffineForOp>, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411282 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251283
1284 LoopNestStats dstLoopNestStats;
1285 LoopNestStatsCollector dstStatsCollector(&dstLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441286 dstStatsCollector.collect(dstLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251287 // Currently only constant trip count loop nests are supported.
1288 if (dstStatsCollector.hasLoopWithNonConstTripCount)
1289 return false;
1290
MLIR Teamd7c82442019-01-30 23:53:411291 // Compute the maximum loop depth at which we can can insert the src slice
1292 // and still satisfy dest loop nest dependences.
1293 unsigned maxDstLoopDepth = getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts);
MLIR Team27d067e2019-01-16 17:55:021294 if (maxDstLoopDepth == 0)
1295 return false;
1296
1297 // Search for min cost value for 'dstLoopDepth'. At each value of
1298 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1299 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1300 // of these bounds). Next the union slice bounds are used to calculate
1301 // the cost of the slice and the cost of the slice inserted into the dst
1302 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241303 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
1304 uint64_t maxStorageReduction = 0;
1305 Optional<uint64_t> sliceMemEstimate = None;
1306
MLIR Team27d067e2019-01-16 17:55:021307 SmallVector<ComputationSliceState, 4> sliceStates;
1308 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241309 // The best loop depth at which to materialize the slice.
1310 Optional<unsigned> bestDstLoopDepth = None;
1311
1312 // Compute op instance count for the src loop nest without iteration slicing.
River Riddle5052bd82019-02-02 00:42:181313 uint64_t srcLoopNestCost =
1314 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
1315 /*tripCountOverrideMap=*/nullptr,
1316 /*computeCostMap=*/nullptr);
Uday Bondhugula864d9e02019-01-23 17:16:241317
MLIR Teamb9dde912019-02-06 19:01:101318 // Compute src loop nest write region size.
1319 MemRefRegion srcWriteRegion(srcOpInst->getLoc());
1320 srcWriteRegion.compute(srcOpInst, /*loopDepth=*/0);
1321 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1322 srcWriteRegion.getRegionSize();
1323 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1324 return false;
1325 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1326
Uday Bondhugula864d9e02019-01-23 17:16:241327 // Compute op instance count for the src loop nest.
River Riddle5052bd82019-02-02 00:42:181328 uint64_t dstLoopNestCost =
1329 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
1330 /*tripCountOverrideMap=*/nullptr,
1331 /*computeCostMap=*/nullptr);
MLIR Team27d067e2019-01-16 17:55:021332
MLIR Teamb9dde912019-02-06 19:01:101333 // Evaluate all depth choices for materializing the slice in the destination
1334 // loop nest.
River Riddle5052bd82019-02-02 00:42:181335 llvm::SmallDenseMap<Instruction *, uint64_t, 8> sliceTripCountMap;
1336 DenseMap<Instruction *, int64_t> computeCostMap;
MLIR Team27d067e2019-01-16 17:55:021337 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
1338 MemRefAccess srcAccess(srcOpInst);
1339 // Handle the common case of one dst load without a copy.
1340 if (!mlir::getBackwardComputationSliceState(
MLIR Teamd7c82442019-01-30 23:53:411341 srcAccess, MemRefAccess(dstLoadOpInsts[0]), i, &sliceStates[i - 1]))
MLIR Team27d067e2019-01-16 17:55:021342 return false;
MLIR Teamd7c82442019-01-30 23:53:411343 // Compute the union of slice bound of all ops in 'dstLoadOpInsts'.
1344 for (int j = 1, e = dstLoadOpInsts.size(); j < e; ++j) {
1345 MemRefAccess dstAccess(dstLoadOpInsts[j]);
MLIR Team27d067e2019-01-16 17:55:021346 ComputationSliceState tmpSliceState;
1347 if (!mlir::getBackwardComputationSliceState(srcAccess, dstAccess, i,
1348 &tmpSliceState))
1349 return false;
1350 // Compute slice boun dunion of 'tmpSliceState' and 'sliceStates[i - 1]'.
Uday Bondhugulac1ca23e2019-01-16 21:13:001351 getSliceUnion(tmpSliceState, &sliceStates[i - 1]);
MLIR Team38c2fe32019-01-14 19:26:251352 }
Uday Bondhugulab4a14432019-01-26 00:00:501353 // Build trip count map for computation slice. We'll skip cases where the
1354 // trip count was non-constant.
MLIR Team27d067e2019-01-16 17:55:021355 sliceTripCountMap.clear();
1356 if (!buildSliceTripCountMap(srcOpInst, &sliceStates[i - 1],
1357 &sliceTripCountMap))
Uday Bondhugula864d9e02019-01-23 17:16:241358 continue;
1359
1360 // Checks whether a store to load forwarding will happen.
1361 int64_t sliceIterationCount = getSliceIterationCount(sliceTripCountMap);
Uday Bondhugula864d9e02019-01-23 17:16:241362 assert(sliceIterationCount > 0);
Uday Bondhugulab4a14432019-01-26 00:00:501363 bool storeLoadFwdGuaranteed = (sliceIterationCount == 1);
Uday Bondhugula864d9e02019-01-23 17:16:241364
1365 // Compute cost of fusion for this dest loop depth.
1366
1367 computeCostMap.clear();
1368
1369 // The store and loads to this memref will disappear.
1370 if (storeLoadFwdGuaranteed) {
1371 // A single store disappears: -1 for that.
River Riddle5052bd82019-02-02 00:42:181372 computeCostMap[srcLoopIVs[numSrcLoopIVs - 1]->getInstruction()] = -1;
MLIR Teamd7c82442019-01-30 23:53:411373 for (auto *loadOp : dstLoadOpInsts) {
River Riddle5052bd82019-02-02 00:42:181374 auto *parentInst = loadOp->getParentInst();
River Riddleb4992772019-02-04 18:38:471375 if (parentInst && parentInst->isa<AffineForOp>())
River Riddle5052bd82019-02-02 00:42:181376 computeCostMap[parentInst] = -1;
Uday Bondhugula864d9e02019-01-23 17:16:241377 }
1378 }
MLIR Team27d067e2019-01-16 17:55:021379
MLIR Team38c2fe32019-01-14 19:26:251380 // Compute op instance count for the src loop nest with iteration slicing.
Uday Bondhugula864d9e02019-01-23 17:16:241381 int64_t sliceComputeCost =
River Riddle5052bd82019-02-02 00:42:181382 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
Uday Bondhugula864d9e02019-01-23 17:16:241383 /*tripCountOverrideMap=*/&sliceTripCountMap,
1384 /*computeCostMap=*/&computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:251385
Uday Bondhugula864d9e02019-01-23 17:16:241386 // Compute cost of fusion for this depth.
River Riddle5052bd82019-02-02 00:42:181387 computeCostMap[dstLoopIVs[i - 1]->getInstruction()] = sliceComputeCost;
Uday Bondhugula864d9e02019-01-23 17:16:241388
1389 int64_t fusedLoopNestComputeCost =
River Riddle5052bd82019-02-02 00:42:181390 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
MLIR Team27d067e2019-01-16 17:55:021391 /*tripCountOverrideMap=*/nullptr, &computeCostMap);
Uday Bondhugula864d9e02019-01-23 17:16:241392
1393 double additionalComputeFraction =
1394 fusedLoopNestComputeCost /
1395 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1396 1;
1397
MLIR Teamb9dde912019-02-06 19:01:101398 // Compute what the slice write MemRefRegion would be, if the src loop
1399 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1400 // nest at loop depth 'i'
1401 MemRefRegion sliceWriteRegion(srcOpInst->getLoc());
1402 sliceWriteRegion.compute(srcOpInst, /*loopDepth=*/0, &sliceStates[i - 1]);
1403 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1404 sliceWriteRegion.getRegionSize();
1405 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
1406 maybeSliceWriteRegionSizeBytes.getValue() == 0)
1407 continue;
1408 int64_t sliceWriteRegionSizeBytes =
1409 maybeSliceWriteRegionSizeBytes.getValue();
1410
1411 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1412 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241413
Uday Bondhugula06d21d92019-01-25 01:01:491414 LLVM_DEBUG({
1415 std::stringstream msg;
1416 msg << " evaluating fusion profitability at depth : " << i << "\n"
1417 << std::setprecision(2) << " additional compute fraction: "
1418 << 100.0 * additionalComputeFraction << "%\n"
1419 << " storage reduction factor: " << storageReduction << "x\n"
1420 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191421 << " slice iteration count: " << sliceIterationCount << "\n"
1422 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1423 << " slice write region size: " << sliceWriteRegionSizeBytes
1424 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491425 llvm::dbgs() << msg.str();
1426 });
Uday Bondhugula864d9e02019-01-23 17:16:241427
1428 double computeToleranceThreshold =
1429 clFusionAddlComputeTolerance.getNumOccurrences() > 0
1430 ? clFusionAddlComputeTolerance
1431 : LoopFusion::kComputeToleranceThreshold;
1432
1433 // TODO(b/123247369): This is a placeholder cost model.
1434 // Among all choices that add an acceptable amount of redundant computation
1435 // (as per computeToleranceThreshold), we will simply pick the one that
1436 // reduces the intermediary size the most.
1437 if ((storageReduction > maxStorageReduction) &&
1438 (clMaximalLoopFusion ||
1439 (additionalComputeFraction < computeToleranceThreshold))) {
1440 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021441 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241442 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101443 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251444 }
1445 }
1446
Uday Bondhugula864d9e02019-01-23 17:16:241447 // A simple cost model: fuse if it reduces the memory footprint. If
1448 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251449
Uday Bondhugula864d9e02019-01-23 17:16:241450 if (!clMaximalLoopFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191451 LLVM_DEBUG(
1452 llvm::dbgs()
1453 << "All fusion choices involve more than the threshold amount of "
1454 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251455 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241456 }
1457
1458 assert(bestDstLoopDepth.hasValue() &&
1459 "expected to have a value per logic above");
1460
1461 // Set dstLoopDepth based on best values from search.
1462 *dstLoopDepth = bestDstLoopDepth.getValue();
1463
1464 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491465 llvm::dbgs() << " LoopFusion fusion stats:"
1466 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241467 << "\n src loop nest compute cost: " << srcLoopNestCost
1468 << "\n dst loop nest compute cost: " << dstLoopNestCost
1469 << "\n fused loop nest compute cost: "
1470 << minFusedLoopNestComputeCost << "\n");
1471
River Riddle5052bd82019-02-02 00:42:181472 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1473 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241474
1475 Optional<double> storageReduction = None;
1476
1477 if (!clMaximalLoopFusion) {
1478 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1479 LLVM_DEBUG(
1480 llvm::dbgs()
1481 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1482 return false;
1483 }
1484
1485 auto srcMemSizeVal = srcMemSize.getValue();
1486 auto dstMemSizeVal = dstMemSize.getValue();
1487
1488 assert(sliceMemEstimate.hasValue() && "expected value");
1489 // This is an inaccurate estimate since sliceMemEstimate is isaccurate.
1490 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1491
1492 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1493 << " dst mem: " << dstMemSizeVal << "\n"
1494 << " fused mem: " << fusedMem << "\n"
1495 << " slice mem: " << sliceMemEstimate << "\n");
1496
1497 if (fusedMem > srcMemSizeVal + dstMemSizeVal) {
1498 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1499 return false;
1500 }
1501 storageReduction =
1502 100.0 *
1503 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1504 }
1505
1506 double additionalComputeFraction =
1507 100.0 * (minFusedLoopNestComputeCost /
1508 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1509 1);
MLIR Team5c5739d2019-01-25 06:27:401510 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491511 LLVM_DEBUG({
1512 std::stringstream msg;
1513 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591514 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491515 << "% redundant computation and a ";
1516 msg << (storageReduction.hasValue()
1517 ? std::to_string(storageReduction.getValue())
1518 : "<unknown>");
1519 msg << "% storage reduction.\n";
1520 llvm::dbgs() << msg.str();
1521 });
Uday Bondhugula864d9e02019-01-23 17:16:241522
MLIR Team27d067e2019-01-16 17:55:021523 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241524 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021525 sliceState->lbs = bestSliceState->lbs;
1526 sliceState->ubs = bestSliceState->ubs;
1527 sliceState->lbOperands = bestSliceState->lbOperands;
1528 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241529
MLIR Team27d067e2019-01-16 17:55:021530 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251531 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171532 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021533 canonicalizeMapAndOperands(&sliceState->lbs[i],
1534 &sliceState->lbOperands[i]);
1535 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171536 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021537 canonicalizeMapAndOperands(&sliceState->ubs[i],
1538 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251539 }
1540 }
1541 return true;
1542}
1543
MLIR Team6892ffb2018-12-20 04:42:551544// GreedyFusion greedily fuses loop nests which have a producer/consumer
MLIR Team3b692302018-12-17 17:57:141545// relationship on a memref, with the goal of improving locality. Currently,
1546// this the producer/consumer relationship is required to be unique in the
Chris Lattner69d9e992018-12-28 16:48:091547// Function (there are TODOs to relax this constraint in the future).
MLIR Teamf28e4df2018-11-01 14:26:001548//
MLIR Team3b692302018-12-17 17:57:141549// The steps of the algorithm are as follows:
1550//
MLIR Team6892ffb2018-12-20 04:42:551551// *) A worklist is initialized with node ids from the dependence graph.
1552// *) For each node id in the worklist:
River Riddle5052bd82019-02-02 00:42:181553// *) Pop a AffineForOp of the worklist. This 'dstAffineForOp' will be a
1554// candidate destination AffineForOp into which fusion will be attempted.
1555// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141556// *) For each LoadOp in 'dstLoadOps' do:
Chris Lattner69d9e992018-12-28 16:48:091557// *) Lookup dependent loop nests at earlier positions in the Function
MLIR Team3b692302018-12-17 17:57:141558// which have a single store op to the same memref.
1559// *) Check if dependences would be violated by the fusion. For example,
1560// the src loop nest may load from memrefs which are different than
1561// the producer-consumer memref between src and dest loop nests.
MLIR Team6892ffb2018-12-20 04:42:551562// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141563// bounds to be functions of 'dstLoopNest' IVs and symbols.
1564// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
1565// just before the dst load op user.
Chris Lattner456ad6a2018-12-29 00:05:351566// *) Add the newly fused load/store operation instructions to the state,
MLIR Team3b692302018-12-17 17:57:141567// and also add newly fuse load ops to 'dstLoopOps' to be considered
1568// as fusion dst load ops in another iteration.
1569// *) Remove old src loop nest and its associated state.
1570//
Chris Lattner456ad6a2018-12-29 00:05:351571// Given a graph where top-level instructions are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141572// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551573// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141574//
MLIR Team6892ffb2018-12-20 04:42:551575// This greedy algorithm is not 'maximal' due to the current restriction of
1576// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141577//
1578// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551579// TODO(andydavis) Add support for fusing for input reuse (perhaps by
1580// constructing a graph with edges which represent loads from the same memref
MLIR Team5c5739d2019-01-25 06:27:401581// in two different loop nests.
MLIR Team6892ffb2018-12-20 04:42:551582struct GreedyFusion {
1583public:
1584 MemRefDependenceGraph *mdg;
MLIR Teama78edcd2019-02-05 14:57:081585 SmallVector<unsigned, 8> worklist;
1586 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamf28e4df2018-11-01 14:26:001587
MLIR Team6892ffb2018-12-20 04:42:551588 GreedyFusion(MemRefDependenceGraph *mdg) : mdg(mdg) {
1589 // Initialize worklist with nodes from 'mdg'.
MLIR Teama78edcd2019-02-05 14:57:081590 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1591 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Team6892ffb2018-12-20 04:42:551592 worklist.resize(mdg->nodes.size());
1593 std::iota(worklist.begin(), worklist.end(), 0);
MLIR Teama78edcd2019-02-05 14:57:081594 worklistSet.insert(worklist.begin(), worklist.end());
MLIR Team6892ffb2018-12-20 04:42:551595 }
MLIR Team3b692302018-12-17 17:57:141596
Uday Bondhugula8be26272019-02-02 01:06:221597 void run(unsigned localBufSizeThreshold, Optional<unsigned> fastMemorySpace) {
MLIR Team3b692302018-12-17 17:57:141598 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551599 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141600 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081601 worklistSet.erase(dstId);
1602
MLIR Team6892ffb2018-12-20 04:42:551603 // Skip if this node was removed (fused into another node).
1604 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141605 continue;
MLIR Team6892ffb2018-12-20 04:42:551606 // Get 'dstNode' into which to attempt fusion.
1607 auto *dstNode = mdg->getNode(dstId);
1608 // Skip if 'dstNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471609 if (!dstNode->inst->isa<AffineForOp>())
MLIR Team3b692302018-12-17 17:57:141610 continue;
MLIR Team8f5f2c72019-02-15 17:32:181611 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1612 // while preserving relative order. This can increase the maximum loop
1613 // depth at which we can fuse a slice of a producer loop nest into a
1614 // consumer loop nest.
1615 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141616
River Riddleb4992772019-02-04 18:38:471617 SmallVector<Instruction *, 4> loads = dstNode->loads;
1618 SmallVector<Instruction *, 4> dstLoadOpInsts;
MLIR Teamc4237ae2019-01-18 16:56:271619 DenseSet<Value *> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551620 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021621 // Get memref of load on top of the stack.
1622 auto *memref = loads.back()->cast<LoadOp>()->getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271623 if (visitedMemrefs.count(memref) > 0)
1624 continue;
1625 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021626 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1627 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551628 // Skip if no input edges along which to fuse.
1629 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141630 continue;
MLIR Team1e851912019-01-31 00:01:461631 // Iterate through in edges for 'dstId' and src node id for any
1632 // edges on 'memref'.
1633 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551634 for (auto &srcEdge : mdg->inEdges[dstId]) {
1635 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411636 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551637 continue;
MLIR Team1e851912019-01-31 00:01:461638 srcNodeIds.push_back(srcEdge.id);
1639 }
1640 for (unsigned srcId : srcNodeIds) {
1641 // Skip if this node was removed (fused into another node).
1642 if (mdg->nodes.count(srcId) == 0)
1643 continue;
1644 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1645 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551646 // Skip if 'srcNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471647 if (!srcNode->inst->isa<AffineForOp>())
MLIR Team6892ffb2018-12-20 04:42:551648 continue;
MLIR Teamb28009b2019-01-23 19:11:431649 // Skip if 'srcNode' has more than one store to any memref.
1650 // TODO(andydavis) Support fusing multi-output src loop nests.
1651 if (srcNode->stores.size() != 1)
MLIR Team6892ffb2018-12-20 04:42:551652 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241653
MLIR Teama0f3db402019-01-29 17:36:411654 // Skip 'srcNode' if it has in edges on 'memref'.
MLIR Team6892ffb2018-12-20 04:42:551655 // TODO(andydavis) Track dependence type with edges, and just check
MLIR Teama0f3db402019-01-29 17:36:411656 // for WAW dependence edge here. Note that this check is overly
1657 // conservative and will be removed in the future.
1658 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) != 0)
MLIR Team6892ffb2018-12-20 04:42:551659 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241660
MLIR Team58aa3832019-02-16 01:12:191661 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1662 // and cannot be fused.
1663 bool writesToLiveInOrOut =
1664 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1665 if (writesToLiveInOrOut &&
1666 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, memref, mdg))
MLIR Teamd7c82442019-01-30 23:53:411667 continue;
1668
MLIR Teama0f3db402019-01-29 17:36:411669 // Compute an instruction list insertion point for the fused loop
1670 // nest which preserves dependences.
MLIR Teama78edcd2019-02-05 14:57:081671 Instruction *insertPointInst =
1672 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411673 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551674 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241675
MLIR Team6892ffb2018-12-20 04:42:551676 // Get unique 'srcNode' store op.
Chris Lattner456ad6a2018-12-29 00:05:351677 auto *srcStoreOpInst = srcNode->stores.front();
MLIR Teamd7c82442019-01-30 23:53:411678 // Gather 'dstNode' store ops to 'memref'.
River Riddleb4992772019-02-04 18:38:471679 SmallVector<Instruction *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411680 for (auto *storeOpInst : dstNode->stores)
1681 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1682 dstStoreOpInsts.push_back(storeOpInst);
1683
Uday Bondhugulab4a14432019-01-26 00:00:501684 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251685 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411686 // Check if fusion would be profitable.
MLIR Teamd7c82442019-01-30 23:53:411687 if (!isFusionProfitable(srcStoreOpInst, dstLoadOpInsts,
1688 dstStoreOpInsts, &sliceState,
Uday Bondhugulab4a14432019-01-26 00:00:501689 &bestDstLoopDepth))
MLIR Team38c2fe32019-01-14 19:26:251690 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241691
MLIR Team6892ffb2018-12-20 04:42:551692 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181693 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Uday Bondhugulab4a14432019-01-26 00:00:501694 srcStoreOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
MLIR Team6892ffb2018-12-20 04:42:551695 if (sliceLoopNest != nullptr) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191696 LLVM_DEBUG(llvm::dbgs()
1697 << "\tslice loop nest:\n"
1698 << *sliceLoopNest->getInstruction() << "\n");
River Riddle5052bd82019-02-02 00:42:181699 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleb4992772019-02-04 18:38:471700 auto dstAffineForOp = dstNode->inst->cast<AffineForOp>();
River Riddle5052bd82019-02-02 00:42:181701 if (insertPointInst != dstAffineForOp->getInstruction()) {
1702 dstAffineForOp->getInstruction()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411703 }
MLIR Teamc4237ae2019-01-18 16:56:271704 // Update edges between 'srcNode' and 'dstNode'.
MLIR Teama0f3db402019-01-29 17:36:411705 mdg->updateEdges(srcNode->id, dstNode->id, memref);
MLIR Teamc4237ae2019-01-18 16:56:271706
1707 // Collect slice loop stats.
1708 LoopNestStateCollector sliceCollector;
River Riddlebf9c3812019-02-05 00:24:441709 sliceCollector.collect(sliceLoopNest->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271710 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181711 for (auto forOp : sliceCollector.forOps) {
1712 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551713 }
MLIR Team58aa3832019-02-16 01:12:191714 if (!writesToLiveInOrOut) {
1715 // Create private memref for 'memref' in 'dstAffineForOp'.
1716 SmallVector<Instruction *, 4> storesForMemref;
1717 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
1718 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1719 storesForMemref.push_back(storeOpInst);
1720 }
1721 assert(storesForMemref.size() == 1);
1722 auto *newMemRef = createPrivateMemRef(
1723 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1724 fastMemorySpace, localBufSizeThreshold);
1725 visitedMemrefs.insert(newMemRef);
1726 // Create new node in dependence graph for 'newMemRef' alloc op.
1727 unsigned newMemRefNodeId =
1728 mdg->addNode(newMemRef->getDefiningInst());
1729 // Add edge from 'newMemRef' node to dstNode.
1730 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271731 }
MLIR Teamc4237ae2019-01-18 16:56:271732
1733 // Collect dst loop stats after memref privatizaton transformation.
1734 LoopNestStateCollector dstLoopCollector;
River Riddlebf9c3812019-02-05 00:24:441735 dstLoopCollector.collect(dstAffineForOp->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271736
1737 // Add new load ops to current Node load op list 'loads' to
1738 // continue fusing based on new operands.
1739 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
1740 auto *loadMemRef = loadOpInst->cast<LoadOp>()->getMemRef();
1741 if (visitedMemrefs.count(loadMemRef) == 0)
1742 loads.push_back(loadOpInst);
1743 }
1744
1745 // Clear and add back loads and stores
1746 mdg->clearNodeLoadAndStores(dstNode->id);
1747 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1748 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371749 // Remove old src loop nest if it no longer has outgoing dependence
1750 // edges, and it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191751 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1752 // been fused into 'dstNode' and write region of 'dstNode' covers
1753 // the write region of 'srcNode', and 'srcNode' has no other users
1754 // so it is safe to remove.
1755 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271756 mdg->removeNode(srcNode->id);
River Riddle5052bd82019-02-02 00:42:181757 srcNode->inst->erase();
MLIR Teama78edcd2019-02-05 14:57:081758 } else {
1759 // Add remaining users of 'oldMemRef' back on the worklist (if not
1760 // already there), as its replacement with a local/private memref
1761 // has reduced dependences on 'oldMemRef' which may have created
1762 // new fusion opportunities.
1763 if (mdg->outEdges.count(srcNode->id) > 0) {
1764 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1765 mdg->outEdges[srcNode->id];
1766 for (auto &outEdge : oldOutEdges) {
1767 if (outEdge.value == memref &&
1768 worklistSet.count(outEdge.id) == 0) {
1769 worklist.push_back(outEdge.id);
1770 worklistSet.insert(outEdge.id);
1771 }
1772 }
1773 }
MLIR Teamc4237ae2019-01-18 16:56:271774 }
MLIR Team3b692302018-12-17 17:57:141775 }
MLIR Team3b692302018-12-17 17:57:141776 }
1777 }
1778 }
MLIR Teamc4237ae2019-01-18 16:56:271779 // Clean up any allocs with no users.
1780 for (auto &pair : mdg->memrefEdgeCount) {
1781 if (pair.second > 0)
1782 continue;
1783 auto *memref = pair.first;
MLIR Team71495d52019-01-22 21:23:371784 // Skip if there exist other uses (return instruction or function calls).
1785 if (!memref->use_empty())
1786 continue;
MLIR Teamc4237ae2019-01-18 16:56:271787 // Use list expected to match the dep graph info.
MLIR Teamc4237ae2019-01-18 16:56:271788 auto *inst = memref->getDefiningInst();
River Riddleb4992772019-02-04 18:38:471789 if (inst && inst->isa<AllocOp>())
1790 inst->erase();
MLIR Teamc4237ae2019-01-18 16:56:271791 }
MLIR Teamf28e4df2018-11-01 14:26:001792 }
MLIR Team3b692302018-12-17 17:57:141793};
1794
1795} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001796
Chris Lattner79748892018-12-31 07:10:351797PassResult LoopFusion::runOnFunction(Function *f) {
Uday Bondhugula8be26272019-02-02 01:06:221798 if (clFusionFastMemorySpace.getNumOccurrences() > 0) {
1799 fastMemorySpace = clFusionFastMemorySpace.getValue();
1800 }
1801
MLIR Team6892ffb2018-12-20 04:42:551802 MemRefDependenceGraph g;
1803 if (g.init(f))
Uday Bondhugula8be26272019-02-02 01:06:221804 GreedyFusion(&g).run(localBufSizeThreshold, fastMemorySpace);
MLIR Teamf28e4df2018-11-01 14:26:001805 return success();
1806}
Jacques Pienaar6f0fb222018-11-07 02:34:181807
1808static PassRegistration<LoopFusion> pass("loop-fusion", "Fuse loop nests");