#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/SCF/Transforms/Passes.h"
#include "mlir/Dialect/SCF/Transforms/Transforms.h"
#include "mlir/IR/PatternMatch.h"
namespace mlir {
#define GEN_PASS_DEF_SCFFORALLTOPARALLELLOOP
#include "mlir/Dialect/SCF/Transforms/Passes.h.inc"
}
using namespace mlir;
LogicalResult mlir::scf::forallToParallelLoop(RewriterBase &rewriter,
scf::ForallOp forallOp,
scf::ParallelOp *result) {
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPoint(forallOp);
Location loc = forallOp.getLoc();
if (!forallOp.getOutputs().empty())
return rewriter.notifyMatchFailure(
forallOp,
"only fully bufferized scf.forall ops can be lowered to scf.parallel");
SmallVector<Value> lbs = forallOp.getLowerBound(rewriter);
SmallVector<Value> ubs = forallOp.getUpperBound(rewriter);
SmallVector<Value> steps = forallOp.getStep(rewriter);
auto parallelOp = rewriter.create<scf::ParallelOp>(loc, lbs, ubs, steps);
rewriter.eraseBlock(¶llelOp.getRegion().front());
rewriter.inlineRegionBefore(forallOp.getRegion(), parallelOp.getRegion(),
parallelOp.getRegion().begin());
rewriter.setInsertionPointToEnd(¶llelOp.getRegion().front());
rewriter.replaceOpWithNewOp<scf::ReduceOp>(
parallelOp.getRegion().front().getTerminator());
if (forallOp.getMapping())
parallelOp->setAttr("mapping", *forallOp.getMapping());
rewriter.replaceOp(forallOp, parallelOp);
if (result)
*result = parallelOp;
return success();
}
namespace {
struct ForallToParallelLoop final
: public impl::SCFForallToParallelLoopBase<ForallToParallelLoop> {
void runOnOperation() override {
Operation *parentOp = getOperation();
IRRewriter rewriter(parentOp->getContext());
parentOp->walk([&](scf::ForallOp forallOp) {
if (failed(scf::forallToParallelLoop(rewriter, forallOp))) {
return signalPassFailure();
}
});
}
};
}
std::unique_ptr<Pass> mlir::createForallToParallelLoopPass() {
return std::make_unique<ForallToParallelLoop>();
}