Skip to content

Commit dbd9818

Browse files
[mlir][scf] Add parallelLoopUnrollByFactors() (#164958)
- In the SCF Utils, add the `parallelLoopUnrollByFactors()` function to unroll scf::ParallelOp loops according to the specified unroll factors - Add a test pass "TestParallelLoopUnrolling" and the related LIT test - Expose `mlir::parallelLoopUnrollByFactors()`, `mlir::generateUnrolledLoop()`, and `mlir::scf::computeUbMinusLb()` functions in the mlir/Dialect/SCF/Utils/Utils.h and /IR/SCF.h headers to make them available to other passes. - In `mlir::generateUnrolledLoop()`, add an optional `IRMapping *clonedToSrcOpsMap` argument to map the new cloned operations to their original ones. In the function body, change the default `AnnotateFn` type to `static const` to silence potential warnings about dangling references when a function_ref is assigned to a variable with automatic storage. Signed-off-by: Fabrizio Indirli <[email protected]>
1 parent b2da8ef commit dbd9818

File tree

8 files changed

+426
-21
lines changed

8 files changed

+426
-21
lines changed

mlir/include/mlir/Dialect/SCF/IR/SCF.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@ SmallVector<Value> replaceAndCastForOpIterArg(RewriterBase &rewriter,
112112
Value replacement,
113113
const ValueTypeCastFnTy &castFn);
114114

115+
/// Helper function to compute the difference between two values. This is used
116+
/// by the loop implementations to compute the trip count.
117+
std::optional<llvm::APSInt> computeUbMinusLb(Value lb, Value ub, bool isSigned);
118+
115119
} // namespace scf
116120
} // namespace mlir
117121
#endif // MLIR_DIALECT_SCF_SCF_H

mlir/include/mlir/Dialect/SCF/Utils/Utils.h

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,39 @@ FailureOr<scf::ForallOp> normalizeForallOp(RewriterBase &rewriter,
221221
/// 4. Each region iter arg and result has exactly one use
222222
bool isPerfectlyNestedForLoops(MutableArrayRef<LoopLikeOpInterface> loops);
223223

224+
/// Generate unrolled copies of an scf loop's 'loopBodyBlock', with 'iterArgs'
225+
/// and 'yieldedValues' as the block arguments and yielded values of the loop.
226+
/// The content of the loop body is replicated 'unrollFactor' times, calling
227+
/// 'ivRemapFn' to remap 'iv' for each unrolled body. If specified, annotates
228+
/// the Ops in each unrolled iteration using annotateFn. If provided,
229+
/// 'clonedToSrcOpsMap' is populated with the mappings from the cloned ops to
230+
/// the original op.
231+
void generateUnrolledLoop(
232+
Block *loopBodyBlock, Value iv, uint64_t unrollFactor,
233+
function_ref<Value(unsigned, Value, OpBuilder)> ivRemapFn,
234+
function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
235+
ValueRange iterArgs, ValueRange yieldedValues,
236+
IRMapping *clonedToSrcOpsMap = nullptr);
237+
238+
/// Unroll this scf::Parallel loop by the specified unroll factors. Returns the
239+
/// unrolled loop if the unroll succeded; otherwise returns failure if the loop
240+
/// cannot be unrolled either due to restrictions or to invalid unroll factors.
241+
/// Requires positive loop bounds and step. If specified, annotates the Ops in
242+
/// each unrolled iteration by applying `annotateFn`.
243+
/// If provided, 'clonedToSrcOpsMap' is populated with the mappings from the
244+
/// cloned ops to the original op.
245+
FailureOr<scf::ParallelOp> parallelLoopUnrollByFactors(
246+
scf::ParallelOp op, ArrayRef<uint64_t> unrollFactors,
247+
RewriterBase &rewriter,
248+
function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn = nullptr,
249+
IRMapping *clonedToSrcOpsMap = nullptr);
250+
251+
/// Get constant trip counts for each of the induction variables of the given
252+
/// loop operation. If any of the loop's trip counts is not constant, return an
253+
/// empty vector.
254+
llvm::SmallVector<int64_t>
255+
getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp);
256+
224257
} // namespace mlir
225258

226259
#endif // MLIR_DIALECT_SCF_UTILS_UTILS_H_

mlir/lib/Dialect/SCF/IR/SCF.cpp

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,8 @@ static TerminatorTy verifyAndGetTerminator(Operation *op, Region &region,
111111
return nullptr;
112112
}
113113

114-
/// Helper function to compute the difference between two values. This is used
115-
/// by the loop implementations to compute the trip count.
116-
static std::optional<llvm::APSInt> computeUbMinusLb(Value lb, Value ub,
117-
bool isSigned) {
114+
std::optional<llvm::APSInt> mlir::scf::computeUbMinusLb(Value lb, Value ub,
115+
bool isSigned) {
118116
llvm::APSInt diff;
119117
auto addOp = ub.getDefiningOp<arith::AddIOp>();
120118
if (!addOp)

mlir/lib/Dialect/SCF/Utils/Utils.cpp

Lines changed: 128 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -291,47 +291,61 @@ static Value ceilDivPositive(OpBuilder &builder, Location loc, Value dividend,
291291
return arith::DivUIOp::create(builder, loc, sum, divisor);
292292
}
293293

294-
/// Generates unrolled copies of scf::ForOp 'loopBodyBlock', with
295-
/// associated 'forOpIV' by 'unrollFactor', calling 'ivRemapFn' to remap
296-
/// 'forOpIV' for each unrolled body. If specified, annotates the Ops in each
297-
/// unrolled iteration using annotateFn.
298-
static void generateUnrolledLoop(
299-
Block *loopBodyBlock, Value forOpIV, uint64_t unrollFactor,
294+
void mlir::generateUnrolledLoop(
295+
Block *loopBodyBlock, Value iv, uint64_t unrollFactor,
300296
function_ref<Value(unsigned, Value, OpBuilder)> ivRemapFn,
301297
function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
302-
ValueRange iterArgs, ValueRange yieldedValues) {
298+
ValueRange iterArgs, ValueRange yieldedValues,
299+
IRMapping *clonedToSrcOpsMap) {
300+
301+
// Check if the op was cloned from another source op, and return it if found
302+
// (or the same op if not found)
303+
auto findOriginalSrcOp =
304+
[](Operation *op, const IRMapping &clonedToSrcOpsMap) -> Operation * {
305+
Operation *srcOp = op;
306+
// If the source op derives from another op: traverse the chain to find the
307+
// original source op
308+
while (srcOp && clonedToSrcOpsMap.contains(srcOp))
309+
srcOp = clonedToSrcOpsMap.lookup(srcOp);
310+
return srcOp;
311+
};
312+
303313
// Builder to insert unrolled bodies just before the terminator of the body of
304-
// 'forOp'.
314+
// the loop.
305315
auto builder = OpBuilder::atBlockTerminator(loopBodyBlock);
306316

307-
constexpr auto defaultAnnotateFn = [](unsigned, Operation *, OpBuilder) {};
317+
static const auto noopAnnotateFn = [](unsigned, Operation *, OpBuilder) {};
308318
if (!annotateFn)
309-
annotateFn = defaultAnnotateFn;
319+
annotateFn = noopAnnotateFn;
310320

311321
// Keep a pointer to the last non-terminator operation in the original block
312322
// so that we know what to clone (since we are doing this in-place).
313323
Block::iterator srcBlockEnd = std::prev(loopBodyBlock->end(), 2);
314324

315-
// Unroll the contents of 'forOp' (append unrollFactor - 1 additional copies).
325+
// Unroll the contents of the loop body (append unrollFactor - 1 additional
326+
// copies).
316327
SmallVector<Value, 4> lastYielded(yieldedValues);
317328

318329
for (unsigned i = 1; i < unrollFactor; i++) {
319-
IRMapping operandMap;
320-
321330
// Prepare operand map.
331+
IRMapping operandMap;
322332
operandMap.map(iterArgs, lastYielded);
323333

324334
// If the induction variable is used, create a remapping to the value for
325335
// this unrolled instance.
326-
if (!forOpIV.use_empty()) {
327-
Value ivUnroll = ivRemapFn(i, forOpIV, builder);
328-
operandMap.map(forOpIV, ivUnroll);
336+
if (!iv.use_empty()) {
337+
Value ivUnroll = ivRemapFn(i, iv, builder);
338+
operandMap.map(iv, ivUnroll);
329339
}
330340

331341
// Clone the original body of 'forOp'.
332342
for (auto it = loopBodyBlock->begin(); it != std::next(srcBlockEnd); it++) {
333-
Operation *clonedOp = builder.clone(*it, operandMap);
343+
Operation *srcOp = &(*it);
344+
Operation *clonedOp = builder.clone(*srcOp, operandMap);
334345
annotateFn(i, clonedOp, builder);
346+
if (clonedToSrcOpsMap)
347+
clonedToSrcOpsMap->map(clonedOp,
348+
findOriginalSrcOp(srcOp, *clonedToSrcOpsMap));
335349
}
336350

337351
// Update yielded values.
@@ -1544,3 +1558,100 @@ bool mlir::isPerfectlyNestedForLoops(
15441558
}
15451559
return true;
15461560
}
1561+
1562+
llvm::SmallVector<int64_t>
1563+
mlir::getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp) {
1564+
std::optional<SmallVector<OpFoldResult>> loBnds = loopOp.getLoopLowerBounds();
1565+
std::optional<SmallVector<OpFoldResult>> upBnds = loopOp.getLoopUpperBounds();
1566+
std::optional<SmallVector<OpFoldResult>> steps = loopOp.getLoopSteps();
1567+
if (!loBnds || !upBnds || !steps)
1568+
return {};
1569+
llvm::SmallVector<int64_t> tripCounts;
1570+
for (auto [lb, ub, step] : llvm::zip(*loBnds, *upBnds, *steps)) {
1571+
std::optional<llvm::APInt> numIter = constantTripCount(
1572+
lb, ub, step, /*isSigned=*/true, scf::computeUbMinusLb);
1573+
if (!numIter)
1574+
return {};
1575+
tripCounts.push_back(numIter->getSExtValue());
1576+
}
1577+
return tripCounts;
1578+
}
1579+
1580+
FailureOr<scf::ParallelOp> mlir::parallelLoopUnrollByFactors(
1581+
scf::ParallelOp op, ArrayRef<uint64_t> unrollFactors,
1582+
RewriterBase &rewriter,
1583+
function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
1584+
IRMapping *clonedToSrcOpsMap) {
1585+
const unsigned numLoops = op.getNumLoops();
1586+
assert(llvm::none_of(unrollFactors, [](uint64_t f) { return f == 0; }) &&
1587+
"Expected positive unroll factors");
1588+
assert((!unrollFactors.empty() && (unrollFactors.size() <= numLoops)) &&
1589+
"Expected non-empty unroll factors of size <= to the number of loops");
1590+
1591+
// Bail out if no valid unroll factors were provided
1592+
if (llvm::all_of(unrollFactors, [](uint64_t f) { return f == 1; }))
1593+
return rewriter.notifyMatchFailure(
1594+
op, "Unrolling not applied if all factors are 1");
1595+
1596+
// Return if the loop body is empty.
1597+
if (llvm::hasSingleElement(op.getBody()->getOperations()))
1598+
return rewriter.notifyMatchFailure(op, "Cannot unroll an empty loop body");
1599+
1600+
// If the provided unroll factors do not cover all the loop dims, they are
1601+
// applied to the inner loop dimensions.
1602+
const unsigned firstLoopDimIdx = numLoops - unrollFactors.size();
1603+
1604+
// Make sure that the unroll factors divide the iteration space evenly
1605+
// TODO: Support unrolling loops with dynamic iteration spaces.
1606+
const llvm::SmallVector<int64_t> tripCounts = getConstLoopTripCounts(op);
1607+
if (tripCounts.empty())
1608+
return rewriter.notifyMatchFailure(
1609+
op, "Failed to compute constant trip counts for the loop. Note that "
1610+
"dynamic loop sizes are not supported.");
1611+
1612+
for (unsigned dimIdx = firstLoopDimIdx; dimIdx < numLoops; dimIdx++) {
1613+
const uint64_t unrollFactor = unrollFactors[dimIdx - firstLoopDimIdx];
1614+
if (tripCounts[dimIdx] % unrollFactor)
1615+
return rewriter.notifyMatchFailure(
1616+
op, "Unroll factors don't divide the iteration space evenly");
1617+
}
1618+
1619+
std::optional<SmallVector<OpFoldResult>> maybeFoldSteps = op.getLoopSteps();
1620+
if (!maybeFoldSteps)
1621+
return rewriter.notifyMatchFailure(op, "Failed to retrieve loop steps");
1622+
llvm::SmallVector<size_t> steps{};
1623+
for (auto step : *maybeFoldSteps)
1624+
steps.push_back(static_cast<size_t>(*getConstantIntValue(step)));
1625+
1626+
for (unsigned dimIdx = firstLoopDimIdx; dimIdx < numLoops; dimIdx++) {
1627+
const uint64_t unrollFactor = unrollFactors[dimIdx - firstLoopDimIdx];
1628+
if (unrollFactor == 1)
1629+
continue;
1630+
const size_t origStep = steps[dimIdx];
1631+
const int64_t newStep = origStep * unrollFactor;
1632+
IRMapping clonedToSrcOpsMap;
1633+
1634+
ValueRange iterArgs = ValueRange(op.getRegionIterArgs());
1635+
auto yieldedValues = op.getBody()->getTerminator()->getOperands();
1636+
1637+
generateUnrolledLoop(
1638+
op.getBody(), op.getInductionVars()[dimIdx], unrollFactor,
1639+
[&](unsigned i, Value iv, OpBuilder b) {
1640+
// iv' = iv + step * i;
1641+
const AffineExpr expr = b.getAffineDimExpr(0) + (origStep * i);
1642+
const auto map =
1643+
b.getDimIdentityMap().dropResult(0).insertResult(expr, 0);
1644+
return affine::AffineApplyOp::create(b, iv.getLoc(), map,
1645+
ValueRange{iv});
1646+
},
1647+
/*annotateFn*/ annotateFn, iterArgs, yieldedValues, &clonedToSrcOpsMap);
1648+
1649+
// Update loop step
1650+
auto prevInsertPoint = rewriter.saveInsertionPoint();
1651+
rewriter.setInsertionPoint(op);
1652+
op.getStepMutable()[dimIdx].assign(
1653+
arith::ConstantIndexOp::create(rewriter, op.getLoc(), newStep));
1654+
rewriter.restoreInsertionPoint(prevInsertPoint);
1655+
}
1656+
return op;
1657+
}

0 commit comments

Comments
 (0)