|
| 1 | +//===- RemoveSingleIterationLoop.cpp --- remove single iteration loop ---*-===// |
| 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 | +#include "mlir/Dialect/Affine/Passes.h" |
| 10 | + |
| 11 | +#include "mlir/Dialect/Affine/IR/AffineOps.h" |
| 12 | +#include "mlir/Dialect/Affine/Transforms/Transforms.h" |
| 13 | +#include "mlir/Interfaces/ValueBoundsOpInterface.h" |
| 14 | +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" |
| 15 | + |
| 16 | +#include "llvm/Support/Debug.h" |
| 17 | + |
| 18 | +namespace mlir { |
| 19 | +namespace affine { |
| 20 | +#define GEN_PASS_DEF_REMOVESINGLEITERATIONLOOP |
| 21 | +#include "mlir/Dialect/Affine/Passes.h.inc" |
| 22 | +} // namespace affine |
| 23 | +} // namespace mlir |
| 24 | + |
| 25 | +#define DEBUG_TYPE "affine-remove-single-iteration" |
| 26 | + |
| 27 | +using namespace mlir; |
| 28 | +using namespace affine; |
| 29 | + |
| 30 | +/// Replaces the given op with the contents of the given single-block region, |
| 31 | +/// using the operands of the block terminator to replace operation results. |
| 32 | +static void replaceOpWithRegion(PatternRewriter &rewriter, Operation *op, |
| 33 | + Region ®ion, ValueRange blockArgs = {}) { |
| 34 | + assert(llvm::hasSingleElement(region) && "expected single-region block"); |
| 35 | + Block *block = ®ion.front(); |
| 36 | + Operation *terminator = block->getTerminator(); |
| 37 | + ValueRange results = terminator->getOperands(); |
| 38 | + rewriter.inlineBlockBefore(block, op, blockArgs); |
| 39 | + rewriter.replaceOp(op, results); |
| 40 | + rewriter.eraseOp(terminator); |
| 41 | +} |
| 42 | + |
| 43 | +/// Return true if we can prove that the we always run at least the first |
| 44 | +/// iteration of the ForOp. |
| 45 | +static bool alwaysRunsFirstIteration(AffineForOp op) { |
| 46 | + // Can't perform the analysis if the loops's bounds aren't index-typed. |
| 47 | + if (!op.getInductionVar().getType().isIndex()) |
| 48 | + return false; |
| 49 | + SmallVector<Value> lowerMapOperands = op.getLowerBoundOperands(); |
| 50 | + SmallVector<Value> upperMapOperands = op.getUpperBoundOperands(); |
| 51 | + ValueBoundsConstraintSet::Variable lower(op.getLowerBoundMap(), |
| 52 | + lowerMapOperands); |
| 53 | + ValueBoundsConstraintSet::Variable upper(op.getUpperBoundMap(), |
| 54 | + upperMapOperands); |
| 55 | + FailureOr<bool> isLb = ValueBoundsConstraintSet::compare( |
| 56 | + lower, ValueBoundsConstraintSet::LT, upper); |
| 57 | + return isLb.value_or(false); |
| 58 | +} |
| 59 | + |
| 60 | +/// Return true if we can prove that the we never run more than one iteration of |
| 61 | +/// the ForOp. |
| 62 | +static bool neverRunsSecondIteration(AffineForOp op) { |
| 63 | + // Can't perform the analysis if the loops's bounds aren't index-typed. |
| 64 | + if (!op.getInductionVar().getType().isIndex()) |
| 65 | + return false; |
| 66 | + |
| 67 | + // The loop will only loop once if the inducation variable for the next time |
| 68 | + // in the loop is greater than or equal to upper. |
| 69 | + MLIRContext *context = op.getContext(); |
| 70 | + SmallVector<Value> lowerMapOperands = op.getLowerBoundOperands(); |
| 71 | + SmallVector<Value> upperMapOperands = op.getUpperBoundOperands(); |
| 72 | + SmallVector<AffineExpr> results; |
| 73 | + AffineMap lowerMap = op.getLowerBoundMap(); |
| 74 | + for (AffineExpr expr : lowerMap.getResults()) { |
| 75 | + results.push_back(expr + op.getStep().getSExtValue()); |
| 76 | + } |
| 77 | + AffineMap nextItMap = AffineMap::get( |
| 78 | + lowerMap.getNumDims(), lowerMap.getNumSymbols(), results, context); |
| 79 | + ValueBoundsConstraintSet::Variable nextItVar(nextItMap, lowerMapOperands); |
| 80 | + ValueBoundsConstraintSet::Variable upperVar(op.getUpperBoundMap(), |
| 81 | + upperMapOperands); |
| 82 | + FailureOr<bool> isUpperUnderNextIter = ValueBoundsConstraintSet::compare( |
| 83 | + nextItVar, ValueBoundsConstraintSet::LE, upperVar); |
| 84 | + return isUpperUnderNextIter.value_or(false); |
| 85 | +} |
| 86 | + |
| 87 | +namespace { |
| 88 | + |
| 89 | +/// Rewriting pattern that replaces single-iteration loops with their bodies. |
| 90 | +struct SimplifyTrivialLoops : public OpRewritePattern<AffineForOp> { |
| 91 | + using OpRewritePattern::OpRewritePattern; |
| 92 | + |
| 93 | + LogicalResult matchAndRewrite(AffineForOp op, |
| 94 | + PatternRewriter &rewriter) const override { |
| 95 | + if (!(alwaysRunsFirstIteration(op) && neverRunsSecondIteration(op))) { |
| 96 | + return failure(); |
| 97 | + } |
| 98 | + |
| 99 | + // The first iteration is always run and the second iteration is never run |
| 100 | + // so the loop always have 1 iteration. Inline its body and remove the loop. |
| 101 | + SmallVector<Value> blockArgs; |
| 102 | + blockArgs.reserve(op.getInits().size() + 1); |
| 103 | + rewriter.setInsertionPointToStart(op.getBody()); |
| 104 | + Value lower = rewriter.create<AffineApplyOp>( |
| 105 | + op.getLoc(), op.getLowerBoundMap(), op.getLowerBoundOperands()); |
| 106 | + op.getInductionVar().replaceAllUsesWith(lower); |
| 107 | + blockArgs.push_back(lower); |
| 108 | + llvm::append_range(blockArgs, op.getInits()); |
| 109 | + replaceOpWithRegion(rewriter, op, op.getRegion(), blockArgs); |
| 110 | + return success(); |
| 111 | + } |
| 112 | +}; |
| 113 | + |
| 114 | +struct RemoveSingleIterationLoop |
| 115 | + : public affine::impl::RemoveSingleIterationLoopBase< |
| 116 | + RemoveSingleIterationLoop> { |
| 117 | + void runOnOperation() override { |
| 118 | + auto funcOp = getOperation(); |
| 119 | + RewritePatternSet patterns(funcOp.getContext()); |
| 120 | + populateRemoveSingleIterationLoopPattern(patterns); |
| 121 | + if (failed(applyPatternsGreedily(funcOp, std::move(patterns)))) |
| 122 | + return signalPassFailure(); |
| 123 | + } |
| 124 | +}; |
| 125 | + |
| 126 | +} // namespace |
| 127 | + |
| 128 | +void mlir::affine::populateRemoveSingleIterationLoopPattern( |
| 129 | + RewritePatternSet &patterns) { |
| 130 | + patterns.add<SimplifyTrivialLoops>(patterns.getContext()); |
| 131 | +} |
| 132 | + |
| 133 | +std::unique_ptr<InterfacePass<FunctionOpInterface>> |
| 134 | +mlir::affine::createRemoveSingleIterationLoopPass() { |
| 135 | + return std::make_unique<RemoveSingleIterationLoop>(); |
| 136 | +} |
0 commit comments