MLIR 24.0.0git
LoopUtils.cpp
Go to the documentation of this file.
1//===- LoopUtils.cpp ---- Misc utilities for loop transformation ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements miscellaneous loop transformation routines.
10//
11//===----------------------------------------------------------------------===//
12
22#include "mlir/IR/IRMapping.h"
23#include "mlir/IR/IntegerSet.h"
26#include "llvm/ADT/MapVector.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/DebugLog.h"
29#include "llvm/Support/raw_ostream.h"
30#include <optional>
31
32#define DEBUG_TYPE "loop-utils"
33
34using namespace mlir;
35using namespace affine;
36using namespace presburger;
37using llvm::SmallMapVector;
38
39/// Computes the cleanup loop lower bound of the loop being unrolled with
40/// the specified unroll factor; this bound will also be upper bound of the main
41/// part of the unrolled loop. Computes the bound as an AffineMap with its
42/// operands or a null map when the trip count can't be expressed as an affine
43/// expression.
44static void
45getCleanupLoopLowerBound(AffineForOp forOp, unsigned unrollFactor,
46 AffineMap &cleanupLbMap,
47 SmallVectorImpl<Value> &cleanupLbOperands) {
48 AffineMap tripCountMap;
49 SmallVector<Value, 4> tripCountOperands;
50 getTripCountMapAndOperands(forOp, &tripCountMap, &tripCountOperands);
51 // Trip count can't be computed.
52 if (!tripCountMap) {
53 cleanupLbMap = AffineMap();
54 return;
55 }
56
57 OpBuilder b(forOp);
58 auto lbMap = forOp.getLowerBoundMap();
59 auto lb = AffineApplyOp::create(b, forOp.getLoc(), lbMap,
60 forOp.getLowerBoundOperands());
61
62 // For each upper bound expr, get the range.
63 // Eg: affine.for %i = lb to min (ub1, ub2),
64 // where tripCountExprs yield (tr1, tr2), we create affine.apply's:
65 // lb + tr1 - tr1 % ufactor, lb + tr2 - tr2 % ufactor; the results of all
66 // these affine.apply's make up the cleanup loop lower bound.
67 SmallVector<AffineExpr, 4> bumpExprs(tripCountMap.getNumResults());
68 SmallVector<Value, 4> bumpValues(tripCountMap.getNumResults());
69 int64_t step = forOp.getStepAsInt();
70 for (unsigned i = 0, e = tripCountMap.getNumResults(); i < e; i++) {
71 auto tripCountExpr = tripCountMap.getResult(i);
72 bumpExprs[i] = (tripCountExpr - tripCountExpr % unrollFactor) * step;
73 auto bumpMap = AffineMap::get(tripCountMap.getNumDims(),
74 tripCountMap.getNumSymbols(), bumpExprs[i]);
75 bumpValues[i] =
76 AffineApplyOp::create(b, forOp.getLoc(), bumpMap, tripCountOperands);
77 }
78
79 SmallVector<AffineExpr, 4> newUbExprs(tripCountMap.getNumResults());
80 for (unsigned i = 0, e = bumpExprs.size(); i < e; i++)
81 newUbExprs[i] = b.getAffineDimExpr(0) + b.getAffineDimExpr(i + 1);
82
83 cleanupLbOperands.clear();
84 cleanupLbOperands.push_back(lb);
85 cleanupLbOperands.append(bumpValues.begin(), bumpValues.end());
86 cleanupLbMap = AffineMap::get(1 + tripCountMap.getNumResults(), 0, newUbExprs,
87 b.getContext());
88 // Simplify the cleanupLbMap + cleanupLbOperands.
89 fullyComposeAffineMapAndOperands(&cleanupLbMap, &cleanupLbOperands);
90 cleanupLbMap = simplifyAffineMap(cleanupLbMap);
91 canonicalizeMapAndOperands(&cleanupLbMap, &cleanupLbOperands);
92 // Remove any affine.apply's that became dead from the simplification above.
93 for (auto v : bumpValues)
94 if (v.use_empty())
95 v.getDefiningOp()->erase();
96
97 if (lb.use_empty())
98 lb.erase();
99}
100
101/// Returns the max of the bound given by `map` applied to `operands` and the
102/// lower bound of `forOp`, as a map over the updated `operands`. Returns `map`
103/// unchanged if it is known not to be below the lower bound. Both bounds must
104/// have a single result.
105static AffineMap getMaxWithLowerBound(AffineForOp forOp, AffineMap map,
106 SmallVectorImpl<Value> &operands) {
107 AffineMap lbMap = forOp.getLowerBoundMap();
108 assert(map.getNumResults() == 1 && lbMap.getNumResults() == 1 &&
109 "expected single-result bounds");
110 // Place the dims and symbols of the lower bound after those of `map`.
111 unsigned numDims = map.getNumDims();
112 unsigned numLbDims = lbMap.getNumDims();
113 AffineMap shiftedLbMap =
114 lbMap.shiftDims(numDims).shiftSymbols(map.getNumSymbols());
115 AffineMap maxMap = AffineMap::get(
116 shiftedLbMap.getNumDims(), shiftedLbMap.getNumSymbols(),
117 {map.getResult(0), shiftedLbMap.getResult(0)}, forOp.getContext());
118 ValueRange lbOperands = forOp.getLowerBoundOperands();
119 SmallVector<Value, 4> maxOperands(operands.begin(),
120 operands.begin() + numDims);
121 llvm::append_range(maxOperands, lbOperands.take_front(numLbDims));
122 llvm::append_range(maxOperands,
123 ArrayRef<Value>(operands).drop_front(numDims));
124 llvm::append_range(maxOperands, lbOperands.drop_front(numLbDims));
125 fullyComposeAffineMapAndOperands(&maxMap, &maxOperands);
126 canonicalizeMapAndOperands(&maxMap, &maxOperands);
127 maxMap = simplifyAffineMap(maxMap);
128
129 AffineExpr diff =
130 simplifyAffineExpr(maxMap.getResult(0) - maxMap.getResult(1),
131 maxMap.getNumDims(), maxMap.getNumSymbols());
132 if (auto cst = dyn_cast<AffineConstantExpr>(diff); cst && cst.getValue() >= 0)
133 return map;
134 operands.assign(maxOperands.begin(), maxOperands.end());
135 return maxMap;
136}
137
138/// Helper to replace uses of loop carried values (iter_args) and loop
139/// yield values while promoting single iteration affine.for ops.
140static void replaceIterArgsAndYieldResults(AffineForOp forOp) {
141 // Replace uses of iter arguments with iter operands (initial values).
142 auto iterOperands = forOp.getInits();
143 auto iterArgs = forOp.getRegionIterArgs();
144 for (auto e : llvm::zip(iterOperands, iterArgs))
145 std::get<1>(e).replaceAllUsesWith(std::get<0>(e));
146
147 // Replace uses of loop results with the values yielded by the loop.
148 auto outerResults = forOp.getResults();
149 auto innerResults = forOp.getBody()->getTerminator()->getOperands();
150 for (auto e : llvm::zip(outerResults, innerResults))
151 std::get<0>(e).replaceAllUsesWith(std::get<1>(e));
152}
153
154/// Promotes the loop body of a forOp to its containing block if the forOp
155/// was known to have a single iteration.
156LogicalResult mlir::affine::promoteIfSingleIteration(AffineForOp forOp) {
157 std::optional<APInt> tripCount = forOp.getStaticTripCount();
158 if (!tripCount || *tripCount != 1)
159 return failure();
160
161 // TODO: extend this for arbitrary affine bounds.
162 if (forOp.getLowerBoundMap().getNumResults() != 1)
163 return failure();
164
165 // Replaces all IV uses to its single iteration value.
166 auto iv = forOp.getInductionVar();
167 auto *parentBlock = forOp->getBlock();
168 if (!iv.use_empty()) {
169 if (forOp.hasConstantLowerBound()) {
170 auto func = forOp->getParentOfType<FunctionOpInterface>();
171 OpBuilder builder(forOp->getContext());
172 if (func)
173 builder.setInsertionPointToStart(&func.getFunctionBody().front());
174 else
175 builder.setInsertionPoint(forOp);
176 auto constOp = arith::ConstantIndexOp::create(
177 builder, forOp.getLoc(), forOp.getConstantLowerBound());
178 iv.replaceAllUsesWith(constOp);
179 } else {
180 auto lbOperands = forOp.getLowerBoundOperands();
181 auto lbMap = forOp.getLowerBoundMap();
182 OpBuilder builder(forOp);
183 if (lbMap == builder.getDimIdentityMap()) {
184 // No need of generating an affine.apply.
185 iv.replaceAllUsesWith(lbOperands[0]);
186 } else {
187 auto affineApplyOp =
188 AffineApplyOp::create(builder, forOp.getLoc(), lbMap, lbOperands);
189 iv.replaceAllUsesWith(affineApplyOp);
190 }
191 }
192 }
193
195
196 // Move the loop body operations, except for its terminator, to the loop's
197 // containing block.
198 forOp.getBody()->back().erase();
199 parentBlock->getOperations().splice(Block::iterator(forOp),
200 forOp.getBody()->getOperations());
201 forOp.erase();
202 return success();
203}
204
205/// Generates an affine.for op with the specified lower and upper bounds
206/// while generating the right IV remappings to realize shifts for operations in
207/// its body. The operations that go into the loop body are specified in
208/// opGroupQueue starting from the specified offset, and in that order. The
209/// first element of the pair specifies the shift applied to that group of
210/// operations; the shift is multiplied by the loop step before being applied.
211/// Returns nullptr if the generated loop simplifies to a single iteration one.
212static AffineForOp generateShiftedLoop(
213 AffineMap lbMap, AffineMap ubMap,
214 const std::vector<std::pair<uint64_t, ArrayRef<Operation *>>> &opGroupQueue,
215 unsigned offset, AffineForOp srcForOp, OpBuilder b) {
216 auto lbOperands = srcForOp.getLowerBoundOperands();
217 auto ubOperands = srcForOp.getUpperBoundOperands();
218
219 assert(lbMap.getNumInputs() == lbOperands.size());
220 assert(ubMap.getNumInputs() == ubOperands.size());
221
222 auto loopChunk =
223 AffineForOp::create(b, srcForOp.getLoc(), lbOperands, lbMap, ubOperands,
224 ubMap, srcForOp.getStepAsInt());
225 auto loopChunkIV = loopChunk.getInductionVar();
226 auto srcIV = srcForOp.getInductionVar();
227
228 IRMapping operandMap;
229
230 auto bodyBuilder = OpBuilder::atBlockTerminator(loopChunk.getBody());
231 for (const auto &it : llvm::drop_begin(opGroupQueue, offset)) {
232 uint64_t shift = it.first;
233 auto ops = it.second;
234 // All 'same shift' operations get added with their operands being
235 // remapped to results of cloned operations, and their IV used remapped.
236 // Generate the remapping if the shift is not zero: remappedIV = newIV -
237 // shift.
238 if (!srcIV.use_empty() && shift != 0) {
239 auto ivRemap = AffineApplyOp::create(
240 bodyBuilder, srcForOp.getLoc(),
241 bodyBuilder.getSingleDimShiftAffineMap(
242 -static_cast<int64_t>(srcForOp.getStepAsInt() * shift)),
243 loopChunkIV);
244 operandMap.map(srcIV, ivRemap);
245 } else {
246 operandMap.map(srcIV, loopChunkIV);
247 }
248 for (auto *op : ops)
249 bodyBuilder.clone(*op, operandMap);
250 };
251 if (succeeded(promoteIfSingleIteration(loopChunk)))
252 return AffineForOp();
253 return loopChunk;
254}
255
256// The skewing of operations with respect to one another can be used for
257// example to allow overlap of asynchronous operations (such as DMA
258// communication) with computation, or just relative shifting of operations
259// for better register reuse, locality or parallelism. As such, the shifts are
260// typically expected to be at most of the order of the number of operations.
261// This method should not be used as a substitute for loop distribution/fission.
262// This method uses an algorithm// in time linear in the number of operations
263// in the body of the for loop - (using the 'sweep line' paradigm). This method
264// asserts preservation of SSA dominance. A check for that as well as that for
265// memory-based dependence preservation check rests with the users of this
266// method.
267LogicalResult mlir::affine::affineForOpBodySkew(AffineForOp forOp,
268 ArrayRef<uint64_t> shifts,
269 bool unrollPrologueEpilogue) {
270 assert(forOp.getBody()->getOperations().size() == shifts.size() &&
271 "too few/many shifts");
272 if (forOp.getBody()->begin() == std::prev(forOp.getBody()->end()))
273 return success();
274
275 // If the trip counts aren't constant, we would need versioning and
276 // conditional guards (or context information to prevent such versioning). The
277 // better way to pipeline for such loops is to first tile them and extract
278 // constant trip count "full tiles" before applying this.
279 auto mayBeConstTripCount = forOp.getStaticTripCount();
280 if (!mayBeConstTripCount) {
281 LLVM_DEBUG(forOp.emitRemark("non-constant trip count loop not handled"));
282 return success();
283 }
284 uint64_t tripCount = mayBeConstTripCount->getZExtValue();
285
286 assert(isOpwiseShiftValid(forOp, shifts) &&
287 "shifts will lead to an invalid transformation\n");
288
289 int64_t step = forOp.getStepAsInt();
290
291 unsigned numChildOps = shifts.size();
292
293 // Do a linear time (counting) sort for the shifts.
294 uint64_t maxShift = *llvm::max_element(shifts);
295 if (maxShift >= numChildOps) {
296 // Large shifts are not the typical use case.
297 forOp.emitWarning("not shifting because shifts are unrealistically large");
298 return success();
299 }
300
301 // An array of operation groups sorted by shift amount; each group has all
302 // operations with the same shift in the order in which they appear in the
303 // body of the 'affine.for' op.
304 std::vector<std::vector<Operation *>> sortedOpGroups(maxShift + 1);
305 unsigned pos = 0;
306 for (auto &op : forOp.getBody()->without_terminator()) {
307 auto shift = shifts[pos++];
308 sortedOpGroups[shift].push_back(&op);
309 }
310
311 // Unless the shifts have a specific pattern (which actually would be the
312 // common use case), prologue and epilogue are not meaningfully defined.
313 // Nevertheless, if 'unrollPrologueEpilogue' is set, we will treat the first
314 // loop generated as the prologue and the last as epilogue and unroll these
315 // fully.
316 AffineForOp prologue, epilogue;
317
318 // Do a sweep over the sorted shifts while storing open groups in a
319 // vector, and generating loop portions as necessary during the sweep. A block
320 // of operations is paired with its shift.
321 std::vector<std::pair<uint64_t, ArrayRef<Operation *>>> opGroupQueue;
322
323 auto origLbMap = forOp.getLowerBoundMap();
324 uint64_t lbShift = 0;
325 OpBuilder b(forOp);
326 for (uint64_t d = 0, e = sortedOpGroups.size(); d < e; ++d) {
327 // If nothing is shifted by d, continue.
328 if (sortedOpGroups[d].empty())
329 continue;
330 if (!opGroupQueue.empty()) {
331 assert(d > 0 &&
332 "Queue expected to be empty when the first block is found");
333 // The interval for which the loop needs to be generated here is:
334 // [lbShift, min(lbShift + tripCount, d)) and the body of the
335 // loop needs to have all operations in opQueue in that order.
336 AffineForOp res;
337 if (lbShift + tripCount * step < d * step) {
339 b.getShiftedAffineMap(origLbMap, lbShift),
340 b.getShiftedAffineMap(origLbMap, lbShift + tripCount * step),
341 opGroupQueue, /*offset=*/0, forOp, b);
342 // Entire loop for the queued op groups generated, empty it.
343 opGroupQueue.clear();
344 lbShift += tripCount * step;
345 } else {
346 res = generateShiftedLoop(b.getShiftedAffineMap(origLbMap, lbShift),
347 b.getShiftedAffineMap(origLbMap, d),
348 opGroupQueue, /*offset=*/0, forOp, b);
349 lbShift = d * step;
350 }
351
352 if (res) {
353 // Simplify/canonicalize the affine.for.
354 RewritePatternSet patterns(res.getContext());
355 AffineForOp::getCanonicalizationPatterns(patterns, res.getContext());
356 bool erased;
358 res.getOperation(), std::move(patterns),
359 GreedyRewriteConfig().setStrictness(
361 /*changed=*/nullptr, &erased);
362 if (!erased && !prologue)
363 prologue = res;
364 if (!erased)
365 epilogue = res;
366 }
367 } else {
368 // Start of first interval.
369 lbShift = d * step;
370 }
371 // Augment the list of operations that get into the current open interval.
372 opGroupQueue.emplace_back(d, sortedOpGroups[d]);
373 }
374
375 // Those operations groups left in the queue now need to be processed (FIFO)
376 // and their loops completed.
377 for (unsigned i = 0, e = opGroupQueue.size(); i < e; ++i) {
378 uint64_t ubShift = (opGroupQueue[i].first + tripCount) * step;
379 epilogue = generateShiftedLoop(b.getShiftedAffineMap(origLbMap, lbShift),
380 b.getShiftedAffineMap(origLbMap, ubShift),
381 opGroupQueue, /*offset=*/i, forOp, b);
382 lbShift = ubShift;
383 if (!prologue)
384 prologue = epilogue;
385 }
386
387 // Erase the original for op.
388 forOp.erase();
389
390 if (unrollPrologueEpilogue && prologue)
391 (void)loopUnrollFull(prologue);
392 if (unrollPrologueEpilogue && !epilogue && epilogue != prologue)
393 (void)loopUnrollFull(epilogue);
394
395 return success();
396}
397
398/// Checks whether a loop nest is hyper-rectangular or not.
399static LogicalResult
402 SmallVector<Operation *, 8> ops(input.begin(), input.end());
403 // 0-d or 1-d is trivially hyper-rectangular.
404 if (input.size() <= 1)
405 return success();
406 if (failed(getIndexSet(ops, &cst))) {
407 LDBG() << "Index set computation failed!";
408 return failure();
409 }
410 if (!cst.isHyperRectangular(0, input.size())) {
411 LDBG() << "Non-hyperrectangular nests not supported for tiling!";
412 return failure();
413 }
414 return success();
415}
416
417/// Check if the input nest is supported for tiling and whether tiling would be
418/// legal or not.
419template <typename t>
421 ArrayRef<t> tileSizes) {
422 assert(input.size() == tileSizes.size() && "Too few/many tile sizes");
423
424 if (llvm::any_of(input,
425 [](AffineForOp op) { return op.getNumResults() > 0; })) {
426 LDBG() << "Cannot tile nest where a loop has yield values";
427 return failure();
428 }
429
430 // Check if the supplied `for` ops are all successively nested.
431 if (!isPerfectlyNested(input)) {
432 LDBG() << "input loops not perfectly nested";
433 return failure();
434 }
435
436 // TODO: handle non hyper-rectangular spaces.
437 if (failed(checkIfHyperRectangular(input)))
438 return failure();
439
440 return success();
441}
442
443/// Move the loop body of AffineForOp 'src' from 'src' into the specified
444/// location in destination's body, ignoring the terminator.
445static void moveLoopBodyImpl(AffineForOp src, AffineForOp dest,
446 Block::iterator loc) {
447 auto &ops = src.getBody()->getOperations();
448 dest.getBody()->getOperations().splice(loc, ops, ops.begin(),
449 std::prev(ops.end()));
450}
451
452/// Move the loop body of AffineForOp 'src' from 'src' to the start of dest
453/// body.
454static void moveLoopBody(AffineForOp src, AffineForOp dest) {
455 moveLoopBodyImpl(src, dest, dest.getBody()->begin());
456}
457
458/// Constructs tiled loop nest, without setting the loop bounds and move the
459/// body of the original loop nest to the tiled loop nest.
461 AffineForOp rootAffineForOp, unsigned width,
462 MutableArrayRef<AffineForOp> tiledLoops) {
463 Location loc = rootAffineForOp.getLoc();
464
465 // The outermost among the loops as we add more..
466 Operation *topLoop = rootAffineForOp.getOperation();
467 AffineForOp innermostPointLoop;
468
469 // Add intra-tile (or point) loops.
470 for (unsigned i = 0; i < width; i++) {
471 OpBuilder b(topLoop);
472 // Loop bounds will be set later.
473 AffineForOp pointLoop = AffineForOp::create(b, loc, 0, 0);
474 pointLoop.getBody()->getOperations().splice(
475 pointLoop.getBody()->begin(), topLoop->getBlock()->getOperations(),
476 topLoop);
477 tiledLoops[2 * width - 1 - i] = pointLoop;
478 topLoop = pointLoop.getOperation();
479 if (i == 0)
480 innermostPointLoop = pointLoop;
481 }
482
483 // Add tile space loops;
484 for (unsigned i = width; i < 2 * width; i++) {
485 OpBuilder b(topLoop);
486 // Loop bounds will be set later.
487 AffineForOp tileSpaceLoop = AffineForOp::create(b, loc, 0, 0);
488 tileSpaceLoop.getBody()->getOperations().splice(
489 tileSpaceLoop.getBody()->begin(), topLoop->getBlock()->getOperations(),
490 topLoop);
491 tiledLoops[2 * width - i - 1] = tileSpaceLoop;
492 topLoop = tileSpaceLoop.getOperation();
493 }
494
495 // Move the loop body of the original nest to the new one.
496 moveLoopBody(origLoops.back(), innermostPointLoop);
497}
498
499/// Set lower and upper bounds of intra-tile loops for parametric tiling.
500// TODO: Handle non-constant lower bounds.
501static void setIntraTileBoundsParametric(OpBuilder &b, AffineForOp origLoop,
502 AffineForOp newInterTileLoop,
503 AffineForOp newIntraTileLoop,
504 Value tileSize) {
505 // The lower bound for the intra-tile loop is represented by an affine map
506 // as (%i, %t0)->((%i - %origlb) * %t0 + %origlb). Similarly, the upper bound
507 // for the intra-tile loop is represented by an affine map as (%i, %t0)->((%i
508 // - %origlb) * %t0) + (%t0 * %origLoopStep) + %origlb), where %i is loop IV
509 // of the corresponding inter-tile loop, %t0 is the corresponding tiling
510 // parameter, %origlb is lower bound and %origLoopStep is the loop step of the
511 // corresponding inter-tile loop.
512
513 assert(origLoop.hasConstantLowerBound() &&
514 "expected input loops to have constant lower bound.");
515
516 // Get lower bound of original loop as an affine expression.
517 AffineExpr origLowerBoundExpr;
518 origLowerBoundExpr =
519 b.getAffineConstantExpr(origLoop.getConstantLowerBound());
520
521 // Add dim operands from original lower/upper bound.
522 SmallVector<Value, 4> lbOperands, ubOperands;
523 AffineBound lb = origLoop.getLowerBound();
524 AffineBound ub = origLoop.getUpperBound();
525 lbOperands.reserve(lb.getNumOperands() + 2);
526 ubOperands.reserve(ub.getNumOperands() + 2);
527 AffineMap origLbMap = lb.getMap();
528 AffineMap origUbMap = ub.getMap();
529 for (unsigned j = 0, e = origLbMap.getNumDims(); j < e; ++j)
530 lbOperands.push_back(lb.getOperand(j));
531 for (unsigned j = 0, e = origUbMap.getNumDims(); j < e; ++j)
532 ubOperands.push_back(ub.getOperand(j));
533
534 // Add a new dim operand in lb/ubOperands corresponding to the origLoop
535 // IV.
536 lbOperands.push_back(newInterTileLoop.getInductionVar());
537 ubOperands.push_back(newInterTileLoop.getInductionVar());
538
539 // Get loop IV as an affine expression for lower/upper bound. Size of
540 // lb/ubOperands is guaranteed to be atleast one.
541 AffineExpr lbLoopIvExpr = b.getAffineDimExpr(lbOperands.size() - 1);
542 AffineExpr ubLoopIvExpr = b.getAffineDimExpr(ubOperands.size() - 1);
543
544 // Add symbol operands from original lower/upper bound.
545 for (unsigned j = 0, e = origLbMap.getNumSymbols(); j < e; ++j)
546 lbOperands.push_back(lb.getOperand(origLbMap.getNumDims() + j));
547 for (unsigned j = 0, e = origUbMap.getNumSymbols(); j < e; ++j)
548 ubOperands.push_back(ub.getOperand(origUbMap.getNumDims() + j));
549
550 // Add a new symbol operand which is the tile size for this loop.
551 lbOperands.push_back(tileSize);
552 ubOperands.push_back(tileSize);
553
554 SmallVector<AffineExpr, 4> lbBoundExprs;
555 SmallVector<AffineExpr, 4> ubBoundExprs;
556 lbBoundExprs.reserve(origLbMap.getNumResults());
557 ubBoundExprs.reserve(origUbMap.getNumResults());
558
559 // Get tiling parameter as an affine expression for lb/ub.
560 AffineExpr lbTileParameter = b.getAffineSymbolExpr(origLbMap.getNumSymbols());
561 AffineExpr ubTileParameter = b.getAffineSymbolExpr(origUbMap.getNumSymbols());
562
563 // Insert lb as inter-tile ((loop IV - origlb) * tilingParameter) + origlb.
564 lbBoundExprs.push_back(
565 ((lbLoopIvExpr - origLowerBoundExpr) * lbTileParameter) +
566 origLowerBoundExpr);
567
568 // Get the origLoopStep as an affine expression.
569 AffineExpr origLoopStep = b.getAffineConstantExpr(origLoop.getStepAsInt());
570
571 // Insert ub as inter-tile ((loop IV - origlb) * tilingParameter) +
572 // (tilingParameter * origLoopStep) + origlb.
573 ubBoundExprs.push_back(
574 ((ubLoopIvExpr - origLowerBoundExpr) * ubTileParameter) +
575 (ubTileParameter * origLoopStep) + origLowerBoundExpr);
576
577 ubBoundExprs.append(origUbMap.getResults().begin(),
578 origUbMap.getResults().end());
579
580 AffineMap lbMap =
581 AffineMap::get(origLbMap.getNumDims() + 1, origLbMap.getNumSymbols() + 1,
582 lbBoundExprs, b.getContext());
583 newIntraTileLoop.setLowerBound(lbOperands, lbMap);
584
585 AffineMap ubMap =
586 AffineMap::get(origUbMap.getNumDims() + 1, origUbMap.getNumSymbols() + 1,
587 ubBoundExprs, b.getContext());
588 newIntraTileLoop.setUpperBound(ubOperands, ubMap);
589
590 // Original loop step must be preserved.
591 newIntraTileLoop.setStep(origLoop.getStepAsInt());
592}
593
594/// Set lower and upper bounds of inter-tile loops for parametric tiling.
595// TODO: Handle non-constant lower bounds.
596static void setInterTileBoundsParametric(OpBuilder &b, AffineForOp origLoop,
597 AffineForOp newLoop, Value tileSize) {
598 OperandRange newLbOperands = origLoop.getLowerBoundOperands();
599
600 // The lower bounds for inter-tile loops are same as the corresponding lower
601 // bounds of original loops.
602 newLoop.setLowerBound(newLbOperands, origLoop.getLowerBoundMap());
603
604 // The new upper bound map for inter-tile loops, assuming constant lower
605 // bounds, are now originalLowerBound + ceildiv((originalUpperBound -
606 // originalLowerBound), tiling parameter); where tiling parameter is the
607 // respective tile size for that loop. For e.g. if the original ubmap was
608 // ()->(1024), the new map will be
609 // ()[s0]->(ceildiv((1024 -lb) % s0)), where s0 is the tiling parameter.
610 // Therefore a new symbol operand is inserted in the map and the result
611 // expression is overwritten.
612
613 assert(origLoop.hasConstantLowerBound() &&
614 "expected input loops to have constant lower bound.");
615
616 // Get lower bound of original loop as an affine expression.
617 AffineExpr origLowerBoundExpr;
618 origLowerBoundExpr =
619 b.getAffineConstantExpr(origLoop.getConstantLowerBound());
620
621 // Add dim operands from original upper bound.
622 SmallVector<Value, 4> ubOperands;
623 AffineBound ub = origLoop.getUpperBound();
624 ubOperands.reserve(ub.getNumOperands() + 1);
625 AffineMap origUbMap = ub.getMap();
626 for (unsigned j = 0, e = origUbMap.getNumDims(); j < e; ++j)
627 ubOperands.push_back(ub.getOperand(j));
628
629 // Add symbol operands from original upper bound.
630 for (unsigned j = 0, e = origUbMap.getNumSymbols(); j < e; ++j)
631 ubOperands.push_back(ub.getOperand(origUbMap.getNumDims() + j));
632
633 // Add a new symbol operand which is the tile size for this loop.
634 ubOperands.push_back(tileSize);
635
636 // Get tiling parameter as an affine expression.
637 AffineExpr tileParameter = b.getAffineSymbolExpr(origUbMap.getNumSymbols());
638
640 boundExprs.reserve(origUbMap.getNumResults());
641 int64_t origUpperBound;
642 AffineExpr origUpperBoundExpr;
643
644 // If upper bound for the original loop is constant, then the constant can
645 // be obtained as an affine expression straight away.
646 if (origLoop.hasConstantUpperBound()) {
647 origUpperBound = origLoop.getConstantUpperBound();
648
649 // Get original constant upper bound as an affine expression.
650 origUpperBoundExpr = b.getAffineConstantExpr(origUpperBound);
651
652 // Insert the bound as originalLowerBoundceildiv((originalUpperBound -
653 // originalLowerBound), tilingParameter).
654 boundExprs.push_back(
655 origLowerBoundExpr +
656 (origUpperBoundExpr - origLowerBoundExpr).ceilDiv(tileParameter));
657 } else {
658 // If upper bound for the original loop is not constant then two cases
659 // are possible, although there handeling is the same, 1.) The result of
660 // ubmap has only one result expression. For e.g.
661 // affine.for %i = 5 to %ub
662 //
663 // A symbol operand is added which represents the tiling parameter. The
664 // new loop bounds here will be like ()[s0, s1] -> ((s0 - 5) ceildiv s1 + 5)
665 // where 's0' is the original upper bound and 's1' is the tiling
666 // parameter. 2.) When ubMap has more than one result expression. For e.g.
667 // #map0 = affine_map<()[s0, s1] -> (s0, s1)
668 // affine.for %i = 5 to min #map0()[%s0, %s1]
669 //
670 // A symbol operand is added which represents the tiling parameter. The
671 // new loop bounds will be like ()[s0, s1, s2] -> ((s0 - 5) ceildiv s2 + 5,
672 // (s1 -5) ceildiv s2 + 5), where s2 is the tiling parameter.
673
674 // Insert the bounds as originalLowerBound + ceildiv((originalUpperBound -
675 // originalLowerBound), tilingParameter).
676 for (AffineExpr origUpperBoundExpr : origUbMap.getResults())
677 boundExprs.push_back(
678 origLowerBoundExpr +
679 (origUpperBoundExpr - origLowerBoundExpr).ceilDiv(tileParameter));
680 }
681
682 AffineMap ubMap =
683 AffineMap::get(origUbMap.getNumDims(), origUbMap.getNumSymbols() + 1,
684 boundExprs, b.getContext());
685 newLoop.setUpperBound(ubOperands, ubMap);
686
687 // Original loop step must be preserved.
688 newLoop.setStep(origLoop.getStepAsInt());
689}
690
691/// Constructs and sets new loop bounds after tiling for the case of
692/// hyper-rectangular index sets, where the bounds of one dimension do not
693/// depend on other dimensions and tiling parameters are captured from SSA
694/// values. Bounds of each dimension can thus be treated independently,
695/// and deriving the new bounds is much simpler and faster than for the case of
696/// tiling arbitrary polyhedral shapes.
699 MutableArrayRef<AffineForOp> newLoops, ArrayRef<Value> tileSizes) {
700 assert(!origLoops.empty() && "expected atleast one loop in band");
701 assert(origLoops.size() == tileSizes.size() &&
702 "expected tiling parameter for each loop in band.");
703
704 OpBuilder b(origLoops[0].getOperation());
705 unsigned width = origLoops.size();
706
707 // Set bounds for tile space loops.
708 for (unsigned i = 0; i < width; ++i) {
709 setInterTileBoundsParametric(b, origLoops[i], newLoops[i], tileSizes[i]);
710 }
711
712 // Set bounds for intra-tile loops.
713 for (unsigned i = 0; i < width; ++i) {
714 setIntraTileBoundsParametric(b, origLoops[i], newLoops[i],
715 newLoops[i + width], tileSizes[i]);
716 }
717}
718
719/// Constructs and sets new loop bounds after tiling for the case of
720/// hyper-rectangular index sets, where the bounds of one dimension do not
721/// depend on other dimensions. Bounds of each dimension can thus be treated
722/// independently, and deriving the new bounds is much simpler and faster
723/// than for the case of tiling arbitrary polyhedral shapes.
724static void
727 ArrayRef<unsigned> tileSizes) {
728 assert(!origLoops.empty());
729 assert(origLoops.size() == tileSizes.size());
730
731 OpBuilder b(origLoops[0].getOperation());
732 unsigned width = origLoops.size();
733
734 // Bounds for tile space loops.
735 for (unsigned i = 0; i < width; i++) {
736 OperandRange newLbOperands = origLoops[i].getLowerBoundOperands();
737 OperandRange newUbOperands = origLoops[i].getUpperBoundOperands();
738 newLoops[i].setLowerBound(newLbOperands, origLoops[i].getLowerBoundMap());
739 newLoops[i].setUpperBound(newUbOperands, origLoops[i].getUpperBoundMap());
740 // If the step size of original loop is x and tileSize is y then after
741 // tiling the tile space loops' step size becomes x*y.
742 newLoops[i].setStep(tileSizes[i] * origLoops[i].getStepAsInt());
743 }
744 // Bounds for intra-tile loops.
745 for (unsigned i = 0; i < width; i++) {
746 int64_t largestDiv = getLargestDivisorOfTripCount(origLoops[i]);
747 AffineForOp forOp = origLoops[i];
748 std::optional<uint64_t> mayBeConstantCount = std::nullopt;
749 if (auto staticTripCount = forOp.getStaticTripCount())
750 mayBeConstantCount = staticTripCount->getZExtValue();
751 // The lower bound is just the tile-space loop.
752 AffineMap lbMap = b.getDimIdentityMap();
753 newLoops[width + i].setLowerBound(
754 /*operands=*/newLoops[i].getInductionVar(), lbMap);
755 // The step sizes of intra-tile loops is just the original loops' step size.
756 newLoops[width + i].setStep(origLoops[i].getStepAsInt());
757
758 // Set the upper bound.
759 if (mayBeConstantCount && *mayBeConstantCount < tileSizes[i]) {
760 // Trip count is less than the tile size: upper bound is lower bound +
761 // trip count * stepSize.
762 AffineMap ubMap = b.getSingleDimShiftAffineMap(
763 *mayBeConstantCount * origLoops[i].getStepAsInt());
764 newLoops[width + i].setUpperBound(
765 /*operands=*/newLoops[i].getInductionVar(), ubMap);
766 } else if (largestDiv % tileSizes[i] != 0) {
767 // Intra-tile loop ii goes from i to min(i + tileSize * stepSize, ub_i).
768 // Construct the upper bound map; the operands are the original operands
769 // with 'i' (tile-space loop) appended to it. The new upper bound map is
770 // the original one with an additional expression i + tileSize * stepSize
771 // appended.
772
773 // Add dim operands from original upper bound.
774 SmallVector<Value, 4> ubOperands;
775 AffineBound ub = origLoops[i].getUpperBound();
776 ubOperands.reserve(ub.getNumOperands() + 1);
777 AffineMap origUbMap = ub.getMap();
778 for (unsigned j = 0, e = origUbMap.getNumDims(); j < e; ++j)
779 ubOperands.push_back(ub.getOperand(j));
780
781 // Add dim operand for new loop upper bound.
782 ubOperands.push_back(newLoops[i].getInductionVar());
783
784 // Add symbol operands from original upper bound.
785 for (unsigned j = 0, e = origUbMap.getNumSymbols(); j < e; ++j)
786 ubOperands.push_back(ub.getOperand(origUbMap.getNumDims() + j));
787
789 boundExprs.reserve(1 + origUbMap.getNumResults());
790 AffineExpr dim = b.getAffineDimExpr(origUbMap.getNumDims());
791 // The new upper bound map is the original one with an additional
792 // expression i + tileSize * stepSize (of original loop) appended.
793 boundExprs.push_back(dim + tileSizes[i] * origLoops[i].getStepAsInt());
794 boundExprs.append(origUbMap.getResults().begin(),
795 origUbMap.getResults().end());
796 AffineMap ubMap =
797 AffineMap::get(origUbMap.getNumDims() + 1, origUbMap.getNumSymbols(),
798 boundExprs, b.getContext());
799 newLoops[width + i].setUpperBound(/*operands=*/ubOperands, ubMap);
800 } else {
801 // No need of the min expression.
802 AffineExpr dim = b.getAffineDimExpr(0);
804 1, 0, dim + tileSizes[i] * origLoops[i].getStepAsInt());
805 newLoops[width + i].setUpperBound(newLoops[i].getInductionVar(), ubMap);
806 }
807 }
808}
809
810LogicalResult
812 ArrayRef<unsigned> tileSizes,
813 SmallVectorImpl<AffineForOp> *tiledNest) {
814 if (input.empty())
815 return success();
816
817 if (failed(performPreTilingChecks(input, tileSizes)))
818 return failure();
819
820 MutableArrayRef<AffineForOp> origLoops = input;
821 AffineForOp rootAffineForOp = origLoops[0];
822
823 // Note that width is at least one since the band isn't empty.
824 unsigned width = input.size();
825 SmallVector<AffineForOp, 6> tiledLoops(2 * width);
826
827 // Construct a tiled loop nest without setting their bounds. Bounds are
828 // set later.
829 constructTiledLoopNest(origLoops, rootAffineForOp, width, tiledLoops);
830
831 SmallVector<Value, 8> origLoopIVs;
832 extractForInductionVars(input, &origLoopIVs);
833
834 // Set loop bounds for the tiled loop nest.
835 constructTiledIndexSetHyperRect(origLoops, tiledLoops, tileSizes);
836
837 // Replace original IVs with intra-tile loop IVs.
838 for (unsigned i = 0; i < width; i++)
839 origLoopIVs[i].replaceAllUsesWith(tiledLoops[i + width].getInductionVar());
840
841 // Erase the old loop nest.
842 rootAffineForOp.erase();
843
844 if (tiledNest)
845 *tiledNest = std::move(tiledLoops);
846
847 return success();
848}
849
850/// Tiles the specified band of perfectly nested loops creating tile-space
851/// loops and intra-tile loops, using SSA values as tiling parameters. A band
852/// is a contiguous set of loops.
855 SmallVectorImpl<AffineForOp> *tiledNest) {
856 if (input.empty())
857 return success();
858
859 if (failed(performPreTilingChecks(input, tileSizes)))
860 return failure();
861
862 MutableArrayRef<AffineForOp> origLoops = input;
863 AffineForOp rootAffineForOp = origLoops[0];
864 unsigned width = input.size();
865 SmallVector<AffineForOp, 6> tiledLoops(2 * width);
866
867 // Construct a tiled loop nest without setting their bounds. Bounds are
868 // set later.
869 constructTiledLoopNest(origLoops, rootAffineForOp, width, tiledLoops);
870
871 SmallVector<Value, 8> origLoopIVs;
872 extractForInductionVars(input, &origLoopIVs);
873
874 // Set loop bounds for the tiled loop nest.
876 tileSizes);
877
878 // Replace original IVs with intra-tile loop IVs.
879 for (unsigned i = 0; i < width; i++)
880 origLoopIVs[i].replaceAllUsesWith(tiledLoops[i + width].getInductionVar());
881
882 // Erase the old loop nest.
883 rootAffineForOp.erase();
884
885 if (tiledNest)
886 *tiledNest = std::move(tiledLoops);
887
888 return success();
889}
890
891/// Get perfectly nested sequence of loops starting at root of loop nest
892/// (the first op being another AffineFor, and the second op - a terminator).
893/// A loop is perfectly nested iff: the first op in the loop's body is another
894/// AffineForOp, and the second op is a terminator).
896 SmallVectorImpl<AffineForOp> &nestedLoops, AffineForOp root) {
897 for (unsigned i = 0; i < std::numeric_limits<unsigned>::max(); ++i) {
898 nestedLoops.push_back(root);
899 Block &body = root.getRegion().front();
900 if (body.begin() != std::prev(body.end(), 2))
901 return;
902
903 root = dyn_cast<AffineForOp>(&body.front());
904 if (!root)
905 return;
906 }
907}
908
909/// Unrolls this loop completely.
910LogicalResult mlir::affine::loopUnrollFull(AffineForOp forOp) {
911 std::optional<APInt> mayBeConstantTripCount = forOp.getStaticTripCount();
912 if (mayBeConstantTripCount.has_value()) {
913 uint64_t tripCount = mayBeConstantTripCount->getZExtValue();
914 if (tripCount == 0)
915 return success();
916 if (tripCount == 1)
917 return promoteIfSingleIteration(forOp);
918 return loopUnrollByFactor(forOp, tripCount);
919 }
920 return failure();
921}
922
923/// Unrolls this loop by the specified factor or by the trip count (if constant)
924/// whichever is lower.
925LogicalResult mlir::affine::loopUnrollUpToFactor(AffineForOp forOp,
926 uint64_t unrollFactor) {
927 std::optional<APInt> mayBeConstantTripCount = forOp.getStaticTripCount();
928 if (mayBeConstantTripCount.has_value() &&
929 mayBeConstantTripCount->ult(unrollFactor)) {
930 // Nothing to unroll in a zero-trip loop.
931 if (mayBeConstantTripCount->isZero())
932 return success();
933 return loopUnrollByFactor(forOp, mayBeConstantTripCount->getZExtValue());
934 }
935 return loopUnrollByFactor(forOp, unrollFactor);
936}
937
938/// Generates unrolled copies of AffineForOp 'loopBodyBlock', with associated
939/// 'forOpIV' by 'unrollFactor', calling 'ivRemapFn' to remap 'forOpIV' for each
940/// unrolled body. If specified, annotates the Ops in each unrolled iteration
941/// using annotateFn.
943 Block *loopBodyBlock, Value forOpIV, uint64_t unrollFactor,
944 function_ref<Value(unsigned, Value, OpBuilder)> ivRemapFn,
945 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
946 ValueRange iterArgs, ValueRange yieldedValues) {
947 // Builder to insert unrolled bodies just before the terminator of the body of
948 // 'forOp'.
949 auto builder = OpBuilder::atBlockTerminator(loopBodyBlock);
950
951 constexpr auto defaultAnnotateFn = [](unsigned, Operation *, OpBuilder) {};
952 if (!annotateFn)
953 annotateFn = defaultAnnotateFn;
954
955 // Keep a pointer to the last non-terminator operation in the original block
956 // so that we know what to clone (since we are doing this in-place).
957 Block::iterator srcBlockEnd = std::prev(loopBodyBlock->end(), 2);
958
959 // Unroll the contents of 'forOp' (append unrollFactor - 1 additional copies).
960 SmallVector<Value, 4> lastYielded(yieldedValues);
961
962 for (unsigned i = 1; i < unrollFactor; i++) {
963 IRMapping operandMap;
964
965 // Prepare operand map.
966 operandMap.map(iterArgs, lastYielded);
967
968 // If the induction variable is used, create a remapping to the value for
969 // this unrolled instance.
970 if (!forOpIV.use_empty()) {
971 Value ivUnroll = ivRemapFn(i, forOpIV, builder);
972 operandMap.map(forOpIV, ivUnroll);
973 }
974
975 // Clone the original body of 'forOp'.
976 for (auto it = loopBodyBlock->begin(); it != std::next(srcBlockEnd); it++) {
977 Operation *clonedOp = builder.clone(*it, operandMap);
978 annotateFn(i, clonedOp, builder);
979 }
980
981 // Update yielded values. Values defined outside the loop body are not in
982 // `operandMap` and stay unchanged.
983 for (unsigned i = 0, e = lastYielded.size(); i < e; i++)
984 lastYielded[i] = operandMap.lookupOrDefault(yieldedValues[i]);
985 }
986
987 // Make sure we annotate the Ops in the original body. We do this last so that
988 // any annotations are not copied into the cloned Ops above.
989 for (auto it = loopBodyBlock->begin(); it != std::next(srcBlockEnd); it++)
990 annotateFn(0, &*it, builder);
991
992 // Update operands of the yield statement.
993 loopBodyBlock->getTerminator()->setOperands(lastYielded);
994}
995
996/// Helper to generate cleanup loop for unroll or unroll-and-jam when the trip
997/// count is not a multiple of `unrollFactor`.
998static LogicalResult generateCleanupLoopForUnroll(AffineForOp forOp,
999 uint64_t unrollFactor) {
1000 // Insert the cleanup loop right after 'forOp'.
1001 OpBuilder builder(forOp->getBlock(), std::next(Block::iterator(forOp)));
1002 auto cleanupForOp = cast<AffineForOp>(builder.clone(*forOp));
1003
1004 // Update uses of `forOp` results. `cleanupForOp` should use `forOp` result
1005 // and produce results for the original users of `forOp` results.
1006 auto results = forOp.getResults();
1007 auto cleanupResults = cleanupForOp.getResults();
1008 auto cleanupIterOperands = cleanupForOp.getInits();
1009
1010 for (auto e : llvm::zip(results, cleanupResults, cleanupIterOperands)) {
1011 std::get<0>(e).replaceAllUsesWith(std::get<1>(e));
1012 cleanupForOp->replaceUsesOfWith(std::get<2>(e), std::get<0>(e));
1013 }
1014
1015 AffineMap cleanupMap;
1016 SmallVector<Value, 4> cleanupOperands;
1017 getCleanupLoopLowerBound(forOp, unrollFactor, cleanupMap, cleanupOperands);
1018 if (!cleanupMap)
1019 return failure();
1020
1021 // The cleanup loop must not execute if `forOp` does not, but `cleanupMap` is
1022 // below the lower bound of `forOp` if the trip count is negative.
1023 SmallVector<Value, 4> cleanupLbOperands(cleanupOperands);
1024 AffineMap cleanupLbMap =
1025 getMaxWithLowerBound(forOp, cleanupMap, cleanupLbOperands);
1026 cleanupForOp.setLowerBound(cleanupLbOperands, cleanupLbMap);
1027 // Promote the loop body up if this has turned into a single iteration loop.
1028 (void)promoteIfSingleIteration(cleanupForOp);
1029
1030 // Adjust upper bound of the original loop; this is the same as the lower
1031 // bound of the cleanup loop.
1032 forOp.setUpperBound(cleanupOperands, cleanupMap);
1033 return success();
1034}
1035
1036/// Unrolls this loop by the specified factor. Returns success if the loop
1037/// is successfully unrolled.
1039 AffineForOp forOp, uint64_t unrollFactor,
1040 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
1041 bool cleanUpUnroll) {
1042 assert(unrollFactor > 0 && "unroll factor should be positive");
1043
1044 std::optional<uint64_t> mayBeConstantTripCount = std::nullopt;
1045 if (auto staticTripCount = forOp.getStaticTripCount())
1046 mayBeConstantTripCount = staticTripCount->getZExtValue();
1047 if (unrollFactor == 1) {
1048 if (mayBeConstantTripCount == 1 && failed(promoteIfSingleIteration(forOp)))
1049 return failure();
1050 return success();
1051 }
1052
1053 // Nothing in the loop body other than the terminator.
1054 if (llvm::hasSingleElement(forOp.getBody()->getOperations()))
1055 return success();
1056
1057 // If the trip count is lower than the unroll factor, no unrolled body.
1058 if (mayBeConstantTripCount && *mayBeConstantTripCount < unrollFactor) {
1059 if (cleanUpUnroll) {
1060 // Unroll the cleanup loop if cleanUpUnroll is specified.
1061 return loopUnrollFull(forOp);
1062 }
1063
1064 return failure();
1065 }
1066
1067 // Generate the cleanup loop if trip count isn't a multiple of unrollFactor.
1068 if (getLargestDivisorOfTripCount(forOp) % unrollFactor != 0) {
1069 // Loops where the lower bound is a max expression or the upper bound is
1070 // a min expression and the trip count doesn't divide the unroll factor
1071 // can't be unrolled since the lower bound of the cleanup loop in such cases
1072 // cannot be expressed as an affine function or a max over affine functions.
1073 if (forOp.getLowerBoundMap().getNumResults() != 1 ||
1074 forOp.getUpperBoundMap().getNumResults() != 1)
1075 return failure();
1076 if (cleanUpUnroll)
1077 // Force unroll including cleanup loop
1078 return loopUnrollFull(forOp);
1079 if (failed(generateCleanupLoopForUnroll(forOp, unrollFactor)))
1080 assert(false && "cleanup loop lower bound map for single result lower "
1081 "and upper bound maps can always be determined");
1082 }
1083
1084 ValueRange iterArgs(forOp.getRegionIterArgs());
1085 auto yieldedValues = forOp.getBody()->getTerminator()->getOperands();
1086
1087 // Scale the step of loop being unrolled by unroll factor.
1088 int64_t step = forOp.getStepAsInt();
1089 forOp.setStep(step * unrollFactor);
1091 forOp.getBody(), forOp.getInductionVar(), unrollFactor,
1092 [&](unsigned i, Value iv, OpBuilder b) {
1093 // iv' = iv + i * step
1094 auto d0 = b.getAffineDimExpr(0);
1095 auto bumpMap = AffineMap::get(1, 0, d0 + i * step);
1096 return AffineApplyOp::create(b, forOp.getLoc(), bumpMap, iv);
1097 },
1098 /*annotateFn=*/annotateFn,
1099 /*iterArgs=*/iterArgs, /*yieldedValues=*/yieldedValues);
1100
1101 // Promote the loop body up if this has turned into a single iteration loop.
1103 return success();
1104}
1105
1106LogicalResult mlir::affine::loopUnrollJamUpToFactor(AffineForOp forOp,
1107 uint64_t unrollJamFactor) {
1108 std::optional<APInt> mayBeConstantTripCount = forOp.getStaticTripCount();
1109 if (mayBeConstantTripCount.has_value() &&
1110 mayBeConstantTripCount->getZExtValue() < unrollJamFactor)
1111 return loopUnrollJamByFactor(forOp, mayBeConstantTripCount->getZExtValue());
1112 return loopUnrollJamByFactor(forOp, unrollJamFactor);
1113}
1114
1115/// Check if all control operands of all loops are defined outside of `forOp`
1116/// and return false if not.
1117static bool areInnerBoundsInvariant(AffineForOp forOp) {
1118 auto walkResult = forOp.walk([&](AffineForOp aForOp) {
1119 for (auto controlOperand : aForOp.getControlOperands()) {
1120 if (!forOp.isDefinedOutsideOfLoop(controlOperand))
1121 return WalkResult::interrupt();
1122 }
1123 return WalkResult::advance();
1124 });
1125 return !walkResult.wasInterrupted();
1126}
1127
1128/// Unrolls and jams this loop by the specified factor.
1129LogicalResult mlir::affine::loopUnrollJamByFactor(AffineForOp forOp,
1130 uint64_t unrollJamFactor) {
1131 assert(unrollJamFactor > 0 && "unroll jam factor should be positive");
1132
1133 std::optional<uint64_t> mayBeConstantTripCount = std::nullopt;
1134 if (auto staticTripCount = forOp.getStaticTripCount())
1135 mayBeConstantTripCount = staticTripCount->getZExtValue();
1136 if (unrollJamFactor == 1) {
1137 if (mayBeConstantTripCount == 1 && failed(promoteIfSingleIteration(forOp)))
1138 return failure();
1139 return success();
1140 }
1141
1142 // Nothing in the loop body other than the terminator.
1143 if (llvm::hasSingleElement(forOp.getBody()->getOperations()))
1144 return success();
1145
1146 // If the trip count is lower than the unroll jam factor, no unroll jam.
1147 if (mayBeConstantTripCount && *mayBeConstantTripCount < unrollJamFactor) {
1148 LDBG() << "[failed] trip count < unroll-jam factor";
1149 return failure();
1150 }
1151
1152 // If any control operand of any inner loop of `forOp` is defined within
1153 // `forOp`, no unroll jam.
1154 if (!areInnerBoundsInvariant(forOp))
1155 return failure();
1156
1157 // Gather all sub-blocks to jam upon the loop being unrolled.
1159 jbg.walk(forOp);
1160 auto &subBlocks = jbg.subBlocks;
1161
1162 // Collect loops with iter_args.
1163 SmallVector<AffineForOp, 4> loopsWithIterArgs;
1164 forOp.walk([&](AffineForOp aForOp) {
1165 if (aForOp.getNumIterOperands() > 0)
1166 loopsWithIterArgs.push_back(aForOp);
1167 });
1168
1169 // Get supported reductions to be used for creating reduction ops at the end.
1170 SmallVector<LoopReduction> reductions;
1171 if (forOp.getNumIterOperands() > 0)
1172 getSupportedReductions(forOp, reductions);
1173
1174 // Generate the cleanup loop if trip count isn't a multiple of
1175 // unrollJamFactor.
1176 if (getLargestDivisorOfTripCount(forOp) % unrollJamFactor != 0) {
1177 // Loops where the lower bound is a max expression or the upper bound is
1178 // a min expression and the trip count doesn't divide the unroll factor
1179 // can't be unrolled since the lower bound of the cleanup loop in such cases
1180 // cannot be expressed as an affine function or a max over affine functions.
1181 if (forOp.getLowerBoundMap().getNumResults() != 1 ||
1182 forOp.getUpperBoundMap().getNumResults() != 1)
1183 return failure();
1184 if (failed(generateCleanupLoopForUnroll(forOp, unrollJamFactor)))
1185 assert(false && "cleanup loop lower bound map for single result lower "
1186 "and upper bound maps can always be determined");
1187 }
1188
1189 // `operandMaps[i - 1]` carries old->new operand mapping for the ith unrolled
1190 // iteration. There are (`unrollJamFactor` - 1) iterations.
1191 SmallVector<IRMapping, 4> operandMaps(unrollJamFactor - 1);
1192
1193 // For any loop with iter_args, replace it with a new loop that has
1194 // `unrollJamFactor` copies of its iterOperands, iter_args and yield
1195 // operands.
1196 SmallVector<AffineForOp, 4> newLoopsWithIterArgs;
1197 IRRewriter rewriter(forOp.getContext());
1198 for (AffineForOp oldForOp : loopsWithIterArgs) {
1199 SmallVector<Value> dupIterOperands, dupYieldOperands;
1200 ValueRange oldIterOperands = oldForOp.getInits();
1201 ValueRange oldIterArgs = oldForOp.getRegionIterArgs();
1202 ValueRange oldYieldOperands =
1203 cast<AffineYieldOp>(oldForOp.getBody()->getTerminator()).getOperands();
1204 // Get additional iterOperands, iterArgs, and yield operands. We will
1205 // fix iterOperands and yield operands after cloning of sub-blocks.
1206 for (unsigned i = unrollJamFactor - 1; i >= 1; --i) {
1207 dupIterOperands.append(oldIterOperands.begin(), oldIterOperands.end());
1208 dupYieldOperands.append(oldYieldOperands.begin(), oldYieldOperands.end());
1209 }
1210 // Create a new loop with additional iterOperands, iter_args and yield
1211 // operands. This new loop will take the loop body of the original loop.
1212 bool forOpReplaced = oldForOp == forOp;
1213 AffineForOp newForOp =
1214 cast<AffineForOp>(*oldForOp.replaceWithAdditionalYields(
1215 rewriter, dupIterOperands, /*replaceInitOperandUsesInLoop=*/false,
1216 [&](OpBuilder &b, Location loc, ArrayRef<BlockArgument> newBbArgs) {
1217 return dupYieldOperands;
1218 }));
1219 newLoopsWithIterArgs.push_back(newForOp);
1220 // `forOp` has been replaced with a new loop.
1221 if (forOpReplaced)
1222 forOp = newForOp;
1223 // Update `operandMaps` for `newForOp` iterArgs and results.
1224 ValueRange newIterArgs = newForOp.getRegionIterArgs();
1225 unsigned oldNumIterArgs = oldIterArgs.size();
1226 ValueRange newResults = newForOp.getResults();
1227 unsigned oldNumResults = newResults.size() / unrollJamFactor;
1228 assert(oldNumIterArgs == oldNumResults &&
1229 "oldNumIterArgs must be the same as oldNumResults");
1230 for (unsigned i = unrollJamFactor - 1; i >= 1; --i) {
1231 for (unsigned j = 0; j < oldNumIterArgs; ++j) {
1232 // `newForOp` has `unrollJamFactor` - 1 new sets of iterArgs and
1233 // results. Update `operandMaps[i - 1]` to map old iterArgs and results
1234 // to those in the `i`th new set.
1235 operandMaps[i - 1].map(newIterArgs[j],
1236 newIterArgs[i * oldNumIterArgs + j]);
1237 operandMaps[i - 1].map(newResults[j],
1238 newResults[i * oldNumResults + j]);
1239 }
1240 }
1241 }
1242
1243 // Scale the step of loop being unroll-jammed by the unroll-jam factor.
1244 int64_t step = forOp.getStepAsInt();
1245 forOp.setStep(step * unrollJamFactor);
1246
1247 auto forOpIV = forOp.getInductionVar();
1248 // Unroll and jam (appends unrollJamFactor - 1 additional copies).
1249 for (unsigned i = unrollJamFactor - 1; i >= 1; --i) {
1250 for (auto &subBlock : subBlocks) {
1251 // Builder to insert unroll-jammed bodies. Insert right at the end of
1252 // sub-block.
1253 OpBuilder builder(subBlock.first->getBlock(), std::next(subBlock.second));
1254
1255 // If the induction variable is used, create a remapping to the value for
1256 // this unrolled instance.
1257 if (!forOpIV.use_empty()) {
1258 // iv' = iv + i * step, i = 1 to unrollJamFactor-1.
1259 auto d0 = builder.getAffineDimExpr(0);
1260 auto bumpMap = AffineMap::get(1, 0, d0 + i * step);
1261 auto ivUnroll =
1262 AffineApplyOp::create(builder, forOp.getLoc(), bumpMap, forOpIV);
1263 operandMaps[i - 1].map(forOpIV, ivUnroll);
1264 }
1265 // Clone the sub-block being unroll-jammed.
1266 for (auto it = subBlock.first; it != std::next(subBlock.second); ++it)
1267 builder.clone(*it, operandMaps[i - 1]);
1268 }
1269 // Fix iterOperands and yield op operands of newly created loops.
1270 for (auto newForOp : newLoopsWithIterArgs) {
1271 unsigned oldNumIterOperands =
1272 newForOp.getNumIterOperands() / unrollJamFactor;
1273 unsigned numControlOperands = newForOp.getNumControlOperands();
1274 auto yieldOp = cast<AffineYieldOp>(newForOp.getBody()->getTerminator());
1275 unsigned oldNumYieldOperands = yieldOp.getNumOperands() / unrollJamFactor;
1276 assert(oldNumIterOperands == oldNumYieldOperands &&
1277 "oldNumIterOperands must be the same as oldNumYieldOperands");
1278 for (unsigned j = 0; j < oldNumIterOperands; ++j) {
1279 // The `i`th duplication of an old iterOperand or yield op operand
1280 // needs to be replaced with a mapped value from `operandMaps[i - 1]`
1281 // if such mapped value exists.
1282 newForOp.setOperand(numControlOperands + i * oldNumIterOperands + j,
1283 operandMaps[i - 1].lookupOrDefault(
1284 newForOp.getOperand(numControlOperands + j)));
1285 yieldOp.setOperand(
1286 i * oldNumYieldOperands + j,
1287 operandMaps[i - 1].lookupOrDefault(yieldOp.getOperand(j)));
1288 }
1289 }
1290 }
1291 if (forOp.getNumResults() > 0) {
1292 // Create reduction ops to combine every `unrollJamFactor` related results
1293 // into one value. For example, for %0:2 = affine.for ... and addf, we add
1294 // %1 = arith.addf %0#0, %0#1, and replace the following uses of %0#0 with
1295 // %1.
1296 rewriter.setInsertionPointAfter(forOp);
1297 auto loc = forOp.getLoc();
1298 unsigned oldNumResults = forOp.getNumResults() / unrollJamFactor;
1299 for (LoopReduction &reduction : reductions) {
1300 unsigned pos = reduction.iterArgPosition;
1301 Value lhs = forOp.getResult(pos);
1302 Value rhs;
1304 for (unsigned i = unrollJamFactor - 1; i >= 1; --i) {
1305 rhs = forOp.getResult(i * oldNumResults + pos);
1306 // Create ops based on reduction type.
1307 lhs = arith::getReductionOp(reduction.kind, rewriter, loc, lhs, rhs);
1308 if (!lhs)
1309 return failure();
1310 Operation *op = lhs.getDefiningOp();
1311 assert(op && "Reduction op should have been created");
1312 newOps.insert(op);
1313 }
1314 // Replace all uses except those in newly created reduction ops.
1315 forOp.getResult(pos).replaceAllUsesExcept(lhs, newOps);
1316 }
1317 }
1318
1319 // Promote the loop body up if this has turned into a single iteration loop.
1321 return success();
1322}
1323
1324/// Performs loop interchange on 'forOpA' and 'forOpB', where 'forOpB' is
1325/// nested within 'forOpA' as the only non-terminator operation in its block.
1326void mlir::affine::interchangeLoops(AffineForOp forOpA, AffineForOp forOpB) {
1327 assert(&*forOpA.getBody()->begin() == forOpB.getOperation());
1328 auto &forOpABody = forOpA.getBody()->getOperations();
1329 auto &forOpBBody = forOpB.getBody()->getOperations();
1330
1331 // 1) Splice forOpA's non-terminator operations (which is just forOpB) just
1332 // before forOpA (in ForOpA's parent's block) this should leave 'forOpA's
1333 // body containing only the terminator.
1334 forOpA->getBlock()->getOperations().splice(Block::iterator(forOpA),
1335 forOpABody, forOpABody.begin(),
1336 std::prev(forOpABody.end()));
1337 // 2) Splice forOpB's non-terminator operations into the beginning of forOpA's
1338 // body (this leaves forOpB's body containing only the terminator).
1339 forOpABody.splice(forOpABody.begin(), forOpBBody, forOpBBody.begin(),
1340 std::prev(forOpBBody.end()));
1341 // 3) Splice forOpA into the beginning of forOpB's body.
1342 forOpBBody.splice(forOpBBody.begin(), forOpA->getBlock()->getOperations(),
1343 Block::iterator(forOpA));
1344}
1345
1346// Checks each dependence component against the permutation to see if the
1347// desired loop interchange would violate dependences by making the
1348// dependence component lexicographically negative.
1350 const std::vector<SmallVector<DependenceComponent, 2>> &depCompsVec,
1351 ArrayRef<AffineForOp> loops, ArrayRef<unsigned> loopPermMap) {
1352 // Invert permutation map.
1353 unsigned maxLoopDepth = loops.size();
1354 SmallVector<unsigned, 4> loopPermMapInv;
1355 loopPermMapInv.resize(maxLoopDepth);
1356 for (unsigned i = 0; i < maxLoopDepth; ++i)
1357 loopPermMapInv[loopPermMap[i]] = i;
1358
1359 // Check each dependence component against the permutation to see if the
1360 // desired loop interchange permutation would make the dependence vectors
1361 // lexicographically negative.
1362 // Example 1: [-1, 1][0, 0]
1363 // Example 2: [0, 0][-1, 1]
1364 for (const auto &depComps : depCompsVec) {
1365 assert(depComps.size() >= maxLoopDepth);
1366 // Check if the first non-zero dependence component is positive.
1367 // This iterates through loops in the desired order.
1368 for (unsigned j = 0; j < maxLoopDepth; ++j) {
1369 unsigned permIndex = loopPermMapInv[j];
1370 assert(depComps[permIndex].lb);
1371 int64_t depCompLb = *depComps[permIndex].lb;
1372 if (depCompLb > 0)
1373 break;
1374 if (depCompLb < 0)
1375 return false;
1376 }
1377 }
1378 return true;
1379}
1380
1381/// Checks if the loop interchange permutation 'loopPermMap' of the perfectly
1382/// nested sequence of loops in 'loops' would violate dependences.
1384 ArrayRef<AffineForOp> loops, ArrayRef<unsigned> loopPermMap) {
1385 assert(loopPermMap.size() == loops.size() && "invalid loop perm map");
1386 unsigned maxLoopDepth = loops.size();
1387 if (maxLoopDepth == 1)
1388 return true;
1389
1390 // We cannot guarantee the validity of the interchange if the loops have
1391 // iter_args, since the dependence analysis does not take them into account.
1392 // Conservatively return false in such cases.
1393 if (llvm::any_of(loops, [](AffineForOp loop) {
1394 return loop.getNumIterOperands() > 0;
1395 }))
1396 return false;
1397
1398 // Gather dependence components for dependences between all ops in loop nest
1399 // rooted at 'loops[0]', at loop depths in range [1, maxLoopDepth].
1400 std::vector<SmallVector<DependenceComponent, 2>> depCompsVec;
1401 getDependenceComponents(loops[0], maxLoopDepth, &depCompsVec);
1402 return checkLoopInterchangeDependences(depCompsVec, loops, loopPermMap);
1403}
1404
1405/// Returns true if `loops` is a perfectly nested loop nest, where loops appear
1406/// in it from outermost to innermost.
1407[[maybe_unused]] bool
1409 assert(!loops.empty() && "no loops provided");
1410
1411 // We already know that the block can't be empty.
1412 auto hasTwoElements = [](Block *block) {
1413 auto secondOpIt = std::next(block->begin());
1414 return secondOpIt != block->end() && &*secondOpIt == &block->back();
1415 };
1416
1417 auto enclosingLoop = loops.front();
1418 for (auto loop : loops.drop_front()) {
1419 auto parentForOp = dyn_cast<AffineForOp>(loop->getParentOp());
1420 // parentForOp's body should be just this loop and the terminator.
1421 if (parentForOp != enclosingLoop || !hasTwoElements(parentForOp.getBody()))
1422 return false;
1423 enclosingLoop = loop;
1424 }
1425 return true;
1426}
1427
1428// input[i] should move from position i -> permMap[i]. Returns the position in
1429// `input` that becomes the new outermost loop.
1431 ArrayRef<unsigned> permMap) {
1432 assert(input.size() == permMap.size() && "invalid permutation map size");
1433 // Check whether the permutation spec is valid. This is a small vector - we'll
1434 // just sort and check if it's iota.
1435 SmallVector<unsigned, 4> checkPermMap(permMap);
1436 llvm::sort(checkPermMap);
1437 if (llvm::any_of(llvm::enumerate(checkPermMap),
1438 [](const auto &en) { return en.value() != en.index(); }))
1439 assert(false && "invalid permutation map");
1440
1441 // Nothing to do.
1442 if (input.size() < 2)
1443 return 0;
1444
1445 assert(isPerfectlyNested(input) && "input not perfectly nested");
1446
1447 // Compute the inverse mapping, invPermMap: since input[i] goes to position
1448 // permMap[i], position i of the permuted nest is at input[invPermMap[i]].
1450 for (unsigned i = 0, e = input.size(); i < e; ++i)
1451 invPermMap.push_back({permMap[i], i});
1452 llvm::sort(invPermMap);
1453
1454 // Move the innermost loop body to the loop that would be the innermost in the
1455 // permuted nest (only if the innermost loop is going to change).
1456 if (permMap.back() != input.size() - 1) {
1457 Block *destBody = ((AffineForOp)input[invPermMap.back().second]).getBody();
1458 Block *srcBody = ((AffineForOp)input.back()).getBody();
1459 destBody->getOperations().splice(destBody->begin(),
1460 srcBody->getOperations(), srcBody->begin(),
1461 std::prev(srcBody->end()));
1462 }
1463
1464 // We'll move each loop in `input` in the reverse order so that its body is
1465 // empty when we are moving it; this incurs zero copies and no erasing.
1466 for (int i = input.size() - 1; i >= 0; --i) {
1467 // If this has to become the outermost loop after permutation, add it to the
1468 // parent block of the original root.
1469 if (permMap[i] == 0) {
1470 // If the root remains the same, nothing to do.
1471 if (i == 0)
1472 continue;
1473 // Make input[i] the new outermost loop moving it into parentBlock.
1474 auto *parentBlock = input[0]->getBlock();
1475 parentBlock->getOperations().splice(Block::iterator(input[0]),
1476 input[i]->getBlock()->getOperations(),
1477 Block::iterator(input[i]));
1478 continue;
1479 }
1480
1481 // If the parent in the permuted order is the same as in the original,
1482 // nothing to do.
1483 unsigned parentPosInInput = invPermMap[permMap[i] - 1].second;
1484 if (i > 0 && static_cast<unsigned>(i - 1) == parentPosInInput)
1485 continue;
1486
1487 // Move input[i] to its surrounding loop in the transformed nest.
1488 auto *destBody = ((AffineForOp)input[parentPosInInput]).getBody();
1489 destBody->getOperations().splice(destBody->begin(),
1490 input[i]->getBlock()->getOperations(),
1491 Block::iterator(input[i]));
1492 }
1493
1494 return invPermMap[0].second;
1495}
1496
1497// Sinks all sequential loops to the innermost levels (while preserving
1498// relative order among them) and moves all parallel loops to the
1499// outermost (while again preserving relative order among them).
1500AffineForOp mlir::affine::sinkSequentialLoops(AffineForOp forOp) {
1502 getPerfectlyNestedLoops(loops, forOp);
1503 if (loops.size() < 2)
1504 return forOp;
1505
1506 // Gather dependence components for dependences between all ops in loop nest
1507 // rooted at 'loops[0]', at loop depths in range [1, maxLoopDepth].
1508 unsigned maxLoopDepth = loops.size();
1509 std::vector<SmallVector<DependenceComponent, 2>> depCompsVec;
1510 getDependenceComponents(loops[0], maxLoopDepth, &depCompsVec);
1511
1512 // Mark loops as either parallel or sequential.
1513 SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true);
1514 for (auto &depComps : depCompsVec) {
1515 assert(depComps.size() >= maxLoopDepth);
1516 for (unsigned j = 0; j < maxLoopDepth; ++j) {
1517 DependenceComponent &depComp = depComps[j];
1518 assert(depComp.lb.has_value() && depComp.ub.has_value());
1519 if (*depComp.lb != 0 || *depComp.ub != 0)
1520 isParallelLoop[j] = false;
1521 }
1522 }
1523
1524 unsigned numParallelLoops = llvm::count(isParallelLoop, true);
1525
1526 // Compute permutation of loops that sinks sequential loops (and thus raises
1527 // parallel loops) while preserving relative order.
1528 SmallVector<unsigned, 4> loopPermMap(maxLoopDepth);
1529 unsigned nextSequentialLoop = numParallelLoops;
1530 unsigned nextParallelLoop = 0;
1531 for (unsigned i = 0; i < maxLoopDepth; ++i) {
1532 if (isParallelLoop[i]) {
1533 loopPermMap[i] = nextParallelLoop++;
1534 } else {
1535 loopPermMap[i] = nextSequentialLoop++;
1536 }
1537 }
1538
1539 // Check if permutation 'loopPermMap' would violate dependences.
1540 if (!checkLoopInterchangeDependences(depCompsVec, loops, loopPermMap))
1541 return forOp;
1542 // Perform loop interchange according to permutation 'loopPermMap'.
1543 unsigned loopNestRootIndex = permuteLoops(loops, loopPermMap);
1544 return loops[loopNestRootIndex];
1545}
1546
1547// Factors out common behavior to add a new `iv` (resp. `iv` + `offset`) to the
1548// lower (resp. upper) loop bound. When called for both the lower and upper
1549// bounds, the resulting IR resembles:
1550//
1551// ```mlir
1552// affine.for %i = max (`iv, ...) to min (`iv` + `offset`) {
1553// ...
1554// }
1555// ```
1557 SmallVector<Value, 4> *operands,
1558 int64_t offset = 0) {
1559 auto bounds = llvm::to_vector<4>(map->getResults());
1560 bounds.push_back(b.getAffineDimExpr(map->getNumDims()) + offset);
1561 operands->insert(operands->begin() + map->getNumDims(), iv);
1562 *map = AffineMap::get(map->getNumDims() + 1, map->getNumSymbols(), bounds,
1563 b.getContext());
1564 canonicalizeMapAndOperands(map, operands);
1565}
1566
1567// Stripmines `forOp` by `factor` and sinks it under each of the `targets`.
1568// Stripmine-sink is a primitive building block for generalized tiling of
1569// imperfectly nested loops.
1570// This transformation is purely mechanical and does not check legality,
1571// profitability or even structural correctness. It is the user's
1572// responsibility to specify `targets` that are dominated by `forOp`.
1573// Returns the new AffineForOps, one per `targets`, nested immediately under
1574// each of the `targets`.
1576stripmineSink(AffineForOp forOp, uint64_t factor,
1577 ArrayRef<AffineForOp> targets) {
1578 auto originalStep = forOp.getStepAsInt();
1579 auto scaledStep = originalStep * factor;
1580 forOp.setStep(scaledStep);
1581
1582 OpBuilder b(forOp->getBlock(), std::next(Block::iterator(forOp)));
1583
1584 // Lower-bound map creation.
1585 auto lbMap = forOp.getLowerBoundMap();
1586 SmallVector<Value, 4> lbOperands(forOp.getLowerBoundOperands());
1587 augmentMapAndBounds(b, forOp.getInductionVar(), &lbMap, &lbOperands);
1588
1589 // Upper-bound map creation.
1590 auto ubMap = forOp.getUpperBoundMap();
1591 SmallVector<Value, 4> ubOperands(forOp.getUpperBoundOperands());
1592 augmentMapAndBounds(b, forOp.getInductionVar(), &ubMap, &ubOperands,
1593 /*offset=*/scaledStep);
1594
1595 auto iv = forOp.getInductionVar();
1596 SmallVector<AffineForOp, 8> innerLoops;
1597 for (auto t : targets) {
1598 // Insert newForOp before the terminator of `t`.
1599 auto b = OpBuilder::atBlockTerminator(t.getBody());
1600 auto newForOp = AffineForOp::create(b, t.getLoc(), lbOperands, lbMap,
1601 ubOperands, ubMap, originalStep);
1602 auto begin = t.getBody()->begin();
1603 // Skip terminator and `newForOp` which is just before the terminator.
1604 auto nOps = t.getBody()->getOperations().size() - 2;
1605 newForOp.getBody()->getOperations().splice(
1606 newForOp.getBody()->getOperations().begin(),
1607 t.getBody()->getOperations(), begin, std::next(begin, nOps));
1608 replaceAllUsesInRegionWith(iv, newForOp.getInductionVar(),
1609 newForOp.getRegion());
1610 innerLoops.push_back(newForOp);
1611 }
1612
1613 return innerLoops;
1614}
1615
1618 ArrayRef<AffineForOp> targets) {
1620 SmallVector<AffineForOp, 8> currentTargets(targets);
1621 for (auto it : llvm::zip(forOps, sizes)) {
1622 auto step = stripmineSink(std::get<0>(it), std::get<1>(it), currentTargets);
1623 res.push_back(step);
1624 currentTargets = std::move(step);
1625 }
1626 return res;
1627}
1628
1630 ArrayRef<uint64_t> sizes,
1631 AffineForOp target) {
1633 for (auto loops : tile(forOps, sizes, ArrayRef<AffineForOp>(target)))
1634 res.push_back(llvm::getSingleElement(loops));
1635 return res;
1636}
1637
1638LogicalResult mlir::affine::coalesceLoops(MutableArrayRef<AffineForOp> loops) {
1639 if (loops.size() < 2)
1640 return success();
1641
1642 AffineForOp innermost = loops.back();
1643 AffineForOp outermost = loops.front();
1644 AffineBound ub = outermost.getUpperBound();
1645 AffineMap origUbMap = ub.getMap();
1646 Location loc = outermost.getLoc();
1647 OpBuilder builder(outermost);
1648 for (AffineForOp loop : loops) {
1649 // We only work on normalized loops.
1650 if (loop.getStepAsInt() != 1 || !loop.hasConstantLowerBound() ||
1651 loop.getConstantLowerBound() != 0)
1652 return failure();
1653 }
1654 SmallVector<Value, 4> upperBoundSymbols;
1655 SmallVector<Value, 4> ubOperands(ub.getOperands().begin(),
1656 ub.getOperands().end());
1657
1658 // 1. Store the upper bound of the outermost loop in a variable.
1659 Value prev;
1660 if (!llvm::hasSingleElement(origUbMap.getResults()))
1661 prev = AffineMinOp::create(builder, loc, origUbMap, ubOperands);
1662 else
1663 prev = AffineApplyOp::create(builder, loc, origUbMap, ubOperands);
1664 upperBoundSymbols.push_back(prev);
1665
1666 // 2. Emit code computing the upper bound of the coalesced loop as product of
1667 // the number of iterations of all loops.
1668 for (AffineForOp loop : loops.drop_front()) {
1669 ub = loop.getUpperBound();
1670 origUbMap = ub.getMap();
1671 ubOperands = ub.getOperands();
1672 Value upperBound;
1673 // If upper bound map has more than one result, take their minimum.
1674 if (!llvm::hasSingleElement(origUbMap.getResults()))
1675 upperBound = AffineMinOp::create(builder, loc, origUbMap, ubOperands);
1676 else
1677 upperBound = AffineApplyOp::create(builder, loc, origUbMap, ubOperands);
1678 upperBoundSymbols.push_back(upperBound);
1679 SmallVector<Value, 4> operands;
1680 operands.push_back(prev);
1681 operands.push_back(upperBound);
1682 // Maintain running product of loop upper bounds.
1683 prev = AffineApplyOp::create(
1684 builder, loc,
1685 AffineMap::get(/*dimCount=*/1,
1686 /*symbolCount=*/1,
1687 builder.getAffineDimExpr(0) *
1688 builder.getAffineSymbolExpr(0)),
1689 operands);
1690 }
1691 // Set upper bound of the coalesced loop.
1692 AffineMap newUbMap = AffineMap::get(
1693 /*dimCount=*/0,
1694 /*symbolCount=*/1, builder.getAffineSymbolExpr(0), builder.getContext());
1695 outermost.setUpperBound(prev, newUbMap);
1696
1697 builder.setInsertionPointToStart(outermost.getBody());
1698
1699 // 3. Remap induction variables. For each original loop, the value of the
1700 // induction variable can be obtained by dividing the induction variable of
1701 // the linearized loop by the total number of iterations of the loops nested
1702 // in it modulo the number of iterations in this loop (remove the values
1703 // related to the outer loops):
1704 // iv_i = floordiv(iv_linear, product-of-loop-ranges-until-i) mod range_i.
1705 // Compute these iteratively from the innermost loop by creating a "running
1706 // quotient" of division by the range.
1707 Value previous = outermost.getInductionVar();
1708 for (unsigned idx = loops.size(); idx > 0; --idx) {
1709 if (idx != loops.size()) {
1710 SmallVector<Value, 4> operands;
1711 operands.push_back(previous);
1712 operands.push_back(upperBoundSymbols[idx]);
1713 previous = AffineApplyOp::create(builder, loc,
1715 /*dimCount=*/1, /*symbolCount=*/1,
1716 builder.getAffineDimExpr(0).floorDiv(
1717 builder.getAffineSymbolExpr(0))),
1718 operands);
1719 }
1720 // Modified value of the induction variables of the nested loops after
1721 // coalescing.
1722 Value inductionVariable;
1723 if (idx == 1) {
1724 inductionVariable = previous;
1725 } else {
1726 SmallVector<Value, 4> applyOperands;
1727 applyOperands.push_back(previous);
1728 applyOperands.push_back(upperBoundSymbols[idx - 1]);
1729 inductionVariable = AffineApplyOp::create(
1730 builder, loc,
1732 /*dimCount=*/1, /*symbolCount=*/1,
1733 builder.getAffineDimExpr(0) % builder.getAffineSymbolExpr(0)),
1734 applyOperands);
1735 }
1736 replaceAllUsesInRegionWith(loops[idx - 1].getInductionVar(),
1737 inductionVariable, loops.back().getRegion());
1738 }
1739
1740 // 4. Move the operations from the innermost just above the second-outermost
1741 // loop, delete the extra terminator and the second-outermost loop.
1742 AffineForOp secondOutermostLoop = loops[1];
1743 innermost.getBody()->back().erase();
1744 outermost.getBody()->getOperations().splice(
1745 Block::iterator(secondOutermostLoop.getOperation()),
1746 innermost.getBody()->getOperations());
1747 for (auto [iter, init] :
1748 llvm::zip_equal(secondOutermostLoop.getRegionIterArgs(),
1749 secondOutermostLoop.getInits())) {
1750 iter.replaceAllUsesWith(init);
1751 iter.dropAllUses();
1752 }
1753 secondOutermostLoop.erase();
1754 return success();
1755}
1756
1757void mlir::affine::mapLoopToProcessorIds(scf::ForOp forOp,
1758 ArrayRef<Value> processorId,
1759 ArrayRef<Value> numProcessors) {
1760 assert(processorId.size() == numProcessors.size());
1761 if (processorId.empty())
1762 return;
1763
1764 OpBuilder b(forOp);
1765 Location loc(forOp.getLoc());
1766 AffineExpr lhs, rhs;
1767 bindSymbols(forOp.getContext(), lhs, rhs);
1768 auto mulMap = AffineMap::get(0, 2, lhs * rhs);
1769 auto addMap = AffineMap::get(0, 2, lhs + rhs);
1770
1771 Value linearIndex = processorId.front();
1772 for (unsigned i = 1, e = processorId.size(); i < e; ++i) {
1773 auto mulApplyOp = AffineApplyOp::create(
1774 b, loc, mulMap, ValueRange{linearIndex, numProcessors[i]});
1775 linearIndex = AffineApplyOp::create(b, loc, addMap,
1776 ValueRange{mulApplyOp, processorId[i]});
1777 }
1778
1779 auto mulApplyOp = AffineApplyOp::create(
1780 b, loc, mulMap, ValueRange{linearIndex, forOp.getStep()});
1781 Value lb = AffineApplyOp::create(
1782 b, loc, addMap, ValueRange{mulApplyOp, forOp.getLowerBound()});
1783 forOp.setLowerBound(lb);
1784
1785 Value step = forOp.getStep();
1786 for (auto numProcs : numProcessors)
1787 step = AffineApplyOp::create(b, loc, mulMap, ValueRange{numProcs, step});
1788 forOp.setStep(step);
1789}
1790
1791/// Given a memref region, determine the lowest depth at which transfers can be
1792/// placed for it, and return the corresponding block, start and end positions
1793/// in the block for placing incoming (read) and outgoing (write) copies
1794/// respectively. The lowest depth depends on whether the region being accessed
1795/// is hoistable with respect to one or more immediately surrounding loops.
1796static void
1798 Block::iterator &begin, Block::iterator &end,
1799 Block **copyPlacementBlock,
1800 Block::iterator *copyInPlacementStart,
1801 Block::iterator *copyOutPlacementStart) {
1802 const auto *cst = region.getConstraints();
1803 SmallVector<Value, 4> symbols;
1804 cst->getValues(cst->getNumDimVars(), cst->getNumDimAndSymbolVars(), &symbols);
1805
1806 SmallVector<Operation *, 4> enclosingAffineOps;
1807 getEnclosingAffineOps(*block.begin(), &enclosingAffineOps);
1808 // Walk up loop parents till we find an IV on which this region is
1809 // symbolic/variant or we hit `hoistGuard`.
1810 auto it = enclosingAffineOps.rbegin();
1811 AffineForOp lastInvariantFor;
1812 for (auto e = enclosingAffineOps.rend(); it != e; ++it) {
1813 Operation *enclosingOp = *it;
1814 // We can't hoist past the definition of the memref being copied.
1815 Value memref = region.memref;
1816 if (!memref.getParentRegion()->isAncestor(enclosingOp->getParentRegion())) {
1817 LDBG() << "memref definition will end up not dominating hoist location";
1818 break;
1819 }
1820
1821 auto affineFor = dyn_cast<AffineForOp>(enclosingOp);
1822 if (!affineFor)
1823 break;
1824 // TODO: also need to be checking this for regions symbols that
1825 // aren't loop IVs, whether we are within their resp. defs' dominance scope.
1826 if (llvm::is_contained(symbols, affineFor.getInductionVar()))
1827 break;
1828 lastInvariantFor = affineFor;
1829 }
1830
1831 if (it != enclosingAffineOps.rbegin()) {
1832 *copyInPlacementStart = Block::iterator(lastInvariantFor);
1833 *copyOutPlacementStart = std::next(*copyInPlacementStart);
1834 *copyPlacementBlock = lastInvariantFor->getBlock();
1835 } else {
1836 *copyInPlacementStart = begin;
1837 *copyOutPlacementStart = end;
1838 *copyPlacementBlock = &block;
1839 }
1840}
1841
1842// Info comprising stride and number of elements transferred every stride.
1847
1848/// Returns striding information for a copy/transfer of this region with
1849/// potentially multiple striding levels from outermost to innermost. For an
1850/// n-dimensional region, there can be at most n-1 levels of striding
1851/// successively nested.
1852// TODO: make this work with non-identity layout maps.
1853static void getMultiLevelStrides(const MemRefRegion &region,
1854 ArrayRef<int64_t> bufferShape,
1855 SmallVectorImpl<StrideInfo> *strideInfos) {
1856 if (bufferShape.size() <= 1)
1857 return;
1858
1859 int64_t numEltPerStride = 1;
1860 int64_t stride = 1;
1861 for (int d = bufferShape.size() - 1; d >= 1; d--) {
1862 int64_t dimSize = cast<MemRefType>(region.memref.getType()).getDimSize(d);
1863 stride *= dimSize;
1864 numEltPerStride *= bufferShape[d];
1865 // A stride is needed only if the region has a shorter extent than the
1866 // memref along the dimension *and* has an extent greater than one along the
1867 // next major dimension.
1868 if (bufferShape[d] < dimSize && bufferShape[d - 1] > 1) {
1869 strideInfos->push_back({stride, numEltPerStride});
1870 }
1871 }
1872}
1873
1874/// Generates a point-wise copy from/to a non-zero ranked `memref' to/from
1875/// `fastMemRef' and returns the outermost AffineForOp of the copy loop nest.
1876/// `lbMaps` and `ubMaps` along with `lbOperands` and `ubOperands` hold the
1877/// lower and upper bound information for the copy loop nest. `fastBufOffsets`
1878/// contain the expressions to be subtracted out from the respective copy loop
1879/// iterators in order to index the fast buffer. If `copyOut' is true, generates
1880/// a copy-out; otherwise a copy-in. Builder `b` should be set to the point the
1881/// copy nest is inserted.
1882//
1883/// The copy-in nest is generated as follows as an example for a 2-d region:
1884/// for x = ...
1885/// for y = ...
1886/// fast_buf[x - offset_x][y - offset_y] = memref[x][y]
1887///
1888static AffineForOp
1889generatePointWiseCopy(Location loc, Value memref, Value fastMemRef,
1890 ArrayRef<AffineMap> lbMaps, ArrayRef<Value> lbOperands,
1891 ArrayRef<AffineMap> ubMaps, ArrayRef<Value> ubOperands,
1892 ArrayRef<AffineExpr> fastBufOffsets, bool isCopyOut,
1893 OpBuilder b) {
1894 assert(llvm::all_of(lbMaps, [&](AffineMap lbMap) {
1895 return lbMap.getNumInputs() == lbOperands.size();
1896 }));
1897 assert(llvm::all_of(ubMaps, [&](AffineMap ubMap) {
1898 return ubMap.getNumInputs() == ubOperands.size();
1899 }));
1900
1901 unsigned rank = cast<MemRefType>(memref.getType()).getRank();
1902 // A copy nest can't be generated for 0-ranked memrefs.
1903 assert(rank != 0 && "non-zero rank memref expected");
1904 assert(lbMaps.size() == rank && "wrong number of lb maps");
1905 assert(ubMaps.size() == rank && "wrong number of ub maps");
1906
1907 SmallVector<Value, 4> memIndices;
1909 SmallVector<Value, 4> fastBufMapOperands;
1910 AffineForOp copyNestRoot;
1911 SmallVector<AffineApplyOp, 4> mayBeDeadApplys;
1912 for (unsigned d = 0; d < rank; ++d) {
1913 auto forOp = createCanonicalizedAffineForOp(b, loc, lbOperands, lbMaps[d],
1914 ubOperands, ubMaps[d]);
1915 if (d == 0)
1916 copyNestRoot = forOp;
1917
1918 b = OpBuilder::atBlockTerminator(forOp.getBody());
1919
1920 auto fastBufOffsetMap =
1921 AffineMap::get(lbOperands.size(), 0, fastBufOffsets[d]);
1922 auto offset = AffineApplyOp::create(b, loc, fastBufOffsetMap, lbOperands);
1923
1924 // Construct the subscript for the fast memref being copied into/from:
1925 // x - offset_x.
1926 fastBufExprs.push_back(b.getAffineDimExpr(2 * d + 1) -
1927 b.getAffineDimExpr(2 * d));
1928 fastBufMapOperands.push_back(offset);
1929 fastBufMapOperands.push_back(forOp.getInductionVar());
1930 mayBeDeadApplys.push_back(offset);
1931
1932 // Subscript for the slow memref being copied.
1933 memIndices.push_back(forOp.getInductionVar());
1934 }
1935
1936 auto fastBufMap =
1937 AffineMap::get(2 * rank, /*symbolCount=*/0, fastBufExprs, b.getContext());
1940 canonicalizeMapAndOperands(&fastBufMap, &fastBufMapOperands);
1941
1942 // Drop any dead affine.applys.
1943 for (auto applyOp : mayBeDeadApplys)
1944 if (applyOp.use_empty())
1945 applyOp.erase();
1946
1947 if (!isCopyOut) {
1948 // Copy in.
1949 auto load = AffineLoadOp::create(b, loc, memref, memIndices);
1950 AffineStoreOp::create(b, loc, load, fastMemRef, fastBufMap,
1951 fastBufMapOperands);
1952 return copyNestRoot;
1953 }
1954
1955 // Copy out.
1956 auto load =
1957 AffineLoadOp::create(b, loc, fastMemRef, fastBufMap, fastBufMapOperands);
1958 AffineStoreOp::create(b, loc, load, memref, memIndices);
1960}
1961
1962[[maybe_unused]] static InFlightDiagnostic emitRemarkForBlock(Block &block) {
1963 return block.getParentOp()->emitRemark();
1964}
1965
1966/// Creates a buffer in the faster memory space for the specified memref region
1967/// (memref has to be non-zero ranked); generates a copy from the lower memory
1968/// space to this one, and replaces all loads/stores in the block range
1969/// [`begin', `end') of `block' to load/store from that buffer. Returns failure
1970/// if copies could not be generated due to yet unimplemented cases.
1971/// `copyInPlacementStart` and `copyOutPlacementStart` in copyPlacementBlock
1972/// specify the insertion points where the incoming copies and outgoing copies,
1973/// respectively, should be inserted (the insertion happens right before the
1974/// insertion point). Since `begin` can itself be invalidated due to the memref
1975/// rewriting done from this method, the output argument `nBegin` is set to its
1976/// replacement (set to `begin` if no invalidation happens). Since outgoing
1977/// copies could have been inserted at `end`, the output argument `nEnd` is set
1978/// to the new end. `sizeInBytes` is set to the size of the fast buffer
1979/// allocated.
1980static LogicalResult generateCopy(
1981 const MemRefRegion &region, Block *block, Block::iterator begin,
1982 Block::iterator end, Block *copyPlacementBlock,
1983 Block::iterator copyInPlacementStart, Block::iterator copyOutPlacementStart,
1984 const AffineCopyOptions &copyOptions, DenseMap<Value, Value> &fastBufferMap,
1985 DenseSet<Operation *> &copyNests, uint64_t *sizeInBytes,
1986 Block::iterator *nBegin, Block::iterator *nEnd) {
1987 *nBegin = begin;
1988 *nEnd = end;
1989
1990 auto f = begin->getParentOfType<FunctionOpInterface>();
1991 OpBuilder topBuilder(f.getFunctionBody());
1992 Value zeroIndex = arith::ConstantIndexOp::create(topBuilder, f.getLoc(), 0);
1993
1994 *sizeInBytes = 0;
1995
1996 if (begin == end)
1997 return success();
1998
1999 // Record the last op in the block for which we are performing copy
2000 // generation. We later do the memref replacement only in [begin, lastCopyOp]
2001 // so that the original memref's used in the data movement code themselves
2002 // don't get replaced.
2003 Operation *lastCopyOp = end->getPrevNode();
2004
2005 // Is the copy out point at the end of the block where we are doing
2006 // explicit copying.
2007 bool isCopyOutAtEndOfBlock = (end == copyOutPlacementStart);
2008
2009 // Copies for read regions are going to be inserted at 'begin'.
2010 OpBuilder prologue(copyPlacementBlock, copyInPlacementStart);
2011 // Copies for write regions are going to be inserted at 'end'.
2012 OpBuilder epilogue(copyPlacementBlock, copyOutPlacementStart);
2013 OpBuilder &b = region.isWrite() ? epilogue : prologue;
2014
2015 // Builder to create constants at the top level.
2016 auto func =
2017 copyPlacementBlock->getParent()->getParentOfType<FunctionOpInterface>();
2018 OpBuilder top(func.getFunctionBody());
2019
2020 auto loc = region.loc;
2021 auto memref = region.memref;
2022 auto memRefType = cast<MemRefType>(memref.getType());
2023
2024 if (!memRefType.getLayout().isIdentity()) {
2025 LDBG() << "Non-identity layout map not yet supported";
2026 return failure();
2027 }
2028
2029 // Indices to use for the copying.
2030 // Indices for the original memref being copied from/to.
2031 SmallVector<Value, 4> memIndices;
2032 // Indices for the faster buffer being copied into/from.
2033 SmallVector<Value, 4> bufIndices;
2034
2035 unsigned rank = memRefType.getRank();
2036 if (rank == 0) {
2037 LDBG() << "Non-zero ranked memrefs supported";
2038 return failure();
2039 }
2040
2041 SmallVector<int64_t, 4> fastBufferShape;
2042
2043 // Compute the extents of the buffer.
2045 lbs.reserve(rank);
2046 std::optional<int64_t> numElements =
2047 region.getConstantBoundingSizeAndShape(&fastBufferShape, &lbs);
2048 if (!numElements) {
2049 LDBG() << "Non-constant region size not supported";
2050 return failure();
2051 }
2052
2053 if (llvm::any_of(lbs, [](AffineMap lb) { return lb.getNumResults() > 1; })) {
2054 // This can be supported in the future if needed.
2055 LDBG() << "Max lower bound for memref region start not supported";
2056 return failure();
2057 }
2058
2059 if (*numElements == 0) {
2060 LDBG() << "Nothing to copy";
2061 return success();
2062 }
2063
2064 SmallVector<AffineMap, 4> lbMaps(rank), ubMaps(rank);
2065 for (unsigned i = 0; i < rank; ++i) {
2066 region.getLowerAndUpperBound(i, lbMaps[i], ubMaps[i]);
2067 if (lbMaps[i].getNumResults() == 0 || ubMaps[i].getNumResults() == 0) {
2068 LDBG() << "Missing lower or upper bound for region along dimension: "
2069 << i;
2070 return failure();
2071 }
2072 }
2073
2074 const FlatAffineValueConstraints *cst = region.getConstraints();
2075 // 'regionSymbols' hold values that this memory region is symbolic/parametric
2076 // on; these typically include loop IVs surrounding the level at which the
2077 // copy generation is being done or other valid symbols in MLIR.
2078 SmallVector<Value, 8> regionSymbols;
2079 cst->getValues(rank, cst->getNumVars(), &regionSymbols);
2080
2081 // Construct the access expression for the fast memory buffer. The access
2082 // expression for a particular dimension of the fast buffer is obtained by
2083 // subtracting out the lower bound on the original memref's data region
2084 // along the corresponding dimension.
2085
2086 // Index start offsets for faster memory buffer relative to the original.
2087 SmallVector<AffineExpr, 4> fastBufOffsets;
2088 fastBufOffsets.reserve(rank);
2089 for (unsigned d = 0; d < rank; d++) {
2090 assert(lbs[d].getNumSymbols() == cst->getNumCols() - rank - 1 &&
2091 "incorrect bound size");
2092
2093 // Set copy start location for this dimension in the lower memory space
2094 // memref.
2095 if (lbs[d].isSingleConstant()) {
2096 auto indexVal = lbs[d].getSingleConstantResult();
2097 if (indexVal == 0) {
2098 memIndices.push_back(zeroIndex);
2099 } else {
2100 memIndices.push_back(
2101 arith::ConstantIndexOp::create(top, loc, indexVal).getResult());
2102 }
2103 } else {
2104 // The coordinate for the start location is just the lower bound along the
2105 // corresponding dimension on the memory region (stored in 'offset').
2106 // Remap all inputs of the map to dimensions uniformly since in the
2107 // generate IR we need valid affine symbols as opposed to "symbols" for
2108 // the purpose of the memref region.
2109 SmallVector<AffineExpr> symReplacements(lbs[d].getNumSymbols());
2110 for (unsigned i = 0, e = lbs[d].getNumSymbols(); i < e; ++i)
2111 symReplacements[i] = top.getAffineDimExpr(i);
2112 lbs[d] = lbs[d].replaceDimsAndSymbols(
2113 /*dimReplacements=*/{}, symReplacements, lbs[d].getNumSymbols(),
2114 /*numResultSyms=*/0);
2115 memIndices.push_back(
2116 AffineApplyOp::create(b, loc, lbs[d], regionSymbols));
2117 }
2118 // The fast buffer is copied into at location zero; addressing is relative.
2119 bufIndices.push_back(zeroIndex);
2120
2121 // Record the offsets since they are needed to remap the memory accesses of
2122 // the original memref further below.
2123 fastBufOffsets.push_back(lbs[d].getResult(0));
2124 }
2125
2126 // The faster memory space buffer.
2127 Value fastMemRef;
2128
2129 // Check if a buffer was already created.
2130 bool existingBuf = fastBufferMap.count(memref) > 0;
2131 if (!existingBuf) {
2132 AffineMap fastBufferLayout = b.getMultiDimIdentityMap(rank);
2133 auto fastMemRefType =
2134 MemRefType::get(fastBufferShape, memRefType.getElementType(),
2135 fastBufferLayout, copyOptions.fastMemorySpace);
2136
2137 // Create the fast memory space buffer just before the 'affine.for'
2138 // operation.
2139 fastMemRef =
2140 memref::AllocOp::create(prologue, loc, fastMemRefType).getResult();
2141 // Record it.
2142 fastBufferMap[memref] = fastMemRef;
2143 // fastMemRefType is a constant shaped memref.
2144 auto maySizeInBytes = getIntOrFloatMemRefSizeInBytes(fastMemRefType);
2145 // We don't account for things of unknown size.
2146 *sizeInBytes = maySizeInBytes.value_or(0);
2147
2148 LLVM_DEBUG(emitRemarkForBlock(*block)
2149 << "Creating fast buffer of type " << fastMemRefType
2150 << " and size " << llvm::divideCeil(*sizeInBytes, 1024)
2151 << " KiB\n");
2152 } else {
2153 // Reuse the one already created.
2154 fastMemRef = fastBufferMap[memref];
2155 }
2156
2157 auto numElementsSSA = arith::ConstantIndexOp::create(top, loc, *numElements);
2158
2159 Value dmaStride;
2160 Value numEltPerDmaStride;
2161 if (copyOptions.generateDma) {
2162 SmallVector<StrideInfo, 4> dmaStrideInfos;
2163 getMultiLevelStrides(region, fastBufferShape, &dmaStrideInfos);
2164
2165 // TODO: use all stride levels once DmaStartOp is extended for
2166 // multi-level strides.
2167 if (dmaStrideInfos.size() > 1) {
2168 LDBG() << "Only up to one level of stride supported";
2169 return failure();
2170 }
2171
2172 if (!dmaStrideInfos.empty()) {
2173 dmaStride =
2174 arith::ConstantIndexOp::create(top, loc, dmaStrideInfos[0].stride);
2175 numEltPerDmaStride = arith::ConstantIndexOp::create(
2176 top, loc, dmaStrideInfos[0].numEltPerStride);
2177 }
2178 }
2179
2180 // Create fully composed affine maps for each memref.
2181 auto memAffineMap = b.getMultiDimIdentityMap(memIndices.size());
2182 fullyComposeAffineMapAndOperands(&memAffineMap, &memIndices);
2183 auto bufAffineMap = b.getMultiDimIdentityMap(bufIndices.size());
2184 fullyComposeAffineMapAndOperands(&bufAffineMap, &bufIndices);
2185
2186 if (!copyOptions.generateDma) {
2187 // Point-wise copy generation.
2188 auto copyNest =
2189 generatePointWiseCopy(loc, memref, fastMemRef, lbMaps,
2190 /*lbOperands=*/regionSymbols, ubMaps,
2191 /*ubOperands=*/regionSymbols, fastBufOffsets,
2192 /*isCopyOut=*/region.isWrite(), b);
2193
2194 // Record this so that we can skip it from yet another copy.
2195 copyNests.insert(copyNest);
2196
2197 // Since new ops are being appended (for copy out's), adjust the end to
2198 // mark end of block range being processed if necessary.
2199 if (region.isWrite() && isCopyOutAtEndOfBlock)
2200 *nEnd = Block::iterator(copyNest.getOperation());
2201 } else {
2202 // DMA generation.
2203 // Create a tag (single element 1-d memref) for the DMA.
2204 auto tagMemRefType = MemRefType::get({1}, top.getIntegerType(32), {},
2205 copyOptions.tagMemorySpace);
2206 auto tagMemRef = memref::AllocOp::create(prologue, loc, tagMemRefType);
2207
2208 SmallVector<Value, 4> tagIndices({zeroIndex});
2209 auto tagAffineMap = b.getMultiDimIdentityMap(tagIndices.size());
2210 fullyComposeAffineMapAndOperands(&tagAffineMap, &tagIndices);
2211 if (!region.isWrite()) {
2212 // DMA non-blocking read from original buffer to fast buffer.
2213 AffineDmaStartOp::create(b, loc, memref, memAffineMap, memIndices,
2214 fastMemRef, bufAffineMap, bufIndices, tagMemRef,
2215 tagAffineMap, tagIndices, numElementsSSA,
2216 dmaStride, numEltPerDmaStride);
2217 } else {
2218 // DMA non-blocking write from fast buffer to the original memref.
2219 auto op = AffineDmaStartOp::create(
2220 b, loc, fastMemRef, bufAffineMap, bufIndices, memref, memAffineMap,
2221 memIndices, tagMemRef, tagAffineMap, tagIndices, numElementsSSA,
2222 dmaStride, numEltPerDmaStride);
2223 // Since new ops may be appended at 'end' (for outgoing DMAs), adjust the
2224 // end to mark end of block range being processed.
2225 if (isCopyOutAtEndOfBlock)
2226 *nEnd = Block::iterator(op.getOperation());
2227 }
2228
2229 // Matching DMA wait to block on completion; tag always has a 0 index.
2230 AffineDmaWaitOp::create(b, loc, tagMemRef, tagAffineMap, zeroIndex,
2231 numElementsSSA);
2232
2233 // Generate dealloc for the tag.
2234 auto tagDeallocOp = memref::DeallocOp::create(epilogue, loc, tagMemRef);
2235 if (*nEnd == end && isCopyOutAtEndOfBlock)
2236 // Since new ops are being appended (for outgoing DMAs), adjust the end to
2237 // mark end of range of the original.
2238 *nEnd = Block::iterator(tagDeallocOp.getOperation());
2239 }
2240
2241 // Generate dealloc for the buffer.
2242 if (!existingBuf) {
2243 auto bufDeallocOp = memref::DeallocOp::create(epilogue, loc, fastMemRef);
2244 // When generating pointwise copies, `nEnd' has to be set to deallocOp on
2245 // the fast buffer (since it marks the new end insertion point).
2246 if (!copyOptions.generateDma && *nEnd == end && isCopyOutAtEndOfBlock)
2247 *nEnd = Block::iterator(bufDeallocOp.getOperation());
2248 }
2249
2250 // Replace all uses of the old memref with the faster one while remapping
2251 // access indices (subtracting out lower bound offsets for each dimension).
2252 // Ex: to replace load %A[%i, %j] with load %Abuf[%i - %iT, %j - %jT],
2253 // index remap will be (%i, %j) -> (%i - %iT, %j - %jT),
2254 // i.e., affine.apply (d0, d1, d2, d3) -> (d2-d0, d3-d1) (%iT, %jT, %i, %j),
2255 // and (%iT, %jT) will be the 'extraOperands' for 'rep all memref uses with'.
2256 // d2, d3 correspond to the original indices (%i, %j).
2257 SmallVector<AffineExpr, 4> remapExprs;
2258 remapExprs.reserve(rank);
2259 for (unsigned i = 0; i < rank; i++) {
2260 // The starting operands of indexRemap will be regionSymbols (the symbols on
2261 // which the memref region is parametric); then those corresponding to
2262 // the memref's original indices follow.
2263 auto dimExpr = b.getAffineDimExpr(regionSymbols.size() + i);
2264 remapExprs.push_back(dimExpr - fastBufOffsets[i]);
2265 }
2266 auto indexRemap = AffineMap::get(regionSymbols.size() + rank, 0, remapExprs,
2267 b.getContext());
2268
2269 // Record the begin since it may be invalidated by memref replacement.
2270 Block::iterator prevOfBegin;
2271 bool isBeginAtStartOfBlock = (begin == block->begin());
2272 if (!isBeginAtStartOfBlock)
2273 prevOfBegin = std::prev(begin);
2274
2275 auto userFilterFn = [&](Operation *user) {
2276 auto *ancestorUser = block->findAncestorOpInBlock(*user);
2277 return ancestorUser && !ancestorUser->isBeforeInBlock(&*begin) &&
2278 !lastCopyOp->isBeforeInBlock(ancestorUser);
2279 };
2280
2281 // *Only* those uses within the range [begin, end) of 'block' are replaced.
2282 (void)replaceAllMemRefUsesWith(memref, fastMemRef,
2283 /*extraIndices=*/{}, indexRemap,
2284 /*extraOperands=*/regionSymbols,
2285 /*symbolOperands=*/{}, userFilterFn);
2286
2287 *nBegin = isBeginAtStartOfBlock ? block->begin() : std::next(prevOfBegin);
2288
2289 return success();
2290}
2291
2292/// Construct the memref region to just include the entire memref. Returns false
2293/// dynamic shaped memref's for now. `numParamLoopIVs` is the number of
2294/// enclosing loop IVs of `op` (starting from the outermost) that the region
2295/// is parametric on.
2296static bool getFullMemRefAsRegion(Operation *op, unsigned numParamLoopIVs,
2297 MemRefRegion *region) {
2298 unsigned rank;
2299 if (auto loadOp = dyn_cast<AffineLoadOp>(op)) {
2300 rank = loadOp.getMemRefType().getRank();
2301 region->memref = loadOp.getMemRef();
2302 region->setWrite(false);
2303 } else if (auto storeOp = dyn_cast<AffineStoreOp>(op)) {
2304 rank = storeOp.getMemRefType().getRank();
2305 region->memref = storeOp.getMemRef();
2306 region->setWrite(true);
2307 } else {
2308 assert(false && "expected load or store op");
2309 return false;
2310 }
2311 auto memRefType = cast<MemRefType>(region->memref.getType());
2312 if (!memRefType.hasStaticShape())
2313 return false;
2314
2315 auto *regionCst = region->getConstraints();
2316
2317 // Just get the first numSymbols IVs, which the memref region is parametric
2318 // on.
2320 getAffineForIVs(*op, &ivs);
2321 ivs.resize(numParamLoopIVs);
2322 SmallVector<Value, 4> symbols;
2323 extractForInductionVars(ivs, &symbols);
2324 *regionCst = FlatAffineValueConstraints(rank, numParamLoopIVs, 0);
2325 regionCst->setValues(rank, rank + numParamLoopIVs, symbols);
2326
2327 // Memref dim sizes provide the bounds.
2328 for (unsigned d = 0; d < rank; d++) {
2329 auto dimSize = memRefType.getDimSize(d);
2330 assert(dimSize > 0 && "filtered dynamic shapes above");
2331 regionCst->addBound(BoundType::LB, d, 0);
2332 regionCst->addBound(BoundType::UB, d, dimSize - 1);
2333 }
2334 return true;
2335}
2336
2337LogicalResult
2338mlir::affine::affineDataCopyGenerate(Block::iterator begin, Block::iterator end,
2339 const AffineCopyOptions &copyOptions,
2340 std::optional<Value> filterMemRef,
2341 DenseSet<Operation *> &copyNests) {
2342 if (begin == end)
2343 return success();
2344
2345 assert(begin->getBlock() == std::prev(end)->getBlock() &&
2346 "Inconsistent block begin/end args");
2347 assert(end != end->getBlock()->end() && "end can't be the block terminator");
2348
2349 Block *block = begin->getBlock();
2350
2351 // Copies will be generated for this depth, i.e., symbolic in all loops
2352 // surrounding the this block range.
2353 unsigned copyDepth = getNestingDepth(&*begin);
2354
2355 LDBG() << "Generating copies at depth " << copyDepth;
2356 LDBG() << "from begin: "
2357 << OpWithFlags(&*begin, OpPrintingFlags().skipRegions());
2358 LDBG() << "to inclusive end: "
2359 << OpWithFlags(&*std::prev(end), OpPrintingFlags().skipRegions());
2360
2361 // List of memory regions to copy for. We need a map vector to have a
2362 // guaranteed iteration order to write test cases. CHECK-DAG doesn't help here
2363 // since the alloc's for example are identical except for the SSA id.
2364 SmallMapVector<Value, std::unique_ptr<MemRefRegion>, 4> readRegions;
2365 SmallMapVector<Value, std::unique_ptr<MemRefRegion>, 4> writeRegions;
2366
2367 // Map from original memref's to the fast buffers that their accesses are
2368 // replaced with.
2369 DenseMap<Value, Value> fastBufferMap;
2370
2371 // To check for errors when walking the block.
2372 bool error = false;
2373
2374 // Walk this range of operations to gather all memory regions.
2375 block->walk(begin, end, [&](Operation *opInst) {
2376 Value memref;
2377 MemRefType memrefType;
2378 // Gather regions to allocate to buffers in faster memory space.
2379 if (auto loadOp = dyn_cast<AffineLoadOp>(opInst)) {
2380 memref = loadOp.getMemRef();
2381 memrefType = loadOp.getMemRefType();
2382 } else if (auto storeOp = dyn_cast<AffineStoreOp>(opInst)) {
2383 memref = storeOp.getMemRef();
2384 memrefType = storeOp.getMemRefType();
2385 }
2386 // Not an affine.load/store op.
2387 if (!memref)
2388 return;
2389
2390 if ((filterMemRef.has_value() && filterMemRef != memref) ||
2391 (isa_and_nonnull<IntegerAttr>(memrefType.getMemorySpace()) &&
2392 memrefType.getMemorySpaceAsInt() != copyOptions.slowMemorySpace))
2393 return;
2394
2395 if (!memref.getParentRegion()->isAncestor(block->getParent())) {
2396 LDBG() << "memref definition is inside of the depth at "
2397 << "which copy-in/copy-out would happen";
2398 return;
2399 }
2400
2401 // Compute the MemRefRegion accessed.
2402 auto region = std::make_unique<MemRefRegion>(opInst->getLoc());
2403 if (failed(region->compute(opInst, copyDepth, /*sliceState=*/nullptr,
2404 /*addMemRefDimBounds=*/false))) {
2405 LDBG() << "Error obtaining memory region: semi-affine maps?";
2406 LDBG() << "over-approximating to the entire memref";
2407 if (!getFullMemRefAsRegion(opInst, copyDepth, region.get())) {
2408 LDBG() << "non-constant memref sizes not yet supported";
2409 error = true;
2410 return;
2411 }
2412 }
2413
2414 // Each memref has a single buffer associated with it irrespective of how
2415 // many load's and store's happen on it.
2416 // TODO: in the future, when regions don't intersect and satisfy
2417 // other properties (based on load/store regions), we could consider
2418 // multiple buffers per memref.
2419
2420 // Add to the appropriate region if it's not already in it, or take a
2421 // bounding box union with the existing one if it's already in there.
2422 // Note that a memref may have both read and write regions - so update the
2423 // region in the other list if one exists (write in case of read and vice
2424 // versa) since there is a single bounding box for a memref across all reads
2425 // and writes that happen on it.
2426
2427 // Attempts to update; returns true if 'region' exists in targetRegions.
2428 auto updateRegion =
2429 [&](const SmallMapVector<Value, std::unique_ptr<MemRefRegion>, 4>
2430 &targetRegions) {
2431 const auto *const it = targetRegions.find(region->memref);
2432 if (it == targetRegions.end())
2433 return false;
2434
2435 // Perform a union with the existing region.
2436 if (failed(it->second->unionBoundingBox(*region))) {
2437 LDBG() << "Memory region bounding box failed; "
2438 << "over-approximating to the entire memref";
2439 // If the union fails, we will overapproximate.
2440 if (!getFullMemRefAsRegion(opInst, copyDepth, region.get())) {
2441 LDBG() << "non-constant memref sizes not yet supported";
2442 error = true;
2443 return true;
2444 }
2445 it->second->getConstraints()->clearAndCopyFrom(
2446 *region->getConstraints());
2447 } else {
2448 // Union was computed and stored in 'it->second': copy to 'region'.
2449 region->getConstraints()->clearAndCopyFrom(
2450 *it->second->getConstraints());
2451 }
2452 return true;
2453 };
2454
2455 bool existsInRead = updateRegion(readRegions);
2456 if (error)
2457 return;
2458 bool existsInWrite = updateRegion(writeRegions);
2459 if (error)
2460 return;
2461
2462 // Finally add it to the region list.
2463 if (region->isWrite() && !existsInWrite) {
2464 writeRegions[region->memref] = std::move(region);
2465 } else if (!region->isWrite() && !existsInRead) {
2466 readRegions[region->memref] = std::move(region);
2467 }
2468 });
2469
2470 if (error) {
2471 LDBG() << "copy generation failed for one or more memref's in this block";
2472 return failure();
2473 }
2474
2475 uint64_t totalCopyBuffersSizeInBytes = 0;
2476 bool ret = true;
2477 auto processRegions =
2478 [&](const SmallMapVector<Value, std::unique_ptr<MemRefRegion>, 4>
2479 &regions) {
2480 for (const auto &regionEntry : regions) {
2481 // For each region, hoist copy in/out past all hoistable
2482 // 'affine.for's.
2483 Block::iterator copyInPlacementStart, copyOutPlacementStart;
2484 Block *copyPlacementBlock;
2486 *regionEntry.second, *block, begin, end, &copyPlacementBlock,
2487 &copyInPlacementStart, &copyOutPlacementStart);
2488
2489 uint64_t sizeInBytes;
2490 Block::iterator nBegin, nEnd;
2491 LogicalResult iRet = generateCopy(
2492 *regionEntry.second, block, begin, end, copyPlacementBlock,
2493 copyInPlacementStart, copyOutPlacementStart, copyOptions,
2494 fastBufferMap, copyNests, &sizeInBytes, &nBegin, &nEnd);
2495 if (succeeded(iRet)) {
2496 // begin/end could have been invalidated, and need update.
2497 begin = nBegin;
2498 end = nEnd;
2499 totalCopyBuffersSizeInBytes += sizeInBytes;
2500 }
2501 ret = ret & succeeded(iRet);
2502 }
2503 };
2504 processRegions(readRegions);
2505 processRegions(writeRegions);
2506
2507 if (!ret) {
2508 LDBG() << "copy generation failed for one or more memref's in this block";
2509 return failure();
2510 }
2511
2512 // For a range of operations, a note will be emitted at the caller.
2513 AffineForOp forOp;
2514 if (llvm::DebugFlag && (forOp = dyn_cast<AffineForOp>(&*begin))) {
2515 LLVM_DEBUG(forOp.emitRemark()
2516 << llvm::divideCeil(totalCopyBuffersSizeInBytes, 1024)
2517 << " KiB of copy buffers in fast memory space for this block");
2518 }
2519
2520 if (totalCopyBuffersSizeInBytes > copyOptions.fastMemCapacityBytes) {
2521 block->getParentOp()->emitWarning(
2522 "total size of all copy buffers' for this block exceeds fast memory "
2523 "capacity");
2524 }
2525
2526 return success();
2527}
2528
2529// A convenience version of affineDataCopyGenerate for all ops in the body of
2530// an AffineForOp.
2531LogicalResult mlir::affine::affineDataCopyGenerate(
2532 AffineForOp forOp, const AffineCopyOptions &copyOptions,
2533 std::optional<Value> filterMemRef, DenseSet<Operation *> &copyNests) {
2534 return affineDataCopyGenerate(forOp.getBody()->begin(),
2535 std::prev(forOp.getBody()->end()), copyOptions,
2536 filterMemRef, copyNests);
2537}
2538
2539LogicalResult mlir::affine::generateCopyForMemRegion(
2540 const MemRefRegion &memrefRegion, Operation *analyzedOp,
2541 const AffineCopyOptions &copyOptions, CopyGenerateResult &result) {
2542 Block *block = analyzedOp->getBlock();
2543 auto begin = analyzedOp->getIterator();
2544 auto end = std::next(begin);
2545 DenseMap<Value, Value> fastBufferMap;
2546 DenseSet<Operation *> copyNests;
2547
2548 auto err = generateCopy(memrefRegion, block, begin, end, block, begin, end,
2549 copyOptions, fastBufferMap, copyNests,
2550 &result.sizeInBytes, &begin, &end);
2551 if (failed(err))
2552 return err;
2553
2554 const auto &en = fastBufferMap.find(memrefRegion.memref);
2555 // In some cases (empty loops), no copy generation would have happened.
2556 if (en == fastBufferMap.end())
2557 return failure();
2558 result.alloc = en->second.getDefiningOp();
2559 assert(result.alloc && "fast buffer expected to be locally allocated");
2560 assert(copyNests.size() <= 1 && "At most one copy nest is expected.");
2561 result.copyNest = copyNests.empty() ? nullptr : *copyNests.begin();
2562 return success();
2563}
2564
2565/// Gathers all AffineForOps in 'block' at 'currLoopDepth' in 'depthToLoops'.
2566static void
2567gatherLoopsInBlock(Block *block, unsigned currLoopDepth,
2568 std::vector<SmallVector<AffineForOp, 2>> &depthToLoops) {
2569 // Add a new empty level to output if it doesn't exist level already.
2570 assert(currLoopDepth <= depthToLoops.size() && "Unexpected currLoopDepth");
2571 if (currLoopDepth == depthToLoops.size())
2572 depthToLoops.emplace_back();
2573
2574 for (auto &op : *block) {
2575 if (auto forOp = dyn_cast<AffineForOp>(op)) {
2576 depthToLoops[currLoopDepth].push_back(forOp);
2577 gatherLoopsInBlock(forOp.getBody(), currLoopDepth + 1, depthToLoops);
2578 }
2579 }
2580}
2581
2582/// Gathers all AffineForOps in 'func.func' grouped by loop depth.
2583void mlir::affine::gatherLoops(
2584 func::FuncOp func, std::vector<SmallVector<AffineForOp, 2>> &depthToLoops) {
2585 for (auto &block : func)
2586 gatherLoopsInBlock(&block, /*currLoopDepth=*/0, depthToLoops);
2587
2588 // Remove last loop level from output since it's empty.
2589 if (!depthToLoops.empty()) {
2590 assert(depthToLoops.back().empty() && "Last loop level is not empty?");
2591 depthToLoops.pop_back();
2592 }
2593}
2594
2595AffineForOp mlir::affine::createCanonicalizedAffineForOp(
2596 OpBuilder b, Location loc, ValueRange lbOperands, AffineMap lbMap,
2597 ValueRange ubOperands, AffineMap ubMap, int64_t step) {
2598 SmallVector<Value, 4> lowerOperands(lbOperands);
2599 SmallVector<Value, 4> upperOperands(ubOperands);
2600
2601 fullyComposeAffineMapAndOperands(&lbMap, &lowerOperands);
2602 canonicalizeMapAndOperands(&lbMap, &lowerOperands);
2603 lbMap = removeDuplicateExprs(lbMap);
2604 fullyComposeAffineMapAndOperands(&ubMap, &upperOperands);
2605 canonicalizeMapAndOperands(&ubMap, &upperOperands);
2606 ubMap = removeDuplicateExprs(ubMap);
2607
2608 return AffineForOp::create(b, loc, lowerOperands, lbMap, upperOperands, ubMap,
2609 step);
2610}
2611
2612/// Creates an AffineIfOp that encodes the conditional to choose between
2613/// the constant trip count version and an unknown trip count version of this
2614/// nest of loops. This is used to separate partial and full tiles if `loops`
2615/// has the intra-tile loops. The affine.if op is inserted at the builder
2616/// insertion point of `b`.
2618 OpBuilder b) {
2619 if (loops.empty())
2620 return nullptr;
2621
2622 auto *context = loops[0].getContext();
2623
2626 llvm::append_range(ops, loops);
2627 (void)getIndexSet(ops, &cst);
2628
2629 // Remove constraints that are independent of these loop IVs.
2630 cst.removeIndependentConstraints(/*pos=*/0, /*num=*/loops.size());
2631
2632 // Construct the constraint set representing the guard for full tiles. The
2633 // lower bound (and upper bound) corresponding to the full tile should be
2634 // larger (and resp. smaller) than any other lower (or upper bound).
2635 SmallVector<int64_t, 8> fullTileLb, fullTileUb;
2636 for (auto loop : loops) {
2637 (void)loop;
2638 // TODO: Non-unit stride is not an issue to generalize to.
2639 assert(loop.getStepAsInt() == 1 && "point loop step expected to be one");
2640 // Mark everything symbols for the purpose of finding a constant diff pair.
2641 cst.setDimSymbolSeparation(/*newSymbolCount=*/cst.getNumDimAndSymbolVars() -
2642 1);
2643 unsigned fullTileLbPos, fullTileUbPos;
2644 if (!((IntegerRelation)cst)
2645 .getConstantBoundOnDimSize(0, /*lb=*/nullptr,
2646 /*boundFloorDivisor=*/nullptr,
2647 /*ub=*/nullptr, &fullTileLbPos,
2648 &fullTileUbPos)) {
2649 LDBG() << "Can't get constant diff pair for a loop";
2650 return nullptr;
2651 }
2652
2653 SmallVector<unsigned, 4> lbIndices, ubIndices;
2654 cst.getLowerAndUpperBoundIndices(/*pos=*/0, &lbIndices, &ubIndices);
2655
2656 auto fLb = cst.getInequality(fullTileLbPos);
2657 auto fUb = cst.getInequality(fullTileUbPos);
2658 fullTileLb.assign(fLb.begin(), fLb.end());
2659 fullTileUb.assign(fUb.begin(), fUb.end());
2660
2661 // Full tile lower bound should be >= than any other lower bound.
2662 for (auto lbIndex : lbIndices)
2663 for (unsigned i = 0, e = cst.getNumCols(); i < e; ++i)
2664 cst.atIneq(lbIndex, i) = fullTileLb[i] - cst.atIneq(lbIndex, i);
2665
2666 // Full tile upper bound should be <= any other upper bound.
2667 for (auto ubIndex : ubIndices)
2668 for (unsigned i = 0, e = cst.getNumCols(); i < e; ++i)
2669 cst.atIneq(ubIndex, i) -= fullTileUb[i];
2670
2671 cst.removeVar(0);
2672 }
2673
2674 // The previous step leads to all zeros for the full tile lb and ub position
2675 // itself; remove those and any other duplicates / trivial redundancies.
2677
2678 // Turn everything into dims conservatively since we earlier turned all
2679 // trailing ids past point loop IV into symbols. Some of these could be outer
2680 // loop IVs; we'll canonicalize anyway.
2682
2683 IntegerSet ifCondSet = cst.getAsIntegerSet(context);
2684 // ifCondSet can be null if cst was empty -- this can happen if all loops
2685 // in the nest have constant trip counts.
2686 if (!ifCondSet)
2687 return nullptr;
2688
2689 SmallVector<Value, 4> setOperands;
2690 cst.getValues(0, cst.getNumDimAndSymbolVars(), &setOperands);
2691 canonicalizeSetAndOperands(&ifCondSet, &setOperands);
2692 return AffineIfOp::create(b, loops[0].getLoc(), ifCondSet, setOperands,
2693 /*withElseRegion=*/true);
2694}
2695
2696/// Create the full tile loop nest (along with its body).
2697static LogicalResult
2699 SmallVectorImpl<AffineForOp> &fullTileLoops, OpBuilder b) {
2700 fullTileLoops.reserve(inputNest.size());
2701
2702 // For each loop in the original nest identify a lower/upper bound pair such
2703 // that their difference is a constant.
2705 for (auto loop : inputNest) {
2706 // TODO: straightforward to generalize to a non-unit stride.
2707 if (loop.getStepAsInt() != 1) {
2708 LDBG() << "[tile separation] non-unit stride not implemented";
2709 return failure();
2710 }
2711 SmallVector<Operation *, 1> loopOp{loop.getOperation()};
2712 (void)getIndexSet(loopOp, &cst);
2713 // We will mark everything other than this loop IV as symbol for getting a
2714 // pair of <lb, ub> with a constant difference.
2716 unsigned lbPos, ubPos;
2717 if (!((IntegerRelation)cst)
2718 .getConstantBoundOnDimSize(/*pos=*/0, /*lb=*/nullptr,
2719 /*boundFloorDivisor=*/nullptr,
2720 /*ub=*/nullptr, &lbPos, &ubPos) ||
2721 lbPos == ubPos) {
2722 LDBG() << "[tile separation] Can't get constant diff / "
2723 << "equalities not yet handled";
2724 return failure();
2725 }
2726
2727 // Set all variables as dimensions uniformly since some of those marked as
2728 // symbols above could be outer loop IVs (corresponding tile space IVs).
2729 cst.setDimSymbolSeparation(/*newSymbolCount=*/0);
2730
2731 AffineValueMap lbVmap, ubVmap;
2732 cst.getIneqAsAffineValueMap(/*pos=*/0, lbPos, lbVmap, b.getContext());
2733 cst.getIneqAsAffineValueMap(/*pos=*/0, ubPos, ubVmap, b.getContext());
2734 AffineForOp fullTileLoop = createCanonicalizedAffineForOp(
2735 b, loop.getLoc(), lbVmap.getOperands(), lbVmap.getAffineMap(),
2736 ubVmap.getOperands(), ubVmap.getAffineMap());
2737 b = OpBuilder::atBlockTerminator(fullTileLoop.getBody());
2738 fullTileLoops.push_back(fullTileLoop);
2739 }
2740
2741 // Add the body for the full tile loop nest.
2742 IRMapping operandMap;
2743 for (const auto &loopEn : llvm::enumerate(inputNest))
2744 operandMap.map(loopEn.value().getInductionVar(),
2745 fullTileLoops[loopEn.index()].getInductionVar());
2746 b = OpBuilder::atBlockTerminator(fullTileLoops.back().getBody());
2747 for (auto &op : inputNest.back().getBody()->without_terminator())
2748 b.clone(op, operandMap);
2749 return success();
2750}
2751
2752LogicalResult
2753mlir::affine::separateFullTiles(MutableArrayRef<AffineForOp> inputNest,
2754 SmallVectorImpl<AffineForOp> *fullTileNest) {
2755 if (inputNest.empty())
2756 return success();
2757
2758 auto firstLoop = inputNest[0];
2759
2760 // Each successive for op has to be nested in the other.
2761 auto prevLoop = firstLoop;
2762 for (auto loop : inputNest.drop_front(1)) {
2763 assert(loop->getParentOp() == prevLoop && "input not contiguously nested");
2764 prevLoop = loop;
2765 }
2766
2767 // Create the full tile loop nest.
2768 SmallVector<AffineForOp, 4> fullTileLoops;
2769 OpBuilder b(firstLoop);
2770 if (failed(createFullTiles(inputNest, fullTileLoops, b))) {
2771 if (!fullTileLoops.empty())
2772 fullTileLoops.front().erase();
2773 return failure();
2774 }
2775
2776 // Create and insert the version select right before the root of the nest.
2777 b = OpBuilder(firstLoop);
2778 AffineIfOp ifOp = createSeparationCondition(inputNest, b);
2779 if (!ifOp) {
2780 fullTileLoops.front().erase();
2781 LDBG() << "All tiles are full tiles, or failure creating "
2782 << "separation condition";
2783 return failure();
2784 }
2785
2786 // Move the full tile into the then block.
2787 Block *thenBlock = ifOp.getThenBlock();
2788 AffineForOp outermostFullTileLoop = fullTileLoops[0];
2789 thenBlock->getOperations().splice(
2790 std::prev(thenBlock->end()),
2791 outermostFullTileLoop->getBlock()->getOperations(),
2792 Block::iterator(outermostFullTileLoop));
2793
2794 // Move the partial tile into the else block. The partial tile is the same as
2795 // the original loop nest.
2796 Block *elseBlock = ifOp.getElseBlock();
2797 elseBlock->getOperations().splice(std::prev(elseBlock->end()),
2798 firstLoop->getBlock()->getOperations(),
2799 Block::iterator(firstLoop));
2800
2801 if (fullTileNest)
2802 *fullTileNest = std::move(fullTileLoops);
2803
2804 return success();
2805}
2806
2807LogicalResult affine::coalescePerfectlyNestedAffineLoops(AffineForOp op) {
2808 LogicalResult result(failure());
2810 getPerfectlyNestedLoops(loops, op);
2811 if (loops.size() <= 1)
2812 return success();
2813
2814 // Look for a band of loops that can be coalesced, i.e. perfectly nested
2815 // loops with bounds defined above some loop.
2816 // 1. For each loop, find above which parent loop its operands are
2817 // defined.
2818 SmallVector<unsigned> operandsDefinedAbove(loops.size());
2819 for (unsigned i = 0, e = loops.size(); i < e; ++i) {
2820 operandsDefinedAbove[i] = i;
2821 for (unsigned j = 0; j < i; ++j) {
2822 if (areValuesDefinedAbove(loops[i].getOperands(), loops[j].getRegion())) {
2823 operandsDefinedAbove[i] = j;
2824 break;
2825 }
2826 }
2827 }
2828
2829 // 2. Identify bands of loops such that the operands of all of them are
2830 // defined above the first loop in the band. Traverse the nest bottom-up
2831 // so that modifications don't invalidate the inner loops.
2832 for (unsigned end = loops.size(); end > 0; --end) {
2833 unsigned start = 0;
2834 for (; start < end - 1; ++start) {
2835 auto maxPos =
2836 *std::max_element(std::next(operandsDefinedAbove.begin(), start),
2837 std::next(operandsDefinedAbove.begin(), end));
2838 if (maxPos > start)
2839 continue;
2840 assert(maxPos == start &&
2841 "expected loop bounds to be known at the start of the band");
2842 auto band = llvm::MutableArrayRef(loops.data() + start, end - start);
2843 if (succeeded(coalesceLoops(band)))
2844 result = success();
2845 break;
2846 }
2847 // If a band was found and transformed, keep looking at the loops above
2848 // the outermost transformed loop.
2849 if (start != end - 1)
2850 end = start + 1;
2851 }
2852 return result;
2853}
2854
2856 int64_t count = 0;
2857 Operation *currentOp = operand.getOwner();
2858 while (auto loopOp = currentOp->getParentOfType<LoopLikeOpInterface>()) {
2859 if (!loopOp.isDefinedOutsideOfLoop(operand.get()))
2860 break;
2861 currentOp = loopOp;
2862 count++;
2863 }
2864 return count;
2865}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its the output argument nEnd is set *to the new end sizeInBytes is set to the size of the fast buffer *allocated *static LogicalResult generateCopy(const MemRefRegion &region, Block *block, Block::iterator begin, Block::iterator end, Block *copyPlacementBlock, Block::iterator copyInPlacementStart, Block::iterator copyOutPlacementStart, const AffineCopyOptions &copyOptions, DenseMap< Value, Value > &fastBufferMap, DenseSet< Operation * > &copyNests, uint64_t *sizeInBytes, Block::iterator *nBegin, Block::iterator *nEnd)
static LogicalResult performPreTilingChecks(MutableArrayRef< AffineForOp > input, ArrayRef< t > tileSizes)
Check if the input nest is supported for tiling and whether tiling would be legal or not.
static void constructParametricallyTiledIndexSetHyperRect(MutableArrayRef< AffineForOp > origLoops, MutableArrayRef< AffineForOp > newLoops, ArrayRef< Value > tileSizes)
Constructs and sets new loop bounds after tiling for the case of hyper-rectangular index sets,...
fullyComposeAffineMapAndOperands & fastBufMap
static InFlightDiagnostic emitRemarkForBlock(Block &block)
static void constructTiledLoopNest(MutableArrayRef< AffineForOp > origLoops, AffineForOp rootAffineForOp, unsigned width, MutableArrayRef< AffineForOp > tiledLoops)
Constructs tiled loop nest, without setting the loop bounds and move the body of the original loop ne...
static bool getFullMemRefAsRegion(Operation *op, unsigned numParamLoopIVs, MemRefRegion *region)
Construct the memref region to just include the entire memref.
static bool checkLoopInterchangeDependences(const std::vector< SmallVector< DependenceComponent, 2 > > &depCompsVec, ArrayRef< AffineForOp > loops, ArrayRef< unsigned > loopPermMap)
static LogicalResult checkIfHyperRectangular(MutableArrayRef< AffineForOp > input)
Checks whether a loop nest is hyper-rectangular or not.
static void findHighestBlockForPlacement(const MemRefRegion &region, Block &block, Block::iterator &begin, Block::iterator &end, Block **copyPlacementBlock, Block::iterator *copyInPlacementStart, Block::iterator *copyOutPlacementStart)
Given a memref region, determine the lowest depth at which transfers can be placed for it,...
static void moveLoopBodyImpl(AffineForOp src, AffineForOp dest, Block::iterator loc)
Move the loop body of AffineForOp 'src' from 'src' into the specified location in destination's body,...
static void setInterTileBoundsParametric(OpBuilder &b, AffineForOp origLoop, AffineForOp newLoop, Value tileSize)
Set lower and upper bounds of inter-tile loops for parametric tiling.
static void setIntraTileBoundsParametric(OpBuilder &b, AffineForOp origLoop, AffineForOp newInterTileLoop, AffineForOp newIntraTileLoop, Value tileSize)
Set lower and upper bounds of intra-tile loops for parametric tiling.
static AffineMap getMaxWithLowerBound(AffineForOp forOp, AffineMap map, SmallVectorImpl< Value > &operands)
Returns the max of the bound given by map applied to operands and the lower bound of forOp,...
static LogicalResult createFullTiles(MutableArrayRef< AffineForOp > inputNest, SmallVectorImpl< AffineForOp > &fullTileLoops, OpBuilder b)
Create the full tile loop nest (along with its body).
static AffineForOp generateShiftedLoop(AffineMap lbMap, AffineMap ubMap, const std::vector< std::pair< uint64_t, ArrayRef< Operation * > > > &opGroupQueue, unsigned offset, AffineForOp srcForOp, OpBuilder b)
Generates an affine.for op with the specified lower and upper bounds while generating the right IV re...
static void getMultiLevelStrides(const MemRefRegion &region, ArrayRef< int64_t > bufferShape, SmallVectorImpl< StrideInfo > *strideInfos)
Returns striding information for a copy/transfer of this region with potentially multiple striding le...
static void constructTiledIndexSetHyperRect(MutableArrayRef< AffineForOp > origLoops, MutableArrayRef< AffineForOp > newLoops, ArrayRef< unsigned > tileSizes)
Constructs and sets new loop bounds after tiling for the case of hyper-rectangular index sets,...
static LogicalResult generateCleanupLoopForUnroll(AffineForOp forOp, uint64_t unrollFactor)
Helper to generate cleanup loop for unroll or unroll-and-jam when the trip count is not a multiple of...
static bool areInnerBoundsInvariant(AffineForOp forOp)
Check if all control operands of all loops are defined outside of forOp and return false if not.
static void moveLoopBody(AffineForOp src, AffineForOp dest)
Move the loop body of AffineForOp 'src' from 'src' to the start of dest body.
static AffineIfOp createSeparationCondition(MutableArrayRef< AffineForOp > loops, OpBuilder b)
Creates an AffineIfOp that encodes the conditional to choose between the constant trip count version ...
auto load
return copyNestRoot
static void gatherLoopsInBlock(Block *block, unsigned currLoopDepth, std::vector< SmallVector< AffineForOp, 2 > > &depthToLoops)
Gathers all AffineForOps in 'block' at 'currLoopDepth' in 'depthToLoops'.
static void getCleanupLoopLowerBound(AffineForOp forOp, unsigned unrollFactor, AffineMap &cleanupLbMap, SmallVectorImpl< Value > &cleanupLbOperands)
Computes the cleanup loop lower bound of the loop being unrolled with the specified unroll factor; th...
Definition LoopUtils.cpp:45
static void augmentMapAndBounds(OpBuilder &b, Value iv, AffineMap *map, SmallVector< Value, 4 > *operands, int64_t offset=0)
static SmallVector< AffineForOp, 8 > stripmineSink(AffineForOp forOp, uint64_t factor, ArrayRef< AffineForOp > targets)
static void replaceIterArgsAndYieldResults(AffineForOp forOp)
Helper to replace uses of loop carried values (iter_args) and loop yield values while promoting singl...
fastBufExprs
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
AffineMap shiftDims(unsigned shift, unsigned offset=0) const
Replace dims[offset ... numDims) by dims[offset + shift ... shift + numDims).
Definition AffineMap.h:269
unsigned getNumSymbols() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
unsigned getNumInputs() const
AffineMap shiftSymbols(unsigned shift, unsigned offset=0) const
Replace symbols[offset ... numSymbols) by symbols[offset + shift ... shift + numSymbols).
Definition AffineMap.h:282
AffineExpr getResult(unsigned idx) const
Block represents an ordered list of Operations.
Definition Block.h:34
OpListType::iterator iterator
Definition Block.h:165
Operation * findAncestorOpInBlock(Operation &op)
Returns 'op' if 'op' lies in this block, or otherwise finds the ancestor operation of 'op' that lies ...
Definition Block.cpp:74
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
RetT walk(FnT &&callback)
Walk all nested operations, blocks (including this block) or regions, depending on the type of callba...
Definition Block.h:318
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
iterator end()
Definition Block.h:169
iterator begin()
Definition Block.h:168
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
AffineMap getDimIdentityMap()
Definition Builders.cpp:392
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
IntegerSet getAsIntegerSet(MLIRContext *context) const
Returns the constraint system as an integer set.
void getValues(unsigned start, unsigned end, SmallVectorImpl< Value > *values) const
Returns the Values associated with variables in range [start, end).
This class allows control over how the GreedyPatternRewriteDriver works.
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:65
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
IRValueT get() const
Return the current value being used by this operand.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class represents a diagnostic that is inflight and set to be reported.
An integer set representing a conjunction of one or more affine equalities and inequalities.
Definition IntegerSet.h:44
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
Definition Builders.h:255
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
This class represents an operand of an operation.
Definition Value.h:256
Set of flags used to control the behavior of the various IR print methods (e.g.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1171
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
InFlightDiagnostic emitWarning(const Twine &message={})
Emit a warning about this operation, reporting up to any diagnostic handlers that may be listening.
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
void setOperands(ValueRange operands)
Replace the current operands of this operation with the ones provided in 'operands'.
Operation * clone(IRMapping &mapper, const CloneOptions &options=CloneOptions::all())
Create a deep copy of this operation, remapping any operands that use values outside of the operation...
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
InFlightDiagnostic emitRemark(const Twine &message={})
Emit a remark about this operation, reporting up to any diagnostic handlers that may be listening.
ParentT getParentOfType()
Find the first parent operation of the given type, or nullptr if there is no ancestor operation.
Definition Region.h:206
MLIRContext * getContext() const
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
Type getType() const
Return the type of this value.
Definition Value.h:105
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
AffineBound represents a lower or upper bound in the for operation.
Definition AffineOps.h:216
Value getOperand(unsigned idx)
Definition AffineOps.h:222
An AffineValueMap is an affine map plus its ML value operands and results for analysis purposes.
ArrayRef< Value > getOperands() const
FlatAffineValueConstraints is an extension of FlatLinearValueConstraints with helper functions for Af...
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
An IntegerRelation represents the set of points from a PresburgerSpace that satisfy a list of affine ...
void removeIndependentConstraints(unsigned pos, unsigned num)
Removes constraints that are independent of (i.e., do not have a coefficient) variables in the range ...
void removeTrivialRedundancy()
Removes duplicate constraints, trivially true constraints, and constraints that can be detected as re...
ArrayRef< DynamicAPInt > getInequality(unsigned idx) const
DynamicAPInt atIneq(unsigned i, unsigned j) const
Returns the value at the specified inequality row and column.
bool isHyperRectangular(unsigned pos, unsigned num) const
Returns true if the set can be trivially detected as being hyper-rectangular on the specified contigu...
void setDimSymbolSeparation(unsigned newSymbolCount)
Changes the partition between dimensions and symbols.
unsigned getNumCols() const
Returns the number of columns in the constraint system.
void getLowerAndUpperBoundIndices(unsigned pos, SmallVectorImpl< unsigned > *lbIndices, SmallVectorImpl< unsigned > *ubIndices, SmallVectorImpl< unsigned > *eqIndices=nullptr, unsigned offset=0, unsigned num=0) const
Gather positions of all lower and upper bounds of the variable at pos, and optionally any equalities ...
void removeVar(VarKind kind, unsigned pos)
Removes variables of the specified kind with the specified pos (or within the specified range) from t...
LogicalResult loopUnrollFull(AffineForOp forOp)
Unrolls this for operation completely if the trip count is known to be constant.
LogicalResult promoteIfSingleIteration(AffineForOp forOp)
Promotes the loop body of a AffineForOp to its containing block if the loop was known to have a singl...
LogicalResult loopUnrollJamUpToFactor(AffineForOp forOp, uint64_t unrollJamFactor)
Unrolls and jams this loop by the specified factor or by the trip count (if constant),...
void extractForInductionVars(ArrayRef< AffineForOp > forInsts, SmallVectorImpl< Value > *ivs)
Extracts the induction variables from a list of AffineForOps and places them in the output argument i...
LogicalResult loopUnrollByFactor(AffineForOp forOp, uint64_t unrollFactor, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn=nullptr, bool cleanUpUnroll=false)
Unrolls this for operation by the specified unroll factor.
void getEnclosingAffineOps(Operation &op, SmallVectorImpl< Operation * > *ops)
Populates 'ops' with affine operations enclosing op ordered from outermost to innermost while stoppin...
Definition Utils.cpp:880
LogicalResult getIndexSet(MutableArrayRef< Operation * > ops, FlatAffineValueConstraints *domain)
Builds a system of constraints with dimensional variables corresponding to the loop IVs of the forOps...
void getPerfectlyNestedLoops(SmallVectorImpl< AffineForOp > &nestedLoops, AffineForOp root)
Get perfectly nested sequence of loops starting at root of loop nest (the first op being another Affi...
LogicalResult affineForOpBodySkew(AffineForOp forOp, ArrayRef< uint64_t > shifts, bool unrollPrologueEpilogue=false)
Skew the operations in an affine.for's body with the specified operation-wise shifts.
void getTripCountMapAndOperands(AffineForOp forOp, AffineMap *map, SmallVectorImpl< Value > *operands)
Returns the trip count of the loop as an affine map with its corresponding operands if the latter is ...
bool isValidLoopInterchangePermutation(ArrayRef< AffineForOp > loops, ArrayRef< unsigned > loopPermMap)
Checks if the loop interchange permutation 'loopPermMap', of the perfectly nested sequence of loops i...
void getSupportedReductions(AffineForOp forOp, SmallVectorImpl< LoopReduction > &supportedReductions)
Populate supportedReductions with descriptors of the supported reductions.
void canonicalizeMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands)
Modifies both map and operands in-place so as to:
LogicalResult loopUnrollUpToFactor(AffineForOp forOp, uint64_t unrollFactor)
Unrolls this loop by the specified unroll factor or its trip count, whichever is lower.
void getDependenceComponents(AffineForOp forOp, unsigned maxLoopDepth, std::vector< SmallVector< DependenceComponent, 2 > > *depCompsVec)
Returns in 'depCompsVec', dependence components for dependences between all load and store ops in loo...
unsigned permuteLoops(ArrayRef< AffineForOp > inputNest, ArrayRef< unsigned > permMap)
Performs a loop permutation on a perfectly nested loop nest inputNest (where the contained loops appe...
LogicalResult loopUnrollJamByFactor(AffineForOp forOp, uint64_t unrollJamFactor)
Unrolls and jams this loop by the specified factor.
LogicalResult tilePerfectlyNestedParametric(MutableArrayRef< AffineForOp > input, ArrayRef< Value > tileSizes, SmallVectorImpl< AffineForOp > *tiledNest=nullptr)
Tiles the specified band of perfectly nested loops creating tile-space loops and intra-tile loops,...
void fullyComposeAffineMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands, bool composeAffineMin=false)
Given an affine map map and its input operands, this method composes into map, maps of AffineApplyOps...
void canonicalizeSetAndOperands(IntegerSet *set, SmallVectorImpl< Value > *operands)
Canonicalizes an integer set the same way canonicalizeMapAndOperands does for affine maps.
bool isPerfectlyNested(ArrayRef< AffineForOp > loops)
Returns true if loops is a perfectly nested loop nest, where loops appear in it from outermost to inn...
void getAffineForIVs(Operation &op, SmallVectorImpl< AffineForOp > *loops)
Populates 'loops' with IVs of the affine.for ops surrounding 'op' ordered from the outermost 'affine....
Definition Utils.cpp:866
uint64_t getLargestDivisorOfTripCount(AffineForOp forOp)
Returns the greatest known integral divisor of the trip count.
std::optional< uint64_t > getIntOrFloatMemRefSizeInBytes(MemRefType memRefType)
Returns the size of a memref with element type int or float in bytes if it's statically shaped,...
Definition Utils.cpp:1476
int64_t numEnclosingInvariantLoops(OpOperand &operand)
Performs explicit copying for the contiguous sequence of operations in the block iterator range [‘beg...
unsigned getNestingDepth(Operation *op)
Returns the nesting depth of this operation, i.e., the number of loops surrounding this operation.
Definition Utils.cpp:2093
bool isOpwiseShiftValid(AffineForOp forOp, ArrayRef< uint64_t > shifts)
Checks where SSA dominance would be violated if a for op's body operations are shifted by the specifi...
SmallVector< SmallVector< AffineForOp, 8 >, 8 > tile(ArrayRef< AffineForOp > forOps, ArrayRef< uint64_t > sizes, ArrayRef< AffineForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
AffineForOp sinkSequentialLoops(AffineForOp forOp)
LogicalResult tilePerfectlyNested(MutableArrayRef< AffineForOp > input, ArrayRef< unsigned > tileSizes, SmallVectorImpl< AffineForOp > *tiledNest=nullptr)
Tiles the specified band of perfectly nested loops creating tile-space loops and intra-tile loops.
void interchangeLoops(AffineForOp forOpA, AffineForOp forOpB)
Performs loop interchange on 'forOpA' and 'forOpB'.
Value getReductionOp(AtomicRMWKind op, OpBuilder &builder, Location loc, Value lhs, Value rhs)
Returns the value obtained by applying the reduction operation kind associated with a binary AtomicRM...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
AffineMap simplifyAffineMap(AffineMap map)
Simplifies an affine map by simplifying its underlying AffineExpr results.
void replaceAllUsesInRegionWith(Value orig, Value replacement, Region &region)
Replace all uses of orig within the given region with replacement.
void generateUnrolledLoop(Block *loopBodyBlock, Value iv, uint64_t unrollFactor, function_ref< Value(unsigned, Value, OpBuilder)> ivRemapFn, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn, ValueRange iterArgs, ValueRange yieldedValues, IRMapping *clonedToSrcOpsMap=nullptr, SmallVectorImpl< SmallVector< Value > > *unrolledYieldedValues=nullptr)
Generate unrolled copies of an scf loop's 'loopBodyBlock', with 'iterArgs' and 'yieldedValues' as the...
Definition Utils.cpp:295
AffineMap removeDuplicateExprs(AffineMap map)
Returns a map with the same dimension and symbol count as map, but whose results are the unique affin...
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
LogicalResult applyOpPatternsGreedily(ArrayRef< Operation * > ops, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr, bool *allErased=nullptr)
Rewrite the specified ops by repeatedly applying the highest benefit patterns in a greedy worklist dr...
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
Definition AffineExpr.h:327
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
bool areValuesDefinedAbove(Range values, Region &limit)
Check if all values in the provided range are defined above the limit region.
Definition RegionUtils.h:26
@ ExistingAndNewOps
Only pre-existing and newly created ops are processed.
AffineExpr simplifyAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols)
Simplify an affine expression by flattening and some amount of simple analysis.
LogicalResult coalesceLoops(MutableArrayRef< scf::ForOp > loops)
Replace a perfect nest of "for" loops with a single linearized loop.
Definition Utils.cpp:1099
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
int64_t stride
int64_t numEltPerStride
void walk(Operation *op)
SmallVector< std::pair< Block::iterator, Block::iterator > > subBlocks
Explicit copy / DMA generation options for mlir::affineDataCopyGenerate.
Definition LoopUtils.h:155
std::optional< int64_t > ub
std::optional< int64_t > lb
A description of a (parallelizable) reduction in an affine loop.
A region of a memref's data space; this is typically constructed by analyzing load/store op's on this...
Definition Utils.h:493
std::optional< int64_t > getConstantBoundingSizeAndShape(SmallVectorImpl< int64_t > *shape=nullptr, SmallVectorImpl< AffineMap > *lbs=nullptr) const
Returns a constant upper bound on the number of elements in this region if bounded by a known constan...
Definition Utils.cpp:1173
bool isWrite() const
Definition Utils.h:541
void getLowerAndUpperBound(unsigned pos, AffineMap &lbMap, AffineMap &ubMap) const
Gets the lower and upper bound map for the dimensional variable at pos.
Definition Utils.cpp:1229
void setWrite(bool flag)
Definition Utils.h:542
FlatAffineValueConstraints * getConstraints()
Definition Utils.h:539
Value memref
Memref that this region corresponds to.
Definition Utils.h:574
Location loc
If there is more than one load/store op associated with the region, the location information would co...
Definition Utils.h:581
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.