MLIR 24.0.0git
Utils.h
Go to the documentation of this file.
1//===- Utils.h - SCF dialect utilities --------------------------*- C++ -*-===//
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// This header file defines prototypes for various SCF utilities.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_DIALECT_SCF_UTILS_UTILS_H_
14#define MLIR_DIALECT_SCF_UTILS_UTILS_H_
15
18#include "mlir/Support/LLVM.h"
19#include "llvm/ADT/STLExtras.h"
20#include <optional>
21#include <tuple>
22#include <utility>
23
24namespace mlir {
25class Location;
26class Operation;
27class OpBuilder;
28class Region;
29class RewriterBase;
30class ValueRange;
31class Value;
32
33namespace func {
34class CallOp;
35class FuncOp;
36} // namespace func
37
38/// Update a perfectly nested loop nest to yield new values from the innermost
39/// loop and propagating it up through the loop nest. This function
40/// - Expects `loopNest` to be a perfectly nested loop with outer most loop
41/// first and innermost loop last.
42/// - `newIterOperands` are the initialization values to be used for the
43/// outermost loop
44/// - `newYielValueFn` is the callback that generates the new values to be
45/// yielded from within the innermost loop.
46/// - The original loops are not erased, but are left in a "no-op" state where
47/// the body of the loop just yields the basic block arguments that correspond
48/// to the initialization values of a loop. The original loops are dead after
49/// this method.
50/// - If `replaceIterOperandsUsesInLoop` is true, all uses of the
51/// `newIterOperands` within the generated new loop are replaced with the
52/// corresponding `BlockArgument` in the loop body.
54 RewriterBase &rewriter, MutableArrayRef<scf::ForOp> loopNest,
55 ValueRange newIterOperands, const NewYieldValuesFn &newYieldValuesFn,
56 bool replaceIterOperandsUsesInLoop = true);
57
58/// Outline a region with a single block into a new FuncOp.
59/// Assumes the FuncOp result types is the type of the yielded operands of the
60/// single block. This constraint makes it easy to determine the result.
61/// This method also clones the `arith::ConstantIndexOp` at the start of
62/// `outlinedFuncBody` to alloc simple canonicalizations.
63/// Creates a new FuncOp and thus cannot be used in a FuncOp pass.
64/// The client is responsible for providing a unique `funcName` that will not
65/// collide with another FuncOp name. If `callOp` is provided, it will be set
66/// to point to the operation that calls the outlined function.
67// TODO: support more than single-block regions.
68// TODO: more flexible constant handling.
69FailureOr<func::FuncOp>
71 StringRef funcName, func::CallOp *callOp = nullptr);
72
73/// Outline the then and/or else regions of `ifOp` as follows:
74/// - if `thenFn` is not null, `thenFnName` must be specified and the `then`
75/// region is inlined into a new FuncOp that is captured by the pointer.
76/// - if `elseFn` is not null, `elseFnName` must be specified and the `else`
77/// region is inlined into a new FuncOp that is captured by the pointer.
78/// Creates new FuncOps and thus cannot be used in a FuncOp pass.
79/// The client is responsible for providing a unique `thenFnName`/`elseFnName`
80/// that will not collide with another FuncOp name.
81LogicalResult outlineIfOp(RewriterBase &b, scf::IfOp ifOp, func::FuncOp *thenFn,
82 StringRef thenFnName, func::FuncOp *elseFn,
83 StringRef elseFnName);
84
85/// Get a list of innermost parallel loops contained in `rootOp`. Innermost
86/// parallel loops are those that do not contain further parallel loops
87/// themselves.
90
91/// Replace a perfect nest of "for" loops with a single linearized loop. Assumes
92/// `loops` contains a list of perfectly nested loops with bounds and steps
93/// independent of any loop induction variable involved in the nest.
95LogicalResult coalesceLoops(RewriterBase &rewriter,
97
98/// Walk an affine.for to find a band to coalesce.
99LogicalResult coalescePerfectlyNestedSCFForLoops(scf::ForOp op);
100
101/// Take the ParallelLoop and for each set of dimension indices, combine them
102/// into a single dimension. `combinedDimensions` must contain each index into
103/// `loops` exactly once. Returns the collapsed loop. Reductions on `loops` are
104/// preserved.
105scf::ParallelOp
106collapseParallelLoops(RewriterBase &rewriter, scf::ParallelOp loops,
107 ArrayRef<std::vector<unsigned>> combinedDimensions);
108
110 std::optional<scf::ForOp> mainLoopOp = std::nullopt;
111 std::optional<scf::ForOp> epilogueLoopOp = std::nullopt;
112};
113
114/// Splits `forOp` into two consecutive loops at `splitPoint`:
115/// first: [lowerBound, splitPoint)
116/// second: [splitPoint, upperBound)
117///
118/// Uses `rewriter` to replace `forOp` and returns the two new loops. Iter-args
119/// are chained from the first loop to the second.
120///
121/// The caller must ensure that `splitPoint` has the same type as the loop
122/// bounds, that the step is positive, and that
123/// `lowerBound <= splitPoint < upperBound`. The split point must also lie on
124/// the loop's iteration lattice: `splitPoint == lowerBound + k * step` for
125/// some non-negative integer `k`. Statically known violations cause failure;
126/// dynamic values are assumed to satisfy these preconditions.
127FailureOr<std::pair<scf::ForOp, scf::ForOp>>
128splitForOpAtPoint(RewriterBase &rewriter, scf::ForOp forOp, Value splitPoint);
129
130/// Unrolls this for operation by the specified unroll factor. Returns the
131/// unrolled main loop and the epilogue loop, if the loop is unrolled. Otherwise
132/// returns failure if the loop cannot be unrolled either due to restrictions or
133/// due to invalid unroll factors. Requires positive step. If specified,
134// annotates the Ops in each unrolled iteration by applying
135/// `annotateFn`.
136/// If `shouldPromoteIfSingleIteration` is true, the function will promote the
137/// loop body up if this has turned into a single iteration loop.
138FailureOr<UnrolledLoopInfo> loopUnrollByFactor(
139 scf::ForOp forOp, uint64_t unrollFactor,
140 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn = nullptr,
141 bool shouldPromoteIfSingleIteration = true);
142
143/// Unrolls this loop completely.
144LogicalResult loopUnrollFull(scf::ForOp forOp);
145
146/// Unrolls and jams this `scf.for` operation by the specified unroll factor.
147/// Returns failure if the loop cannot be unrolled either due to restrictions or
148/// due to invalid unroll factors. In case of unroll factor of 1, the function
149/// bails out without doing anything (returns success). Currently, only constant
150/// trip count that are divided by the unroll factor is supported. Currently,
151/// for operations with results are not supported.
152LogicalResult loopUnrollJamByFactor(scf::ForOp forOp, uint64_t unrollFactor);
153
154/// Materialize bounds and step of a zero-based and unit-step loop derived by
155/// normalizing the specified bounds and step.
158 OpFoldResult step);
159
160/// Get back the original induction variable values after loop normalization.
162 Value normalizedIv, OpFoldResult origLb,
163 OpFoldResult origStep);
164
165/// Tile a nest of standard for loops rooted at `rootForOp` by finding such
166/// parametric tile sizes that the outer loops have a fixed number of iterations
167/// as defined in `sizes`. Tiling changes the order of the iterations; the
168/// caller must make sure that does not change the result, including the
169/// values carried by iter_args.
171using TileLoops = std::pair<Loops, Loops>;
172TileLoops extractFixedOuterLoops(scf::ForOp rootFOrOp, ArrayRef<int64_t> sizes);
173
174/// Performs tiling fo imperfectly nested loops (with interchange) by
175/// strip-mining the `forOps` by `sizes` and sinking them, in their order of
176/// occurrence in `forOps`, under each of the `targets`.
177/// Returns the new AffineForOps, one per each of (`forOps`, `targets`) pair,
178/// nested immediately under each of `targets`.
180 ArrayRef<scf::ForOp> targets);
181
182/// Performs tiling (with interchange) by strip-mining the `forOps` by `sizes`
183/// and sinking them, in their order of occurrence in `forOps`, under `target`.
184/// Returns the new AffineForOps, one per `forOps`, nested immediately under
185/// `target`.
187 scf::ForOp target);
188
189/// Tile a nest of scf::ForOp loops rooted at `rootForOp` with the given
190/// (parametric) sizes. Sizes are expected to be strictly positive values at
191/// runtime. If more sizes than loops are provided, discard the trailing values
192/// in sizes. Assumes the loop nest is permutable.
193/// Returns the newly created intra-tile loops.
194Loops tilePerfectlyNested(scf::ForOp rootForOp, ArrayRef<Value> sizes);
195
196/// Get perfectly nested sequence of loops starting at root of loop nest
197/// (the first op being another AffineFor, and the second op - a terminator).
198/// A loop is perfectly nested iff: the first op in the loop's body is another
199/// AffineForOp, and the second op is a terminator).
201 scf::ForOp root);
202
203/// Given two scf.forall loops, `target` and `source`, fuses `target` into
204/// `source`. Assumes that the given loops are siblings and are independent of
205/// each other.
206///
207/// This function does not perform any legality checks and simply fuses the
208/// loops. The caller is responsible for ensuring that the loops are legal to
209/// fuse.
210scf::ForallOp fuseIndependentSiblingForallLoops(scf::ForallOp target,
211 scf::ForallOp source,
212 RewriterBase &rewriter);
213
214/// Given two scf.for loops, `target` and `source`, fuses `target` into
215/// `source`. Assumes that the given loops are siblings and are independent of
216/// each other.
217///
218/// This function does not perform any legality checks and simply fuses the
219/// loops. The caller is responsible for ensuring that the loops are legal to
220/// fuse.
221scf::ForOp fuseIndependentSiblingForLoops(scf::ForOp target, scf::ForOp source,
222 RewriterBase &rewriter);
223
224/// Normalize an `scf.forall` operation. Returns `failure()`if normalization
225/// fails.
226// On `success()` returns the
227/// newly created operation with all uses of the original operation replaced
228/// with results of the new operation.
229FailureOr<scf::ForallOp> normalizeForallOp(RewriterBase &rewriter,
230 scf::ForallOp forallOp);
231
232/// Check if the provided loops are perfectly nested for-loops. Perfect nesting
233/// means:
234/// 1. All loops are scf.for operations
235/// 2. Each outer loop's region iter args match the inner loop's init args
236/// 3. Each outer loop's yields match the inner loop's results
237/// 4. Each region iter arg and result has exactly one use
239
240/// Generate unrolled copies of an scf loop's 'loopBodyBlock', with 'iterArgs'
241/// and 'yieldedValues' as the block arguments and yielded values of the loop.
242/// The content of the loop body is replicated 'unrollFactor' times, calling
243/// 'ivRemapFn' to remap 'iv' for each unrolled body. If specified, annotates
244/// the Ops in each unrolled iteration using annotateFn. If provided,
245/// 'clonedToSrcOpsMap' is populated with the mappings from the cloned ops to
246/// the original op. If provided, the values yielded by each additional copy of
247/// the loop body are appended to 'unrolledYieldedValues', in order.
249 Block *loopBodyBlock, Value iv, uint64_t unrollFactor,
250 function_ref<Value(unsigned, Value, OpBuilder)> ivRemapFn,
251 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
252 ValueRange iterArgs, ValueRange yieldedValues,
253 IRMapping *clonedToSrcOpsMap = nullptr,
254 SmallVectorImpl<SmallVector<Value>> *unrolledYieldedValues = nullptr);
255
256/// Unroll this scf::Parallel loop by the specified unroll factors. Returns the
257/// unrolled loop if the unroll succeded; otherwise returns failure if the loop
258/// cannot be unrolled either due to restrictions or to invalid unroll factors.
259/// Requires positive loop bounds and step. The values reduced by the unrolled
260/// iterations are combined with the reduction functions, which are assumed to
261/// be associative; returns failure if a reduction function uses a value
262/// defined in the loop. If specified, annotates the Ops in each unrolled
263/// iteration by applying `annotateFn`.
264/// If provided, 'clonedToSrcOpsMap' is populated with the mappings from the
265/// cloned ops to the original op.
266FailureOr<scf::ParallelOp> parallelLoopUnrollByFactors(
267 scf::ParallelOp op, ArrayRef<uint64_t> unrollFactors,
268 RewriterBase &rewriter,
269 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn = nullptr,
270 IRMapping *clonedToSrcOpsMap = nullptr);
271
272/// Get constant loop bounds and steps for each of the induction variables of
273/// the given loop operation, if all the loop's ranges are constant. Each entry
274/// in the returned vector is a tuple (lowerBound, upperBound, step).
276getConstLoopBounds(mlir::LoopLikeOpInterface loopOp);
277
278/// Get constant trip counts for each of the induction variables of the given
279/// loop operation. If any of the loop's trip counts is not constant, return an
280/// empty vector.
282getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp);
283
284} // namespace mlir
285
286#endif // MLIR_DIALECT_SCF_UTILS_UTILS_H_
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Block represents an ordered list of Operations.
Definition Block.h:34
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
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...
Definition Utils.cpp:1444
bool isPerfectlyNestedForLoops(MutableArrayRef< LoopLikeOpInterface > loops)
Check if the provided loops are perfectly nested for-loops.
Definition Utils.cpp:1642
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.
Definition Utils.cpp:422
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:
Definition Utils.cpp:218
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...
Definition Utils.cpp:295
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...
Definition Utils.cpp:36
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.
Definition Utils.cpp:1182
LogicalResult coalescePerfectlyNestedSCFForLoops(scf::ForOp op)
Walk an affine.for to find a band to coalesce.
Definition Utils.cpp:1107
LogicalResult loopUnrollFull(scf::ForOp forOp)
Unrolls this loop completely.
Definition Utils.cpp:588
llvm::SmallVector< llvm::APInt > getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp)
Get constant trip counts for each of the induction variables of the given loop operation.
Definition Utils.cpp:1700
std::pair< Loops, Loops > TileLoops
Definition Utils.h:171
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,...
Definition Utils.cpp:1681
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...
Definition Utils.cpp:371
Loops tilePerfectlyNested(scf::ForOp rootForOp, ArrayRef< Value > sizes)
Tile a nest of scf::ForOp loops rooted at rootForOp with the given (parametric) sizes.
Definition Utils.cpp:1432
LogicalResult loopUnrollJamByFactor(scf::ForOp forOp, uint64_t unrollFactor)
Unrolls and jams this scf.for operation by the specified unroll factor.
Definition Utils.cpp:616
bool getInnermostParallelLoops(Operation *rootOp, SmallVectorImpl< scf::ParallelOp > &result)
Get a list of innermost parallel loops contained in rootOp.
Definition Utils.cpp:241
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.
Definition Utils.cpp:1741
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...
Definition Utils.cpp:1411
FailureOr< func::FuncOp > outlineSingleBlockRegion(RewriterBase &rewriter, Location loc, Region &region, StringRef funcName, func::CallOp *callOp=nullptr)
Outline a region with a single block into a new FuncOp.
Definition Utils.cpp:115
void denormalizeInductionVariable(RewriterBase &rewriter, Location loc, Value normalizedIv, OpFoldResult origLb, OpFoldResult origStep)
Get back the original induction variable values after loop normalization.
Definition Utils.cpp:870
scf::ForallOp fuseIndependentSiblingForallLoops(scf::ForallOp target, scf::ForallOp source, RewriterBase &rewriter)
Given two scf.forall loops, target and source, fuses target into source.
Definition Utils.cpp:1491
LogicalResult coalesceLoops(MutableArrayRef< scf::ForOp > loops)
Replace a perfect nest of "for" loops with a single linearized loop.
Definition Utils.cpp:1099
scf::ForOp fuseIndependentSiblingForLoops(scf::ForOp target, scf::ForOp source, RewriterBase &rewriter)
Given two scf.for loops, target and source, fuses target into source.
Definition Utils.cpp:1544
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
TileLoops extractFixedOuterLoops(scf::ForOp rootFOrOp, ArrayRef< int64_t > sizes)
Definition Utils.cpp:1449
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...
Definition Utils.cpp:799
SmallVector< scf::ForOp, 8 > Loops
Tile a nest of standard for loops rooted at rootForOp by finding such parametric tile sizes that the ...
Definition Utils.h:170
FailureOr< scf::ForallOp > normalizeForallOp(RewriterBase &rewriter, scf::ForallOp forallOp)
Normalize an scf.forall operation.
Definition Utils.cpp:1597
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
std::optional< scf::ForOp > epilogueLoopOp
Definition Utils.h:111
std::optional< scf::ForOp > mainLoopOp
Definition Utils.h:110