#include "mlir/Dialect/SCF/Transforms/Passes.h"
#include "mlir/Dialect/Affine/Analysis/AffineStructures.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/SCF/Transforms/Transforms.h"
#include "mlir/Dialect/SCF/Utils/AffineCanonicalizationUtils.h"
#include "mlir/Dialect/Utils/StaticValueUtils.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "llvm/ADT/DenseMap.h"
namespace mlir {
#define GEN_PASS_DEF_SCFFORLOOPPEELING
#define GEN_PASS_DEF_SCFFORLOOPSPECIALIZATION
#define GEN_PASS_DEF_SCFPARALLELLOOPSPECIALIZATION
#include "mlir/Dialect/SCF/Transforms/Passes.h.inc"
}
using namespace mlir;
using namespace mlir::affine;
using scf::ForOp;
using scf::ParallelOp;
static void specializeParallelLoopForUnrolling(ParallelOp op) {
SmallVector<int64_t, 2> constantIndices;
constantIndices.reserve(op.getUpperBound().size());
for (auto bound : op.getUpperBound()) {
auto minOp = bound.getDefiningOp<AffineMinOp>();
if (!minOp)
return;
int64_t minConstant = std::numeric_limits<int64_t>::max();
for (AffineExpr expr : minOp.getMap().getResults()) {
if (auto constantIndex = dyn_cast<AffineConstantExpr>(expr))
minConstant = std::min(minConstant, constantIndex.getValue());
}
if (minConstant == std::numeric_limits<int64_t>::max())
return;
constantIndices.push_back(minConstant);
}
OpBuilder b(op);
IRMapping map;
Value cond;
for (auto bound : llvm::zip(op.getUpperBound(), constantIndices)) {
Value constant =
b.create<arith::ConstantIndexOp>(op.getLoc(), std::get<1>(bound));
Value cmp = b.create<arith::CmpIOp>(op.getLoc(), arith::CmpIPredicate::eq,
std::get<0>(bound), constant);
cond = cond ? b.create<arith::AndIOp>(op.getLoc(), cond, cmp) : cmp;
map.map(std::get<0>(bound), constant);
}
auto ifOp = b.create<scf::IfOp>(op.getLoc(), cond, true);
ifOp.getThenBodyBuilder().clone(*op.getOperation(), map);
ifOp.getElseBodyBuilder().clone(*op.getOperation());
op.erase();
}
static void specializeForLoopForUnrolling(ForOp op) {
auto bound = op.getUpperBound();
auto minOp = bound.getDefiningOp<AffineMinOp>();
if (!minOp)
return;
int64_t minConstant = std::numeric_limits<int64_t>::max();
for (AffineExpr expr : minOp.getMap().getResults()) {
if (auto constantIndex = dyn_cast<AffineConstantExpr>(expr))
minConstant = std::min(minConstant, constantIndex.getValue());
}
if (minConstant == std::numeric_limits<int64_t>::max())
return;
OpBuilder b(op);
IRMapping map;
Value constant = b.create<arith::ConstantIndexOp>(op.getLoc(), minConstant);
Value cond = b.create<arith::CmpIOp>(op.getLoc(), arith::CmpIPredicate::eq,
bound, constant);
map.map(bound, constant);
auto ifOp = b.create<scf::IfOp>(op.getLoc(), cond, true);
ifOp.getThenBodyBuilder().clone(*op.getOperation(), map);
ifOp.getElseBodyBuilder().clone(*op.getOperation());
op.erase();
}
static LogicalResult peelForLoop(RewriterBase &b, ForOp forOp,
ForOp &partialIteration, Value &splitBound) {
RewriterBase::InsertionGuard guard(b);
auto lbInt = getConstantIntValue(forOp.getLowerBound());
auto ubInt = getConstantIntValue(forOp.getUpperBound());
auto stepInt = getConstantIntValue(forOp.getStep());
if (stepInt && *stepInt <= 1)
return failure();
if (lbInt && ubInt && stepInt && (*ubInt - *lbInt) % *stepInt == 0)
return failure();
AffineExpr sym0, sym1, sym2;
bindSymbols(b.getContext(), sym0, sym1, sym2);
SmallVector<Value> operands{forOp.getLowerBound(), forOp.getUpperBound(),
forOp.getStep()};
AffineMap map = AffineMap::get(0, 3, {(sym1 - sym0) % sym2});
affine::fullyComposeAffineMapAndOperands(&map, &operands);
if (auto constExpr = dyn_cast<AffineConstantExpr>(map.getResult(0)))
if (constExpr.getValue() == 0)
return failure();
auto modMap = AffineMap::get(0, 3, {sym1 - ((sym1 - sym0) % sym2)});
b.setInsertionPoint(forOp);
auto loc = forOp.getLoc();
splitBound = b.createOrFold<AffineApplyOp>(loc, modMap,
ValueRange{forOp.getLowerBound(),
forOp.getUpperBound(),
forOp.getStep()});
b.setInsertionPointAfter(forOp);
partialIteration = cast<ForOp>(b.clone(*forOp.getOperation()));
partialIteration.getLowerBoundMutable().assign(splitBound);
b.replaceAllUsesWith(forOp.getResults(), partialIteration->getResults());
partialIteration.getInitArgsMutable().assign(forOp->getResults());
b.modifyOpInPlace(forOp,
[&]() { forOp.getUpperBoundMutable().assign(splitBound); });
return success();
}
static void rewriteAffineOpAfterPeeling(RewriterBase &rewriter, ForOp forOp,
ForOp partialIteration,
Value previousUb) {
Value mainIv = forOp.getInductionVar();
Value partialIv = partialIteration.getInductionVar();
assert(forOp.getStep() == partialIteration.getStep() &&
"expected same step in main and partial loop");
Value step = forOp.getStep();
forOp.walk([&](Operation *affineOp) {
if (!isa<AffineMinOp, AffineMaxOp>(affineOp))
return WalkResult::advance();
(void)scf::rewritePeeledMinMaxOp(rewriter, affineOp, mainIv, previousUb,
step,
true);
return WalkResult::advance();
});
partialIteration.walk([&](Operation *affineOp) {
if (!isa<AffineMinOp, AffineMaxOp>(affineOp))
return WalkResult::advance();
(void)scf::rewritePeeledMinMaxOp(rewriter, affineOp, partialIv, previousUb,
step, false);
return WalkResult::advance();
});
}
LogicalResult mlir::scf::peelForLoopAndSimplifyBounds(RewriterBase &rewriter,
ForOp forOp,
ForOp &partialIteration) {
Value previousUb = forOp.getUpperBound();
Value splitBound;
if (failed(peelForLoop(rewriter, forOp, partialIteration, splitBound)))
return failure();
rewriteAffineOpAfterPeeling(rewriter, forOp, partialIteration, previousUb);
return success();
}
LogicalResult mlir::scf::peelForLoopFirstIteration(RewriterBase &b, ForOp forOp,
ForOp &firstIteration) {
RewriterBase::InsertionGuard guard(b);
auto lbInt = getConstantIntValue(forOp.getLowerBound());
auto ubInt = getConstantIntValue(forOp.getUpperBound());
auto stepInt = getConstantIntValue(forOp.getStep());
if (lbInt && ubInt && stepInt && ceil(float(*ubInt - *lbInt) / *stepInt) <= 1)
return failure();
AffineExpr lbSymbol, stepSymbol;
bindSymbols(b.getContext(), lbSymbol, stepSymbol);
auto ubMap = AffineMap::get(0, 2, {lbSymbol + stepSymbol});
b.setInsertionPoint(forOp);
auto loc = forOp.getLoc();
Value splitBound = b.createOrFold<AffineApplyOp>(
loc, ubMap, ValueRange{forOp.getLowerBound(), forOp.getStep()});
IRMapping map;
map.map(forOp.getUpperBound(), splitBound);
firstIteration = cast<ForOp>(b.clone(*forOp.getOperation(), map));
b.modifyOpInPlace(forOp, [&]() {
forOp.getInitArgsMutable().assign(firstIteration->getResults());
forOp.getLowerBoundMutable().assign(splitBound);
});
return success();
}
static constexpr char kPeeledLoopLabel[] = "__peeled_loop__";
static constexpr char kPartialIterationLabel[] = "__partial_iteration__";
namespace {
struct ForLoopPeelingPattern : public OpRewritePattern<ForOp> {
ForLoopPeelingPattern(MLIRContext *ctx, bool peelFront, bool skipPartial)
: OpRewritePattern<ForOp>(ctx), peelFront(peelFront),
skipPartial(skipPartial) {}
LogicalResult matchAndRewrite(ForOp forOp,
PatternRewriter &rewriter) const override {
if (forOp->hasAttr(kPeeledLoopLabel))
return failure();
scf::ForOp partialIteration;
if (peelFront) {
if (failed(
peelForLoopFirstIteration(rewriter, forOp, partialIteration))) {
return failure();
}
} else {
if (skipPartial) {
Operation *op = forOp.getOperation();
while ((op = op->getParentOfType<scf::ForOp>())) {
if (op->hasAttr(kPartialIterationLabel))
return failure();
}
}
if (failed(
peelForLoopAndSimplifyBounds(rewriter, forOp, partialIteration)))
return failure();
}
rewriter.modifyOpInPlace(partialIteration, [&]() {
partialIteration->setAttr(kPeeledLoopLabel, rewriter.getUnitAttr());
partialIteration->setAttr(kPartialIterationLabel, rewriter.getUnitAttr());
});
rewriter.modifyOpInPlace(forOp, [&]() {
forOp->setAttr(kPeeledLoopLabel, rewriter.getUnitAttr());
});
return success();
}
bool peelFront;
bool skipPartial;
};
}
namespace {
struct ParallelLoopSpecialization
: public impl::SCFParallelLoopSpecializationBase<
ParallelLoopSpecialization> {
void runOnOperation() override {
getOperation()->walk(
[](ParallelOp op) { specializeParallelLoopForUnrolling(op); });
}
};
struct ForLoopSpecialization
: public impl::SCFForLoopSpecializationBase<ForLoopSpecialization> {
void runOnOperation() override {
getOperation()->walk([](ForOp op) { specializeForLoopForUnrolling(op); });
}
};
struct ForLoopPeeling : public impl::SCFForLoopPeelingBase<ForLoopPeeling> {
void runOnOperation() override {
auto *parentOp = getOperation();
MLIRContext *ctx = parentOp->getContext();
RewritePatternSet patterns(ctx);
patterns.add<ForLoopPeelingPattern>(ctx, peelFront, skipPartial);
(void)applyPatternsAndFoldGreedily(parentOp, std::move(patterns));
parentOp->walk([](Operation *op) {
op->removeAttr(kPeeledLoopLabel);
op->removeAttr(kPartialIterationLabel);
});
}
};
}
std::unique_ptr<Pass> mlir::createParallelLoopSpecializationPass() {
return std::make_unique<ParallelLoopSpecialization>();
}
std::unique_ptr<Pass> mlir::createForLoopSpecializationPass() {
return std::make_unique<ForLoopSpecialization>();
}
std::unique_ptr<Pass> mlir::createForLoopPeelingPass() {
return std::make_unique<ForLoopPeeling>();
}