25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/SmallVectorExtras.h"
29#include "llvm/Support/DebugLog.h"
34#define DEBUG_TYPE "scf-utils"
39 bool replaceIterOperandsUsesInLoop) {
45 assert(loopNest.size() <= 10 &&
46 "exceeded recursion limit when yielding value from loop nest");
78 if (loopNest.size() == 1) {
80 cast<scf::ForOp>(*loopNest.back().replaceWithAdditionalYields(
81 rewriter, newIterOperands, replaceIterOperandsUsesInLoop,
83 return {innerMostLoop};
93 innerNewBBArgs, newYieldValuesFn,
94 replaceIterOperandsUsesInLoop);
95 return llvm::map_to_vector(
96 newLoopNest.front().getResults().take_back(innerNewBBArgs.size()),
99 scf::ForOp outerMostLoop =
100 cast<scf::ForOp>(*loopNest.front().replaceWithAdditionalYields(
101 rewriter, newIterOperands, replaceIterOperandsUsesInLoop, fn));
102 newLoopNest.insert(newLoopNest.begin(), outerMostLoop);
119 func::CallOp *callOp) {
120 assert(!funcName.empty() &&
"funcName cannot be empty");
134 ValueRange outlinedValues(captures.getArrayRef());
141 outlinedFuncArgTypes.push_back(arg.getType());
142 outlinedFuncArgLocs.push_back(arg.getLoc());
144 for (
Value value : outlinedValues) {
145 outlinedFuncArgTypes.push_back(value.getType());
146 outlinedFuncArgLocs.push_back(value.getLoc());
148 FunctionType outlinedFuncType =
149 FunctionType::get(rewriter.
getContext(), outlinedFuncArgTypes,
152 func::FuncOp::create(rewriter, loc, funcName, outlinedFuncType);
153 Block *outlinedFuncBody = outlinedFunc.addEntryBlock();
158 auto outlinedFuncBlockArgs = outlinedFuncBody->
getArguments();
163 originalBlock, outlinedFuncBody,
164 outlinedFuncBlockArgs.take_front(numOriginalBlockArguments));
167 func::ReturnOp::create(rewriter, loc, originalTerminator->
getResultTypes(),
174 ®ion, region.
begin(),
175 TypeRange{outlinedFuncArgTypes}.take_front(numOriginalBlockArguments),
177 .take_front(numOriginalBlockArguments));
182 llvm::append_range(callValues, newBlock->
getArguments());
183 llvm::append_range(callValues, outlinedValues);
184 auto call = func::CallOp::create(rewriter, loc, outlinedFunc, callValues);
193 rewriter.
clone(*originalTerminator, bvm);
194 rewriter.
eraseOp(originalTerminator);
199 for (
auto it : llvm::zip(outlinedValues, outlinedFuncBlockArgs.take_back(
200 outlinedValues.size()))) {
201 Value orig = std::get<0>(it);
202 Value repl = std::get<1>(it);
211 return outlinedFunc->isProperAncestor(opOperand.
getOwner());
219 func::FuncOp *thenFn, StringRef thenFnName,
220 func::FuncOp *elseFn, StringRef elseFnName) {
223 FailureOr<func::FuncOp> outlinedFuncOpOrFailure;
224 if (thenFn && !ifOp.getThenRegion().empty()) {
226 rewriter, loc, ifOp.getThenRegion(), thenFnName);
227 if (failed(outlinedFuncOpOrFailure))
229 *thenFn = *outlinedFuncOpOrFailure;
231 if (elseFn && !ifOp.getElseRegion().empty()) {
233 rewriter, loc, ifOp.getElseRegion(), elseFnName);
234 if (failed(outlinedFuncOpOrFailure))
236 *elseFn = *outlinedFuncOpOrFailure;
243 assert(rootOp !=
nullptr &&
"Root operation must not be a nullptr.");
244 bool rootEnclosesPloops =
false;
246 for (
Block &block : region.getBlocks()) {
249 rootEnclosesPloops |= enclosesPloops;
250 if (
auto ploop = dyn_cast<scf::ParallelOp>(op)) {
251 rootEnclosesPloops =
true;
260 return rootEnclosesPloops;
268 assert(divisor > 0 &&
"expected positive divisor");
270 "expected integer or index-typed value");
272 Value divisorMinusOneCst = arith::ConstantOp::create(
274 Value divisorCst = arith::ConstantOp::create(
276 Value sum = arith::AddIOp::create(builder, loc, dividend, divisorMinusOneCst);
277 return arith::DivUIOp::create(builder, loc, sum, divisorCst);
287 "expected integer or index-typed value");
288 Value cstOne = arith::ConstantOp::create(
290 Value divisorMinusOne = arith::SubIOp::create(builder, loc, divisor, cstOne);
291 Value sum = arith::AddIOp::create(builder, loc, dividend, divisorMinusOne);
292 return arith::DivUIOp::create(builder, loc, sum, divisor);
296 Block *loopBodyBlock,
Value iv, uint64_t unrollFactor,
304 auto findOriginalSrcOp =
309 while (srcOp && clonedToSrcOpsMap.
contains(srcOp))
310 srcOp = clonedToSrcOpsMap.
lookup(srcOp);
320 annotateFn = noopAnnotateFn;
330 for (
unsigned i = 1; i < unrollFactor; i++) {
333 operandMap.
map(iterArgs, lastYielded);
338 Value ivUnroll = ivRemapFn(i, iv, builder);
339 operandMap.
map(iv, ivUnroll);
343 for (
auto it = loopBodyBlock->
begin(); it != std::next(srcBlockEnd); it++) {
346 annotateFn(i, clonedOp, builder);
347 if (clonedToSrcOpsMap)
348 clonedToSrcOpsMap->
map(clonedOp,
349 findOriginalSrcOp(srcOp, *clonedToSrcOpsMap));
353 for (
unsigned i = 0, e = lastYielded.size(); i < e; i++)
355 if (unrolledYieldedValues)
356 unrolledYieldedValues->emplace_back(lastYielded.begin(),
362 for (
auto it = loopBodyBlock->
begin(); it != std::next(srcBlockEnd); it++)
363 annotateFn(0, &*it, builder);
370FailureOr<std::pair<scf::ForOp, scf::ForOp>>
373 if (splitPoint.
getType() != forOp.getLowerBound().getType())
377 bool isUnsigned = forOp.getUnsignedCmp();
378 Value lbVal = forOp.getLowerBound();
379 Value ubVal = forOp.getUpperBound();
380 Value stepVal = forOp.getStep();
381 auto checkSplitPoint = [&](
auto getBound) -> LogicalResult {
382 auto lb = getBound(lbVal);
383 auto ub = getBound(ubVal);
384 auto step = getBound(stepVal);
385 auto split = getBound(splitPoint);
386 if ((lb && split && *lb > *split) || (split &&
ub && *split >= *
ub) ||
387 (step && *step <= 0))
389 if (lb && step && split && (*split - *lb) % *step != 0)
399 auto firstForOp = cast<scf::ForOp>(rewriter.
clone(*forOp));
400 auto secondForOp = cast<scf::ForOp>(rewriter.
clone(*forOp));
402 [&] { firstForOp.setUpperBound(splitPoint); });
404 [&] { secondForOp.setLowerBound(splitPoint); });
411 secondForOp->setOperands(secondForOp.getNumControlOperands(),
412 secondForOp.getInitArgs().size(),
413 firstForOp.getResults());
415 rewriter.
replaceOp(forOp, secondForOp.getResults());
417 return std::pair<scf::ForOp, scf::ForOp>{firstForOp, secondForOp};
423 scf::ForOp forOp, uint64_t unrollFactor,
425 bool shouldPromoteIfSingleIteration) {
426 assert(unrollFactor > 0 &&
"expected positive unroll factor");
429 if (llvm::hasSingleElement(forOp.getBody()->getOperations()))
436 auto loc = forOp.getLoc();
437 Value step = forOp.getStep();
438 Value upperBoundUnrolled;
440 bool generateEpilogueLoop =
true;
442 std::optional<APInt> constTripCount = forOp.getStaticTripCount();
452 constTripCount = std::nullopt;
453 if (constTripCount) {
455 bool isUnsignedLoop = forOp.getUnsignedCmp();
461 if (isUnsignedLoop) {
462 if (
auto intTy = dyn_cast<IntegerType>(forOp.getUpperBound().getType()))
463 if (intTy.getWidth() >= 64)
468 assert(apInt &&
"expected constant loop bound");
469 return isUnsignedLoop ?
static_cast<int64_t>(apInt->first.getZExtValue())
470 : apInt->first.getSExtValue();
472 int64_t lbCst = getLoopBound(forOp.getLowerBound());
473 int64_t ubCst = getLoopBound(forOp.getUpperBound());
474 int64_t stepCst = getLoopBound(step);
475 if (unrollFactor == 1) {
476 if (shouldPromoteIfSingleIteration && constTripCount->isOne() &&
477 failed(forOp.promoteIfSingleIteration(rewriter)))
482 uint64_t tripCount = constTripCount->getZExtValue();
483 uint64_t tripCountEvenMultiple = tripCount - tripCount % unrollFactor;
484 int64_t upperBoundUnrolledCst = lbCst + tripCountEvenMultiple * stepCst;
485 int64_t stepUnrolledCst = stepCst * unrollFactor;
488 generateEpilogueLoop = upperBoundUnrolledCst < ubCst;
489 if (generateEpilogueLoop)
490 upperBoundUnrolled = arith::ConstantOp::create(
493 upperBoundUnrolledCst));
495 upperBoundUnrolled = forOp.getUpperBound();
503 bool mainLoopHasNoIter = (tripCountEvenMultiple == 0);
504 bool stepUnchanged = (stepCst == stepUnrolledCst);
506 (mainLoopHasNoIter || stepUnchanged)
508 : arith::ConstantOp::create(boundsBuilder, loc,
510 step.
getType(), stepUnrolledCst));
515 auto lowerBound = forOp.getLowerBound();
516 auto upperBound = forOp.getUpperBound();
518 arith::SubIOp::create(boundsBuilder, loc, upperBound, lowerBound);
519 Value zero = arith::ConstantOp::create(
521 Value nonEmpty = arith::CmpIOp::create(boundsBuilder, loc,
522 forOp.getUnsignedCmp()
523 ? arith::CmpIPredicate::ult
524 : arith::CmpIPredicate::slt,
525 lowerBound, upperBound);
526 diff = arith::SelectOp::create(boundsBuilder, loc, nonEmpty, diff, zero);
529 Value unrollFactorCst = arith::ConstantOp::create(
533 arith::RemSIOp::create(boundsBuilder, loc, tripCount, unrollFactorCst);
535 Value tripCountEvenMultiple =
536 arith::SubIOp::create(boundsBuilder, loc, tripCount, tripCountRem);
538 upperBoundUnrolled = arith::AddIOp::create(
539 boundsBuilder, loc, lowerBound,
540 arith::MulIOp::create(boundsBuilder, loc, tripCountEvenMultiple, step));
543 arith::MulIOp::create(boundsBuilder, loc, step, unrollFactorCst);
549 if (generateEpilogueLoop) {
551 if (failed(splitLoops))
553 forOp = splitLoops->first;
554 scf::ForOp epilogueForOp = splitLoops->second;
555 if (!shouldPromoteIfSingleIteration ||
556 epilogueForOp.promoteIfSingleIteration(rewriter).failed())
559 forOp.setUpperBound(upperBoundUnrolled);
563 forOp.setStep(stepUnrolled);
565 auto iterArgs =
ValueRange(forOp.getRegionIterArgs());
566 auto yieldedValues = forOp.getBody()->getTerminator()->getOperands();
569 forOp.getBody(), forOp.getInductionVar(), unrollFactor,
572 auto stride = arith::MulIOp::create(
574 arith::ConstantOp::create(b, loc,
575 b.getIntegerAttr(iv.getType(), i)));
576 return arith::AddIOp::create(b, loc, iv, stride);
578 annotateFn, iterArgs, yieldedValues);
581 if (!shouldPromoteIfSingleIteration ||
582 forOp.promoteIfSingleIteration(rewriter).failed())
590 std::optional<APInt> mayBeConstantTripCount = forOp.getStaticTripCount();
591 if (!mayBeConstantTripCount.has_value())
593 const APInt &tripCount = *mayBeConstantTripCount;
594 if (tripCount.isZero())
596 if (tripCount.isOne())
597 return forOp.promoteIfSingleIteration(rewriter);
604 auto walkResult = forOp.walk([&](scf::ForOp innerForOp) {
605 if (!forOp.isDefinedOutsideOfLoop(innerForOp.getLowerBound()) ||
606 !forOp.isDefinedOutsideOfLoop(innerForOp.getUpperBound()) ||
607 !forOp.isDefinedOutsideOfLoop(innerForOp.getStep()))
612 return !walkResult.wasInterrupted();
617 uint64_t unrollJamFactor) {
618 assert(unrollJamFactor > 0 &&
"unroll jam factor should be positive");
620 if (unrollJamFactor == 1)
626 LDBG() <<
"failed to unroll and jam: inner bounds are not invariant";
631 if (forOp->getNumResults() > 0) {
632 LDBG() <<
"failed to unroll and jam: unsupported loop with results";
638 std::optional<APInt> tripCount = forOp.getStaticTripCount();
639 if (!tripCount.has_value()) {
641 LDBG() <<
"failed to unroll and jam: trip count could not be determined";
644 uint64_t tripCountValue = tripCount->getZExtValue();
645 if (tripCountValue == 0)
647 if (unrollJamFactor > tripCountValue) {
648 LDBG() <<
"unroll and jam factor is greater than trip count, set factor to "
651 unrollJamFactor = tripCountValue;
652 }
else if (tripCountValue % unrollJamFactor != 0) {
653 LDBG() <<
"failed to unroll and jam: unsupported trip count that is not a "
654 "multiple of unroll jam factor";
659 if (llvm::hasSingleElement(forOp.getBody()->getOperations()))
669 forOp.walk([&](scf::ForOp innerForOp) { innerLoops.push_back(innerForOp); });
680 for (scf::ForOp oldForOp : innerLoops) {
682 ValueRange oldIterOperands = oldForOp.getInits();
683 ValueRange oldIterArgs = oldForOp.getRegionIterArgs();
685 cast<scf::YieldOp>(oldForOp.getBody()->getTerminator()).getOperands();
688 for (
unsigned i = unrollJamFactor - 1; i >= 1; --i) {
689 dupIterOperands.append(oldIterOperands.begin(), oldIterOperands.end());
690 dupYieldOperands.append(oldYieldOperands.begin(), oldYieldOperands.end());
694 bool forOpReplaced = oldForOp == forOp;
695 scf::ForOp newForOp =
696 cast<scf::ForOp>(*oldForOp.replaceWithAdditionalYields(
697 rewriter, dupIterOperands,
false,
699 return dupYieldOperands;
701 newInnerLoops.push_back(newForOp);
706 ValueRange newIterArgs = newForOp.getRegionIterArgs();
707 unsigned oldNumIterArgs = oldIterArgs.size();
708 ValueRange newResults = newForOp.getResults();
709 unsigned oldNumResults = newResults.size() / unrollJamFactor;
710 assert(oldNumIterArgs == oldNumResults &&
711 "oldNumIterArgs must be the same as oldNumResults");
712 for (
unsigned i = unrollJamFactor - 1; i >= 1; --i) {
713 for (
unsigned j = 0;
j < oldNumIterArgs; ++
j) {
717 operandMaps[i - 1].map(newIterArgs[
j],
718 newIterArgs[i * oldNumIterArgs +
j]);
719 operandMaps[i - 1].map(newResults[
j],
720 newResults[i * oldNumResults +
j]);
727 int64_t step = forOp.getConstantStep()->getSExtValue();
729 forOp.getLoc(), forOp.getStep(),
731 forOp.getLoc(), rewriter.
getIndexAttr(unrollJamFactor)));
732 forOp.setStep(newStep);
733 auto forOpIV = forOp.getInductionVar();
736 for (
unsigned i = unrollJamFactor - 1; i >= 1; --i) {
737 for (
auto &subBlock : subBlocks) {
740 OpBuilder builder(subBlock.first->getBlock(), std::next(subBlock.second));
744 if (!forOpIV.use_empty()) {
749 builder.
createOrFold<arith::AddIOp>(forOp.getLoc(), forOpIV, ivTag);
750 operandMaps[i - 1].map(forOpIV, ivUnroll);
753 for (
auto it = subBlock.first; it != std::next(subBlock.second); ++it)
754 builder.
clone(*it, operandMaps[i - 1]);
757 for (
auto newForOp : newInnerLoops) {
758 unsigned oldNumIterOperands =
759 newForOp.getNumRegionIterArgs() / unrollJamFactor;
760 unsigned numControlOperands = newForOp.getNumControlOperands();
761 auto yieldOp = cast<scf::YieldOp>(newForOp.getBody()->getTerminator());
762 unsigned oldNumYieldOperands = yieldOp.getNumOperands() / unrollJamFactor;
763 assert(oldNumIterOperands == oldNumYieldOperands &&
764 "oldNumIterOperands must be the same as oldNumYieldOperands");
765 for (
unsigned j = 0;
j < oldNumIterOperands; ++
j) {
769 newForOp.setOperand(numControlOperands + i * oldNumIterOperands +
j,
770 operandMaps[i - 1].lookupOrDefault(
771 newForOp.getOperand(numControlOperands +
j)));
773 i * oldNumYieldOperands +
j,
774 operandMaps[i - 1].lookupOrDefault(yieldOp.getOperand(
j)));
780 (
void)forOp.promoteIfSingleIteration(rewriter);
788 Range normalizedLoopBounds;
794 normalizedLoopBounds.
size =
796 return normalizedLoopBounds;
808 bool isZeroBased =
false;
810 isZeroBased = lbCst.value() == 0;
812 bool isStepOne =
false;
814 isStepOne = stepCst.value() == 1;
818 "expected matching types");
823 if (isZeroBased && isStepOne)
824 return {lb,
ub, step};
834 newUpperBound = rewriter.
createOrFold<arith::CeilDivSIOp>(
842 return {newLowerBound, newUpperBound, newStep};
856 Value denormalizedIvVal =
863 if (
Operation *preservedUse = denormalizedIvVal.getDefiningOp()) {
864 preservedUses.insert(preservedUse);
873 if (
getType(origLb).isIndex()) {
877 Value denormalizedIv;
882 Value scaled = normalizedIv;
884 Value origStepValue =
886 scaled = arith::MulIOp::create(rewriter, loc, normalizedIv, origStepValue);
889 denormalizedIv = scaled;
892 denormalizedIv = arith::AddIOp::create(rewriter, loc, scaled, origLbValue);
901 assert(!values.empty() &&
"unexecpted empty array");
906 for (
auto v : values) {
916 assert(!values.empty() &&
"unexpected empty list");
922 std::optional<Value> productOf;
923 for (
auto v : values) {
925 if (vOne && vOne.value() == 1)
928 productOf = arith::MulIOp::create(rewriter, loc, productOf.value(), v)
934 productOf = arith::ConstantOp::create(
938 return productOf.value();
954 Operation *delinearizedOp = affine::AffineDelinearizeIndexOp::create(
955 rewriter, loc, linearizedIv, ubs);
956 auto resultVals = llvm::map_to_vector(
964 llvm::BitVector isUbOne(ubs.size());
965 for (
auto [
index,
ub] : llvm::enumerate(ubs)) {
967 if (ubCst && ubCst.value() == 1)
972 unsigned numLeadingOneUbs = 0;
973 for (
auto [
index,
ub] : llvm::enumerate(ubs)) {
974 if (!isUbOne.test(
index)) {
977 delinearizedIvs[
index] = arith::ConstantOp::create(
982 Value previous = linearizedIv;
983 for (
unsigned i = numLeadingOneUbs, e = ubs.size(); i < e; ++i) {
984 unsigned idx = ubs.size() - (i - numLeadingOneUbs) - 1;
985 if (i != numLeadingOneUbs && !isUbOne.test(idx + 1)) {
986 previous = arith::DivSIOp::create(rewriter, loc, previous, ubs[idx + 1]);
991 if (!isUbOne.test(idx)) {
992 iv = arith::RemSIOp::create(rewriter, loc, previous, ubs[idx]);
995 iv = arith::ConstantOp::create(
996 rewriter, loc, rewriter.
getZeroAttr(ubs[idx].getType()));
999 delinearizedIvs[idx] = iv;
1001 return {delinearizedIvs, preservedUsers};
1006 if (loops.size() < 2)
1009 scf::ForOp innermost = loops.back();
1010 scf::ForOp outermost = loops.front();
1014 for (
auto loop : loops) {
1016 if (step.value() == 0) {
1023 for (
auto loop : loops) {
1026 Value lb = loop.getLowerBound();
1027 Value ub = loop.getUpperBound();
1028 Value step = loop.getStep();
1034 newLoopRange.offset));
1036 newLoopRange.size));
1038 newLoopRange.stride));
1042 loop.getInductionVar(), lb, step);
1051 loops, [](
auto loop) {
return loop.getUpperBound(); });
1053 outermost.setUpperBound(upperBound);
1058 rewriter, loc, outermost.getInductionVar(), upperBounds);
1062 for (
int i = loops.size() - 1; i > 0; --i) {
1063 auto outerLoop = loops[i - 1];
1064 auto innerLoop = loops[i];
1066 Operation *innerTerminator = innerLoop.getBody()->getTerminator();
1067 auto yieldedVals = llvm::to_vector(innerTerminator->
getOperands());
1068 assert(llvm::equal(outerLoop.getRegionIterArgs(), innerLoop.getInitArgs()));
1069 for (
Value &yieldedVal : yieldedVals) {
1073 if (yieldedVal == innerLoop.getInductionVar()) {
1074 yieldedVal = delinearizeIvs[i];
1079 auto iter = llvm::find(innerLoop.getRegionIterArgs(), yieldedVal);
1080 if (iter != innerLoop.getRegionIterArgs().end()) {
1081 unsigned iterArgIndex = iter - innerLoop.getRegionIterArgs().begin();
1083 assert(iterArgIndex < innerLoop.getInitArgs().size());
1084 yieldedVal = innerLoop.getInitArgs()[iterArgIndex];
1087 rewriter.
eraseOp(innerTerminator);
1090 innerBlockArgs.push_back(delinearizeIvs[i]);
1091 llvm::append_range(innerBlockArgs, outerLoop.getRegionIterArgs());
1094 rewriter.
replaceOp(innerLoop, yieldedVals);
1100 if (loops.empty()) {
1103 IRRewriter rewriter(loops.front().getContext());
1108 LogicalResult
result(failure());
1118 for (
unsigned i = 0, e = loops.size(); i < e; ++i) {
1119 operandsDefinedAbove[i] = i;
1120 for (
unsigned j = 0;
j < i; ++
j) {
1122 loops[i].getUpperBound(),
1123 loops[i].getStep()};
1125 operandsDefinedAbove[i] =
j;
1136 iterArgChainStart[0] = 0;
1137 for (
unsigned i = 1, e = loops.size(); i < e; ++i) {
1139 iterArgChainStart[i] = i;
1140 auto outerloop = loops[i - 1];
1141 auto innerLoop = loops[i];
1142 if (outerloop.getNumRegionIterArgs() != innerLoop.getNumRegionIterArgs()) {
1145 if (!llvm::equal(outerloop.getRegionIterArgs(), innerLoop.getInitArgs())) {
1148 auto outerloopTerminator = outerloop.getBody()->getTerminator();
1149 if (!llvm::equal(outerloopTerminator->getOperands(),
1150 innerLoop.getResults())) {
1153 iterArgChainStart[i] = iterArgChainStart[i - 1];
1159 for (
unsigned end = loops.size(); end > 0; --end) {
1161 for (; start < end - 1; ++start) {
1163 *std::max_element(std::next(operandsDefinedAbove.begin(), start),
1164 std::next(operandsDefinedAbove.begin(), end));
1167 if (iterArgChainStart[end - 1] > start)
1176 if (start != end - 1)
1184 ArrayRef<std::vector<unsigned>> combinedDimensions) {
1190 auto sortedDimensions = llvm::to_vector<3>(combinedDimensions);
1191 for (
auto &dims : sortedDimensions)
1196 for (
unsigned i = 0, e = loops.getNumLoops(); i < e; ++i) {
1199 Value lb = loops.getLowerBound()[i];
1200 Value ub = loops.getUpperBound()[i];
1201 Value step = loops.getStep()[i];
1204 rewriter, loops.getLoc(), newLoopRange.size));
1215 for (
auto &sortedDimension : sortedDimensions) {
1217 for (
auto idx : sortedDimension) {
1218 newUpperBound = arith::MulIOp::create(rewriter, loc, newUpperBound,
1219 normalizedUpperBounds[idx]);
1221 lowerBounds.push_back(cst0);
1222 steps.push_back(cst1);
1223 upperBounds.push_back(newUpperBound);
1233 auto newPloop = scf::ParallelOp::create(
1234 rewriter, loc, lowerBounds, upperBounds, steps, loops.getInitVals(),
1236 for (unsigned i = 0, e = combinedDimensions.size(); i < e; ++i) {
1237 Value previous = ploopIVs[i];
1238 unsigned numberCombinedDimensions = combinedDimensions[i].size();
1240 for (unsigned j = numberCombinedDimensions - 1; j > 0; --j) {
1241 unsigned idx = combinedDimensions[i][j];
1244 Value iv = arith::RemSIOp::create(insideBuilder, loc, previous,
1245 normalizedUpperBounds[idx]);
1250 previous = arith::DivSIOp::create(insideBuilder, loc, previous,
1251 normalizedUpperBounds[idx]);
1255 unsigned idx = combinedDimensions[i][0];
1256 newIVs[idx] = previous;
1263 if (loops.getInitVals().empty())
1264 rewriter.eraseOp(newPloop.getBody()->getTerminator());
1265 rewriter.mergeBlocks(loops.getBody(), newPloop.getBody(), newIVs);
1267 rewriter.replaceOp(loops, newPloop);
1280 return op != inner.getOperation();
1283 LogicalResult status =
success();
1285 for (
auto &op : outer.getBody()->without_terminator()) {
1287 if (&op == inner.getOperation())
1290 if (forwardSlice.count(&op) > 0) {
1295 if (isa<scf::ForOp>(op))
1298 if (op.getNumRegions() > 0) {
1308 toHoist.push_back(&op);
1310 auto *outerForOp = outer.getOperation();
1311 for (
auto *op : toHoist)
1312 op->moveBefore(outerForOp);
1321 LogicalResult status =
success();
1322 const Loops &interTile = tileLoops.first;
1323 const Loops &intraTile = tileLoops.second;
1324 auto size = interTile.size();
1325 assert(size == intraTile.size());
1328 for (
unsigned s = 1; s < size; ++s)
1329 status = succeeded(status) ?
hoistOpsBetween(intraTile[0], intraTile[s])
1331 for (
unsigned s = 1; s < size; ++s)
1332 status = succeeded(status) ?
hoistOpsBetween(interTile[0], interTile[s])
1341template <
typename T>
1344 unsigned maxLoops = std::numeric_limits<unsigned>::max()) {
1345 for (
unsigned i = 0; i < maxLoops; ++i) {
1346 forOps.push_back(rootForOp);
1347 Block &body = rootForOp.getRegion().front();
1348 if (body.
begin() != std::prev(body.
end(), 2))
1351 rootForOp = dyn_cast<T>(&body.
front());
1359 auto originalStep = forOp.getStep();
1360 auto iv = forOp.getInductionVar();
1361 bool isUnsigned = forOp.getUnsignedCmp();
1364 forOp.setStep(arith::MulIOp::create(
b, forOp.getLoc(), originalStep, factor));
1367 for (
auto t : targets) {
1369 auto begin = t.getBody()->begin();
1370 auto nOps = t.getBody()->getOperations().size();
1374 Value stepped = arith::AddIOp::create(
b, t.getLoc(), iv, forOp.getStep());
1378 arith::MinUIOp::create(
b, t.getLoc(), forOp.getUpperBound(), stepped);
1381 arith::MinSIOp::create(
b, t.getLoc(), forOp.getUpperBound(), stepped);
1385 scf::ForOp::create(
b, t.getLoc(), iv,
ub, originalStep,
1386 t.getRegionIterArgs(),
1387 nullptr, isUnsigned);
1388 newForOp.getBody()->getOperations().splice(
1389 newForOp.getBody()->getOperations().begin(),
1390 t.getBody()->getOperations(), begin, std::next(begin, nOps - 1));
1392 newForOp.getRegion());
1395 if (!t.getInitArgs().empty()) {
1396 Operation *yieldOp = t.getBody()->getTerminator();
1397 yieldOp->
moveBefore(newForOp.getBody(), newForOp.getBody()->end());
1398 for (
auto [oldArg, newArg] :
1399 llvm::zip_equal(t.getRegionIterArgs(), newForOp.getRegionIterArgs()))
1401 b.setInsertionPointToEnd(t.getBody());
1402 scf::YieldOp::create(
b, t.getLoc(), newForOp.getResults());
1405 innerLoops.push_back(newForOp);
1416 for (
auto it : llvm::zip(forOps, sizes)) {
1417 auto step =
stripmineSink(std::get<0>(it), std::get<1>(it), currentTargets);
1418 res.push_back(step);
1419 currentTargets = step;
1428 res.push_back(llvm::getSingleElement(loops));
1436 forOps.reserve(sizes.size());
1438 if (forOps.size() < sizes.size())
1439 sizes = sizes.take_front(forOps.size());
1441 return ::tile(forOps, sizes, forOps.back());
1454 forOps.reserve(sizes.size());
1456 if (forOps.size() < sizes.size())
1457 sizes = sizes.take_front(forOps.size());
1464 tileSizes.reserve(sizes.size());
1465 for (
unsigned i = 0, e = sizes.size(); i < e; ++i) {
1466 assert(sizes[i] > 0 &&
"expected strictly positive size for strip-mining");
1468 auto forOp = forOps[i];
1470 auto loc = forOp.getLoc();
1471 Value diff = arith::SubIOp::create(builder, loc, forOp.getUpperBound(),
1472 forOp.getLowerBound());
1474 Value iterationsPerBlock =
1476 tileSizes.push_back(iterationsPerBlock);
1480 auto intraTile =
tile(forOps, tileSizes, forOps.back());
1481 TileLoops tileLoops = std::make_pair(forOps, intraTile);
1492 scf::ForallOp source,
1494 unsigned numTargetOuts =
target.getNumResults();
1495 unsigned numSourceOuts = source.getNumResults();
1499 llvm::append_range(fusedOuts,
target.getOutputs());
1500 llvm::append_range(fusedOuts, source.getOutputs());
1504 scf::ForallOp fusedLoop = scf::ForallOp::create(
1505 rewriter, source.getLoc(), source.getMixedLowerBound(),
1506 source.getMixedUpperBound(), source.getMixedStep(), fusedOuts,
1507 source.getMapping());
1511 mapping.
map(
target.getInductionVars(), fusedLoop.getInductionVars());
1512 mapping.
map(source.getInductionVars(), fusedLoop.getInductionVars());
1516 fusedLoop.getRegionIterArgs().take_front(numTargetOuts));
1517 mapping.
map(source.getRegionIterArgs(),
1518 fusedLoop.getRegionIterArgs().take_back(numSourceOuts));
1523 rewriter.
clone(op, mapping);
1524 for (
Operation &op : source.getBody()->without_terminator())
1525 rewriter.
clone(op, mapping);
1528 scf::InParallelOp targetTerm =
target.getTerminator();
1529 scf::InParallelOp sourceTerm = source.getTerminator();
1530 scf::InParallelOp fusedTerm = fusedLoop.getTerminator();
1532 for (
Operation &op : targetTerm.getYieldingOps())
1533 rewriter.
clone(op, mapping);
1534 for (
Operation &op : sourceTerm.getYieldingOps())
1535 rewriter.
clone(op, mapping);
1538 rewriter.
replaceOp(
target, fusedLoop.getResults().take_front(numTargetOuts));
1539 rewriter.
replaceOp(source, fusedLoop.getResults().take_back(numSourceOuts));
1547 assert(source.getUnsignedCmp() ==
target.getUnsignedCmp() &&
1548 "incompatible signedness");
1549 unsigned numTargetOuts =
target.getNumResults();
1550 unsigned numSourceOuts = source.getNumResults();
1554 llvm::append_range(fusedInitArgs,
target.getInitArgs());
1555 llvm::append_range(fusedInitArgs, source.getInitArgs());
1560 scf::ForOp fusedLoop = scf::ForOp::create(
1561 rewriter, source.getLoc(), source.getLowerBound(), source.getUpperBound(),
1562 source.getStep(), fusedInitArgs,
nullptr,
1563 source.getUnsignedCmp());
1567 mapping.
map(
target.getInductionVar(), fusedLoop.getInductionVar());
1569 fusedLoop.getRegionIterArgs().take_front(numTargetOuts));
1570 mapping.
map(source.getInductionVar(), fusedLoop.getInductionVar());
1571 mapping.
map(source.getRegionIterArgs(),
1572 fusedLoop.getRegionIterArgs().take_back(numSourceOuts));
1577 rewriter.
clone(op, mapping);
1578 for (
Operation &op : source.getBody()->without_terminator())
1579 rewriter.
clone(op, mapping);
1583 for (
Value operand :
target.getBody()->getTerminator()->getOperands())
1585 for (
Value operand : source.getBody()->getTerminator()->getOperands())
1587 if (!yieldResults.empty())
1588 scf::YieldOp::create(rewriter, source.getLoc(), yieldResults);
1591 rewriter.
replaceOp(
target, fusedLoop.getResults().take_front(numTargetOuts));
1592 rewriter.
replaceOp(source, fusedLoop.getResults().take_back(numSourceOuts));
1598 scf::ForallOp forallOp) {
1603 if (forallOp.isNormalized())
1607 auto loc = forallOp.getLoc();
1610 for (
auto [lb,
ub, step] : llvm::zip_equal(lbs, ubs, steps)) {
1611 Range normalizedLoopParams =
1613 newUbs.push_back(normalizedLoopParams.
size);
1619 auto normalizedForallOp = scf::ForallOp::create(
1620 rewriter, loc, newUbs, forallOp.getOutputs(), forallOp.getMapping(),
1624 normalizedForallOp.getBodyRegion(),
1625 normalizedForallOp.getBodyRegion().begin());
1627 rewriter.
eraseBlock(&normalizedForallOp.getBodyRegion().back());
1631 for (
auto [idx, iv] :
1632 llvm::enumerate(normalizedForallOp.getInductionVars())) {
1638 rewriter.
replaceOp(forallOp, normalizedForallOp);
1639 return normalizedForallOp;
1644 assert(!loops.empty() &&
"unexpected empty loop nest");
1645 if (loops.size() == 1)
1646 return isa_and_nonnull<scf::ForOp>(loops.front().getOperation());
1647 for (
auto [outerLoop, innerLoop] :
1648 llvm::zip_equal(loops.drop_back(), loops.drop_front())) {
1649 auto outerFor = dyn_cast_or_null<scf::ForOp>(outerLoop.getOperation());
1650 auto innerFor = dyn_cast_or_null<scf::ForOp>(innerLoop.getOperation());
1651 if (!outerFor || !innerFor)
1653 auto outerBBArgs = outerFor.getRegionIterArgs();
1654 auto innerIterArgs = innerFor.getInitArgs();
1655 if (outerBBArgs.size() != innerIterArgs.size())
1658 for (
auto [outerBBArg, innerIterArg] :
1659 llvm::zip_equal(outerBBArgs, innerIterArgs)) {
1660 if (!llvm::hasSingleElement(outerBBArg.getUses()) ||
1661 innerIterArg != outerBBArg)
1666 cast<scf::YieldOp>(outerFor.getBody()->getTerminator())->getOperands();
1667 ValueRange innerResults = innerFor.getResults();
1668 if (outerYields.size() != innerResults.size())
1670 for (
auto [outerYield, innerResult] :
1671 llvm::zip_equal(outerYields, innerResults)) {
1672 if (!llvm::hasSingleElement(innerResult.getUses()) ||
1673 outerYield != innerResult)
1682 std::optional<SmallVector<OpFoldResult>> loBnds = loopOp.getLoopLowerBounds();
1683 std::optional<SmallVector<OpFoldResult>> upBnds = loopOp.getLoopUpperBounds();
1684 std::optional<SmallVector<OpFoldResult>> steps = loopOp.getLoopSteps();
1685 if (!loBnds || !upBnds || !steps)
1688 for (
auto [lb,
ub, step] : llvm::zip(*loBnds, *upBnds, *steps)) {
1692 if (!lbCst || !ubCst || !stepCst)
1694 loopRanges.emplace_back(*lbCst, *ubCst, *stepCst);
1701 std::optional<SmallVector<OpFoldResult>> loBnds = loopOp.getLoopLowerBounds();
1702 std::optional<SmallVector<OpFoldResult>> upBnds = loopOp.getLoopUpperBounds();
1703 std::optional<SmallVector<OpFoldResult>> steps = loopOp.getLoopSteps();
1704 if (!loBnds || !upBnds || !steps)
1707 for (
auto [lb,
ub, step] : llvm::zip(*loBnds, *upBnds, *steps)) {
1713 tripCounts.push_back(*numIter);
1726 for (
auto [idx, reduction] : llvm::enumerate(reduceOp.getReductions())) {
1733 rewriter.
clone(reduceBodyOp, mapping);
1735 cast<scf::ReduceReturnOp>(reduceBlock.
getTerminator()).getResult());
1738 rewriter.
modifyOpInPlace(reduceOp, [&]() { reduceOp->setOperands(reduced); });
1746 const unsigned numLoops = op.getNumLoops();
1747 assert(llvm::none_of(unrollFactors, [](uint64_t f) {
return f == 0; }) &&
1748 "Expected positive unroll factors");
1749 assert((!unrollFactors.empty() && (unrollFactors.size() <= numLoops)) &&
1750 "Expected non-empty unroll factors of size <= to the number of loops");
1753 if (llvm::all_of(unrollFactors, [](uint64_t f) {
return f == 1; }))
1755 op,
"Unrolling not applied if all factors are 1");
1758 if (llvm::hasSingleElement(op.getBody()->getOperations()))
1763 const unsigned firstLoopDimIdx = numLoops - unrollFactors.size();
1768 if (tripCounts.empty())
1770 op,
"Failed to compute constant trip counts for the loop. Note that "
1771 "dynamic loop sizes are not supported.");
1773 for (
unsigned dimIdx = firstLoopDimIdx; dimIdx < numLoops; dimIdx++) {
1774 const uint64_t unrollFactor = unrollFactors[dimIdx - firstLoopDimIdx];
1775 if (tripCounts[dimIdx].urem(unrollFactor) != 0)
1777 op,
"Unroll factors don't divide the iteration space evenly");
1780 std::optional<SmallVector<OpFoldResult>> maybeFoldSteps = op.getLoopSteps();
1781 if (!maybeFoldSteps)
1784 for (
auto step : *maybeFoldSteps)
1789 auto reduceOp = cast<scf::ReduceOp>(op.getBody()->getTerminator());
1792 if (!llvm::all_of(usedByReductions, [&](
Value value) {
1793 return op.isDefinedOutsideOfLoop(value);
1796 op,
"Reduction functions using values defined in the loop are not "
1799 for (
unsigned dimIdx = firstLoopDimIdx; dimIdx < numLoops; dimIdx++) {
1800 const uint64_t unrollFactor = unrollFactors[dimIdx - firstLoopDimIdx];
1801 if (unrollFactor == 1)
1803 const size_t origStep = steps[dimIdx];
1804 const int64_t newStep = origStep * unrollFactor;
1807 auto yieldedValues = op.getBody()->getTerminator()->getOperands();
1812 op.getBody(), op.getInductionVars()[dimIdx], unrollFactor,
1815 const AffineExpr expr = b.getAffineDimExpr(0) + (origStep * i);
1817 b.getDimIdentityMap().dropResult(0).insertResult(expr, 0);
1818 return affine::AffineApplyOp::create(b, iv.getLoc(), map,
1821 annotateFn, iterArgs, yieldedValues, clonedToSrcOpsMap,
1832 op.getStepMutable()[dimIdx].assign(
static OpFoldResult getProductOfIndexes(RewriterBase &rewriter, Location loc, ArrayRef< OpFoldResult > values)
static LogicalResult tryIsolateBands(const TileLoops &tileLoops)
static void getPerfectlyNestedLoopsImpl(SmallVectorImpl< T > &forOps, T rootForOp, unsigned maxLoops=std::numeric_limits< unsigned >::max())
Collect perfectly nested loops starting from rootForOps.
static LogicalResult hoistOpsBetween(scf::ForOp outer, scf::ForOp inner)
static Range emitNormalizedLoopBoundsForIndexType(RewriterBase &rewriter, Location loc, OpFoldResult lb, OpFoldResult ub, OpFoldResult step)
static void combineUnrolledAssociativeReductions(RewriterBase &rewriter, scf::ReduceOp reduceOp, SmallVector< Value > reduced, ArrayRef< SmallVector< Value > > unrolledReduced)
Makes reduceOp reduce the values of all the copies of the unrolled loop body, combining unrolledReduc...
static Loops stripmineSink(scf::ForOp forOp, Value factor, ArrayRef< scf::ForOp > targets)
static Value ceilDivPositive(OpBuilder &builder, Location loc, Value dividend, int64_t divisor)
static Value getProductOfIntsOrIndexes(RewriterBase &rewriter, Location loc, ArrayRef< Value > values)
Helper function to multiply a sequence of values.
static std::pair< SmallVector< Value >, SmallPtrSet< Operation *, 2 > > delinearizeInductionVariable(RewriterBase &rewriter, Location loc, Value linearizedIv, ArrayRef< Value > ubs)
For each original loop, the value of the induction variable can be obtained by dividing the induction...
static void denormalizeInductionVariableForIndexType(RewriterBase &rewriter, Location loc, Value normalizedIv, OpFoldResult origLb, OpFoldResult origStep)
static bool areInnerBoundsInvariant(scf::ForOp forOp)
Check if bounds of all inner loops are defined outside of forOp and return false if not.
static int64_t product(ArrayRef< int64_t > vals)
static llvm::ManagedStatic< PassManagerOptions > options
Base type for affine expression.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
OpListType::iterator iterator
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgListType getArguments()
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
TypedAttr getZeroAttr(Type type)
MLIRContext * getContext() const
TypedAttr getOneAttr(Type type)
This is a utility class for mapping one set of IR entities to another.
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
auto lookup(T from) const
Lookup a mapped value within the map.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
bool contains(T from) const
Checks to see if a mapping for 'from' exists.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
This class represents a single result from folding an operation.
This class represents an operand of an operation.
This is a value defined by a result of an operation.
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
operand_type_range getOperandTypes()
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
void setOperands(ValueRange operands)
Replace the current operands of this operation with the ones provided in 'operands'.
result_range getResults()
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...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
BlockArgListType getArguments()
ParentT getParentOfType()
Find the first parent operation of the given type, or nullptr if there is no ancestor operation.
bool hasOneBlock()
Return true if this region has exactly one block.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseBlock(Block *block)
This method erases all operations in a block.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void replaceAllUsesExcept(Value from, Value to, Operation *exceptedUser)
Find uses of from and replace them with to except if the user is exceptedUser.
virtual void inlineBlockBefore(Block *source, Block *dest, Block::iterator before, ValueRange argValues={})
Inline the operations of block 'source' into block 'dest' before the given position.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
void inlineRegionBefore(Region ®ion, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
bool use_empty() const
Returns true if this value has no uses.
Type getType() const
Return the type of this value.
bool replaceUsesWithIf(Value newValue, function_ref< bool(OpOperand &)> shouldReplace)
Replace all uses of 'this' value with 'newValue' if the given callback returns true.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static WalkResult advance()
static WalkResult interrupt()
Specialization of arith.constant op that returns an integer of index type.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Operation * getOwner() const
Return the owner of this operand.
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
std::optional< llvm::APSInt > computeUbMinusLb(Value lb, Value ub, bool isSigned)
Helper function to compute the difference between two values.
Include the generated interface declarations.
void getPerfectlyNestedLoops(SmallVectorImpl< scf::ForOp > &nestedLoops, scf::ForOp root)
Get perfectly nested sequence of loops starting at root of loop nest (the first op being another Affi...
bool isPerfectlyNestedForLoops(MutableArrayRef< LoopLikeOpInterface > loops)
Check if the provided loops are perfectly nested for-loops.
FailureOr< UnrolledLoopInfo > loopUnrollByFactor(scf::ForOp forOp, uint64_t unrollFactor, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn=nullptr, bool shouldPromoteIfSingleIteration=true)
Unrolls this for operation by the specified unroll factor.
LogicalResult outlineIfOp(RewriterBase &b, scf::IfOp ifOp, func::FuncOp *thenFn, StringRef thenFnName, func::FuncOp *elseFn, StringRef elseFnName)
Outline the then and/or else regions of ifOp as follows:
void replaceAllUsesInRegionWith(Value orig, Value replacement, Region ®ion)
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...
SmallVector< scf::ForOp > replaceLoopNestWithNewYields(RewriterBase &rewriter, MutableArrayRef< scf::ForOp > loopNest, ValueRange newIterOperands, const NewYieldValuesFn &newYieldValuesFn, bool replaceIterOperandsUsesInLoop=true)
Update a perfectly nested loop nest to yield new values from the innermost loop and propagating it up...
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
std::function< SmallVector< Value >( OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
scf::ParallelOp collapseParallelLoops(RewriterBase &rewriter, scf::ParallelOp loops, ArrayRef< std::vector< unsigned > > combinedDimensions)
Take the ParallelLoop and for each set of dimension indices, combine them into a single dimension.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
LogicalResult coalescePerfectlyNestedSCFForLoops(scf::ForOp op)
Walk an affine.for to find a band to coalesce.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Value getValueOrCreateConstantIntOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
LogicalResult loopUnrollFull(scf::ForOp forOp)
Unrolls this loop completely.
llvm::SmallVector< llvm::APInt > getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp)
Get constant trip counts for each of the induction variables of the given loop operation.
std::pair< Loops, Loops > TileLoops
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::SmallVector< std::tuple< int64_t, int64_t, int64_t > > getConstLoopBounds(mlir::LoopLikeOpInterface loopOp)
Get constant loop bounds and steps for each of the induction variables of the given loop operation,...
llvm::SetVector< T, Vector, Set, N > SetVector
FailureOr< std::pair< scf::ForOp, scf::ForOp > > splitForOpAtPoint(RewriterBase &rewriter, scf::ForOp forOp, Value splitPoint)
Splits forOp into two consecutive loops at splitPoint: first: [lowerBound, splitPoint) second: [split...
std::optional< std::pair< APInt, bool > > getConstantAPIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
SliceOptions ForwardSliceOptions
Loops tilePerfectlyNested(scf::ForOp rootForOp, ArrayRef< Value > sizes)
Tile a nest of scf::ForOp loops rooted at rootForOp with the given (parametric) sizes.
LogicalResult loopUnrollJamByFactor(scf::ForOp forOp, uint64_t unrollFactor)
Unrolls and jams this scf.for operation by the specified unroll factor.
bool getInnermostParallelLoops(Operation *rootOp, SmallVectorImpl< scf::ParallelOp > &result)
Get a list of innermost parallel loops contained in rootOp.
bool isZeroInteger(OpFoldResult v)
Return "true" if v is an integer value/attribute with constant value 0.
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
FailureOr< scf::ParallelOp > parallelLoopUnrollByFactors(scf::ParallelOp op, ArrayRef< uint64_t > unrollFactors, RewriterBase &rewriter, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn=nullptr, IRMapping *clonedToSrcOpsMap=nullptr)
Unroll this scf::Parallel loop by the specified unroll factors.
void getUsedValuesDefinedAbove(Region ®ion, Region &limit, SetVector< Value > &values)
Fill values with a list of values defined at the ancestors of the limit region and used within region...
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
FailureOr< func::FuncOp > outlineSingleBlockRegion(RewriterBase &rewriter, Location loc, Region ®ion, StringRef funcName, func::CallOp *callOp=nullptr)
Outline a region with a single block into a new FuncOp.
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
bool areValuesDefinedAbove(Range values, Region &limit)
Check if all values in the provided range are defined above the limit region.
void denormalizeInductionVariable(RewriterBase &rewriter, Location loc, Value normalizedIv, OpFoldResult origLb, OpFoldResult origStep)
Get back the original induction variable values after loop normalization.
std::optional< uint64_t > getConstantUIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer zero-extended to 64 bits.
scf::ForallOp fuseIndependentSiblingForallLoops(scf::ForallOp target, scf::ForallOp source, RewriterBase &rewriter)
Given two scf.forall loops, target and source, fuses target into source.
LogicalResult coalesceLoops(MutableArrayRef< scf::ForOp > loops)
Replace a perfect nest of "for" loops with a single linearized loop.
scf::ForOp fuseIndependentSiblingForLoops(scf::ForOp target, scf::ForOp source, RewriterBase &rewriter)
Given two scf.for loops, target and source, fuses target into source.
llvm::function_ref< Fn > function_ref
TileLoops extractFixedOuterLoops(scf::ForOp rootFOrOp, ArrayRef< int64_t > sizes)
Range emitNormalizedLoopBounds(RewriterBase &rewriter, Location loc, OpFoldResult lb, OpFoldResult ub, OpFoldResult step)
Materialize bounds and step of a zero-based and unit-step loop derived by normalizing the specified b...
SmallVector< scf::ForOp, 8 > Loops
Tile a nest of standard for loops rooted at rootForOp by finding such parametric tile sizes that the ...
bool isOneInteger(OpFoldResult v)
Return true if v is an IntegerAttr with value 1.
std::optional< APInt > constantTripCount(OpFoldResult lb, OpFoldResult ub, OpFoldResult step, bool isSigned, llvm::function_ref< std::optional< llvm::APSInt >(Value, Value, bool)> computeUbMinusLb)
Return the number of iterations for a loop with a lower bound lb, upper bound ub and step step,...
LogicalResult foldDynamicIndexList(SmallVectorImpl< OpFoldResult > &ofrs, bool onlyNonNegative=false, bool onlyNonZero=false)
Returns "success" when any of the elements in ofrs is a constant value.
FailureOr< scf::ForallOp > normalizeForallOp(RewriterBase &rewriter, scf::ForallOp forallOp)
Normalize an scf.forall operation.
void getForwardSlice(Operation *op, SetVector< Operation * > *forwardSlice, const ForwardSliceOptions &options={})
Fills forwardSlice with the computed forward slice (i.e.
SmallVector< std::pair< Block::iterator, Block::iterator > > subBlocks
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
std::optional< scf::ForOp > epilogueLoopOp
std::optional< scf::ForOp > mainLoopOp
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.