1 //===- LoopSpecialization.cpp - scf.parallel/SCR.for specialization -------===//
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 // Specializes parallel loops and for loops for easier unrolling and
10 // vectorization.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PassDetail.h"
15 #include "mlir/Analysis/AffineStructures.h"
16 #include "mlir/Dialect/Affine/IR/AffineOps.h"
17 #include "mlir/Dialect/SCF/Passes.h"
18 #include "mlir/Dialect/SCF/SCF.h"
19 #include "mlir/Dialect/SCF/Transforms.h"
20 #include "mlir/Dialect/StandardOps/IR/Ops.h"
21 #include "mlir/Dialect/Utils/StaticValueUtils.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/BlockAndValueMapping.h"
24 #include "mlir/IR/PatternMatch.h"
25 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
26 #include "llvm/ADT/DenseMap.h"
27 
28 using namespace mlir;
29 using scf::ForOp;
30 using scf::ParallelOp;
31 
32 /// Rewrite a parallel loop with bounds defined by an affine.min with a constant
33 /// into 2 loops after checking if the bounds are equal to that constant. This
34 /// is beneficial if the loop will almost always have the constant bound and
35 /// that version can be fully unrolled and vectorized.
36 static void specializeParallelLoopForUnrolling(ParallelOp op) {
37   SmallVector<int64_t, 2> constantIndices;
38   constantIndices.reserve(op.upperBound().size());
39   for (auto bound : op.upperBound()) {
40     auto minOp = bound.getDefiningOp<AffineMinOp>();
41     if (!minOp)
42       return;
43     int64_t minConstant = std::numeric_limits<int64_t>::max();
44     for (AffineExpr expr : minOp.map().getResults()) {
45       if (auto constantIndex = expr.dyn_cast<AffineConstantExpr>())
46         minConstant = std::min(minConstant, constantIndex.getValue());
47     }
48     if (minConstant == std::numeric_limits<int64_t>::max())
49       return;
50     constantIndices.push_back(minConstant);
51   }
52 
53   OpBuilder b(op);
54   BlockAndValueMapping map;
55   Value cond;
56   for (auto bound : llvm::zip(op.upperBound(), constantIndices)) {
57     Value constant = b.create<ConstantIndexOp>(op.getLoc(), std::get<1>(bound));
58     Value cmp = b.create<CmpIOp>(op.getLoc(), CmpIPredicate::eq,
59                                  std::get<0>(bound), constant);
60     cond = cond ? b.create<AndOp>(op.getLoc(), cond, cmp) : cmp;
61     map.map(std::get<0>(bound), constant);
62   }
63   auto ifOp = b.create<scf::IfOp>(op.getLoc(), cond, /*withElseRegion=*/true);
64   ifOp.getThenBodyBuilder().clone(*op.getOperation(), map);
65   ifOp.getElseBodyBuilder().clone(*op.getOperation());
66   op.erase();
67 }
68 
69 /// Rewrite a for loop with bounds defined by an affine.min with a constant into
70 /// 2 loops after checking if the bounds are equal to that constant. This is
71 /// beneficial if the loop will almost always have the constant bound and that
72 /// version can be fully unrolled and vectorized.
73 static void specializeForLoopForUnrolling(ForOp op) {
74   auto bound = op.upperBound();
75   auto minOp = bound.getDefiningOp<AffineMinOp>();
76   if (!minOp)
77     return;
78   int64_t minConstant = std::numeric_limits<int64_t>::max();
79   for (AffineExpr expr : minOp.map().getResults()) {
80     if (auto constantIndex = expr.dyn_cast<AffineConstantExpr>())
81       minConstant = std::min(minConstant, constantIndex.getValue());
82   }
83   if (minConstant == std::numeric_limits<int64_t>::max())
84     return;
85 
86   OpBuilder b(op);
87   BlockAndValueMapping map;
88   Value constant = b.create<ConstantIndexOp>(op.getLoc(), minConstant);
89   Value cond =
90       b.create<CmpIOp>(op.getLoc(), CmpIPredicate::eq, bound, constant);
91   map.map(bound, constant);
92   auto ifOp = b.create<scf::IfOp>(op.getLoc(), cond, /*withElseRegion=*/true);
93   ifOp.getThenBodyBuilder().clone(*op.getOperation(), map);
94   ifOp.getElseBodyBuilder().clone(*op.getOperation());
95   op.erase();
96 }
97 
98 /// Rewrite a for loop with bounds/step that potentially do not divide evenly
99 /// into a for loop where the step divides the iteration space evenly, followed
100 /// by an scf.if for the last (partial) iteration (if any).
101 ///
102 /// This function rewrites the given scf.for loop in-place and creates a new
103 /// scf.if operation for the last iteration. It replaces all uses of the
104 /// unpeeled loop with the results of the newly generated scf.if.
105 ///
106 /// The newly generated scf.if operation is returned via `ifOp`. The boundary
107 /// at which the loop is split (new upper bound) is returned via `splitBound`.
108 /// The return value indicates whether the loop was rewritten or not.
109 static LogicalResult peelForLoop(RewriterBase &b, ForOp forOp, scf::IfOp &ifOp,
110                                  Value &splitBound) {
111   RewriterBase::InsertionGuard guard(b);
112   auto lbInt = getConstantIntValue(forOp.lowerBound());
113   auto ubInt = getConstantIntValue(forOp.upperBound());
114   auto stepInt = getConstantIntValue(forOp.step());
115 
116   // No specialization necessary if step already divides upper bound evenly.
117   if (lbInt && ubInt && stepInt && (*ubInt - *lbInt) % *stepInt == 0)
118     return failure();
119   // No specialization necessary if step size is 1.
120   if (stepInt == static_cast<int64_t>(1))
121     return failure();
122 
123   auto loc = forOp.getLoc();
124   AffineExpr sym0, sym1, sym2;
125   bindSymbols(b.getContext(), sym0, sym1, sym2);
126   // New upper bound: %ub - (%ub - %lb) mod %step
127   auto modMap = AffineMap::get(0, 3, {sym1 - ((sym1 - sym0) % sym2)});
128   b.setInsertionPoint(forOp);
129   splitBound = b.createOrFold<AffineApplyOp>(
130       loc, modMap,
131       ValueRange{forOp.lowerBound(), forOp.upperBound(), forOp.step()});
132 
133   // Set new upper loop bound.
134   Value previousUb = forOp.upperBound();
135   b.updateRootInPlace(forOp,
136                       [&]() { forOp.upperBoundMutable().assign(splitBound); });
137   b.setInsertionPointAfter(forOp);
138 
139   // Do we need one more iteration?
140   Value hasMoreIter =
141       b.create<CmpIOp>(loc, CmpIPredicate::slt, splitBound, previousUb);
142 
143   // Create IfOp for last iteration.
144   auto resultTypes = forOp.getResultTypes();
145   ifOp = b.create<scf::IfOp>(loc, resultTypes, hasMoreIter,
146                              /*withElseRegion=*/!resultTypes.empty());
147   forOp.replaceAllUsesWith(ifOp->getResults());
148 
149   // Build then case.
150   BlockAndValueMapping bvm;
151   bvm.map(forOp.region().getArgument(0), splitBound);
152   for (auto it : llvm::zip(forOp.getRegionIterArgs(), forOp->getResults())) {
153     bvm.map(std::get<0>(it), std::get<1>(it));
154   }
155   b.cloneRegionBefore(forOp.region(), ifOp.thenRegion(),
156                       ifOp.thenRegion().begin(), bvm);
157   // Build else case.
158   if (!resultTypes.empty())
159     ifOp.getElseBodyBuilder(b.getListener())
160         .create<scf::YieldOp>(loc, forOp->getResults());
161 
162   return success();
163 }
164 
165 static void unpackOptionalValues(ArrayRef<Optional<Value>> source,
166                                  SmallVector<Value> &target) {
167   target = llvm::to_vector<4>(llvm::map_range(source, [](Optional<Value> val) {
168     return val.hasValue() ? *val : Value();
169   }));
170 }
171 
172 /// Bound an identifier `pos` in a given FlatAffineValueConstraints with
173 /// constraints drawn from an affine map. Before adding the constraint, the
174 /// dimensions/symbols of the affine map are aligned with `constraints`.
175 /// `operands` are the SSA Value operands used with the affine map.
176 /// Note: This function adds a new symbol column to the `constraints` for each
177 /// dimension/symbol that exists in the affine map but not in `constraints`.
178 static LogicalResult alignAndAddBound(FlatAffineValueConstraints &constraints,
179                                       FlatAffineConstraints::BoundType type,
180                                       unsigned pos, AffineMap map,
181                                       ValueRange operands) {
182   SmallVector<Value> dims, syms, newSyms;
183   unpackOptionalValues(constraints.getMaybeDimValues(), dims);
184   unpackOptionalValues(constraints.getMaybeSymbolValues(), syms);
185 
186   AffineMap alignedMap =
187       alignAffineMapWithValues(map, operands, dims, syms, &newSyms);
188   for (unsigned i = syms.size(); i < newSyms.size(); ++i)
189     constraints.appendSymbolId(newSyms[i]);
190   return constraints.addBound(type, pos, alignedMap);
191 }
192 
193 /// This function tries to canonicalize min/max operations by proving that their
194 /// value is bounded by the same lower and upper bound. In that case, the
195 /// operation can be folded away.
196 ///
197 /// Bounds are computed by FlatAffineValueConstraints. Invariants required for
198 /// finding/proving bounds should be supplied via `constraints`.
199 ///
200 /// 1. Add dimensions for `op` and `opBound` (lower or upper bound of `op`).
201 /// 2. Compute an upper bound of `op` (in case of `isMin`) or a lower bound (in
202 ///    case of `!isMin`) and bind it to `opBound`. SSA values that are used in
203 ///    `op` but are not part of `constraints`, are added as extra symbols.
204 /// 3. For each result of `op`: Add result as a dimension `r_i`. Prove that:
205 ///    * If `isMin`: r_i >= opBound
206 ///    * If `isMax`: r_i <= opBound
207 ///    If this is the case, ub(op) == lb(op).
208 /// 4. Replace `op` with `opBound`.
209 ///
210 /// In summary, the following constraints are added throughout this function.
211 /// Note: `invar` are dimensions added by the caller to express the invariants.
212 /// (Showing only the case where `isMin`.)
213 ///
214 ///  invar |    op | opBound | r_i | extra syms... | const |           eq/ineq
215 ///  ------+-------+---------+-----+---------------+-------+-------------------
216 ///   (various eq./ineq. constraining `invar`, added by the caller)
217 ///    ... |     0 |       0 |   0 |             0 |   ... |               ...
218 ///  ------+-------+---------+-----+---------------+-------+-------------------
219 ///   (various ineq. constraining `op` in terms of `op` operands (`invar` and
220 ///    extra `op` operands "extra syms" that are not in `invar`)).
221 ///    ... |    -1 |       0 |   0 |           ... |   ... |              >= 0
222 ///  ------+-------+---------+-----+---------------+-------+-------------------
223 ///   (set `opBound` to `op` upper bound in terms of `invar` and "extra syms")
224 ///    ... |     0 |      -1 |   0 |           ... |   ... |               = 0
225 ///  ------+-------+---------+-----+---------------+-------+-------------------
226 ///   (for each `op` map result r_i: set r_i to corresponding map result,
227 ///    prove that r_i >= minOpUb via contradiction)
228 ///    ... |     0 |       0 |  -1 |           ... |   ... |               = 0
229 ///      0 |     0 |       1 |  -1 |             0 |    -1 |              >= 0
230 ///
231 static LogicalResult
232 canonicalizeMinMaxOp(RewriterBase &rewriter, Operation *op, AffineMap map,
233                      ValueRange operands, bool isMin,
234                      FlatAffineValueConstraints constraints) {
235   RewriterBase::InsertionGuard guard(rewriter);
236   unsigned numResults = map.getNumResults();
237 
238   // Add a few extra dimensions.
239   unsigned dimOp = constraints.appendDimId();      // `op`
240   unsigned dimOpBound = constraints.appendDimId(); // `op` lower/upper bound
241   unsigned resultDimStart = constraints.appendDimId(/*num=*/numResults);
242 
243   // Add an inequality for each result expr_i of map:
244   // isMin: op <= expr_i, !isMin: op >= expr_i
245   auto boundType =
246       isMin ? FlatAffineConstraints::UB : FlatAffineConstraints::LB;
247   if (failed(alignAndAddBound(constraints, boundType, dimOp, map, operands)))
248     return failure();
249 
250   // Try to compute a lower/upper bound for op, expressed in terms of the other
251   // `dims` and extra symbols.
252   SmallVector<AffineMap> opLb(1), opUb(1);
253   constraints.getSliceBounds(dimOp, 1, rewriter.getContext(), &opLb, &opUb);
254   AffineMap boundMap = isMin ? opUb[0] : opLb[0];
255   // TODO: `getSliceBounds` may return multiple bounds at the moment. This is
256   // a TODO of `getSliceBounds` and not handled here.
257   if (!boundMap || boundMap.getNumResults() != 1)
258     return failure(); // No or multiple bounds found.
259 
260   // Add an equality: Set dimOpBound to computed bound.
261   // Add back dimension for op. (Was removed by `getSliceBounds`.)
262   AffineMap alignedBoundMap = boundMap.shiftDims(/*shift=*/1, /*offset=*/dimOp);
263   if (failed(constraints.addBound(FlatAffineConstraints::EQ, dimOpBound,
264                                   alignedBoundMap)))
265     return failure();
266 
267   // If the constraint system is empty, there is an inconsistency. (E.g., this
268   // can happen if loop lb > ub.)
269   if (constraints.isEmpty())
270     return failure();
271 
272   // In the case of `isMin` (`!isMin` is inversed):
273   // Prove that each result of `map` has a lower bound that is equal to (or
274   // greater than) the upper bound of `op` (`dimOpBound`). In that case, `op`
275   // can be replaced with the bound. I.e., prove that for each result
276   // expr_i (represented by dimension r_i):
277   //
278   // r_i >= opBound
279   //
280   // To prove this inequality, add its negation to the constraint set and prove
281   // that the constraint set is empty.
282   for (unsigned i = resultDimStart; i < resultDimStart + numResults; ++i) {
283     FlatAffineValueConstraints newConstr(constraints);
284 
285     // Add an equality: r_i = expr_i
286     // Note: These equalities could have been added earlier and used to express
287     // minOp <= expr_i. However, then we run the risk that `getSliceBounds`
288     // computes minOpUb in terms of r_i dims, which is not desired.
289     if (failed(alignAndAddBound(newConstr, FlatAffineConstraints::EQ, i,
290                                 map.getSubMap({i - resultDimStart}), operands)))
291       return failure();
292 
293     // If `isMin`:  Add inequality: r_i < opBound
294     //              equiv.: opBound - r_i - 1 >= 0
295     // If `!isMin`: Add inequality: r_i > opBound
296     //              equiv.: -opBound + r_i - 1 >= 0
297     SmallVector<int64_t> ineq(newConstr.getNumCols(), 0);
298     ineq[dimOpBound] = isMin ? 1 : -1;
299     ineq[i] = isMin ? -1 : 1;
300     ineq[newConstr.getNumCols() - 1] = -1;
301     newConstr.addInequality(ineq);
302     if (!newConstr.isEmpty())
303       return failure();
304   }
305 
306   // Lower and upper bound of `op` are equal. Replace `minOp` with its bound.
307   AffineMap newMap = alignedBoundMap;
308   SmallVector<Value> newOperands;
309   unpackOptionalValues(constraints.getMaybeDimAndSymbolValues(), newOperands);
310   mlir::canonicalizeMapAndOperands(&newMap, &newOperands);
311   rewriter.setInsertionPoint(op);
312   rewriter.replaceOpWithNewOp<AffineApplyOp>(op, newMap, newOperands);
313   return success();
314 }
315 
316 /// Try to simplify a min/max operation `op` after loop peeling. This function
317 /// can simplify min/max operations such as (ub is the previous upper bound of
318 /// the unpeeled loop):
319 /// ```
320 /// #map = affine_map<(d0)[s0, s1] -> (s0, -d0 + s1)>
321 /// %r = affine.min #affine.min #map(%iv)[%step, %ub]
322 /// ```
323 /// and rewrites them into (in the case the peeled loop):
324 /// ```
325 /// %r = %step
326 /// ```
327 /// min/max operations inside the generated scf.if operation are rewritten in
328 /// a similar way.
329 ///
330 /// This function builds up a set of constraints, capable of proving that:
331 /// * Inside the peeled loop: min(step, ub - iv) == step
332 /// * Inside the scf.if operation: min(step, ub - iv) == ub - iv
333 ///
334 /// Returns `success` if the given operation was replaced by a new operation;
335 /// `failure` otherwise.
336 ///
337 /// Note: `ub` is the previous upper bound of the loop (before peeling).
338 /// `insideLoop` must be true for min/max ops inside the loop and false for
339 /// affine.min ops inside the scf.for op. For an explanation of the other
340 /// parameters, see comment of `canonicalizeMinMaxOpInLoop`.
341 static LogicalResult rewritePeeledMinMaxOp(RewriterBase &rewriter,
342                                            Operation *op, AffineMap map,
343                                            ValueRange operands, bool isMin,
344                                            Value iv, Value ub, Value step,
345                                            bool insideLoop) {
346   FlatAffineValueConstraints constraints;
347   constraints.appendDimId({iv, ub, step});
348   if (auto constUb = getConstantIntValue(ub))
349     constraints.addBound(FlatAffineConstraints::EQ, 1, *constUb);
350   if (auto constStep = getConstantIntValue(step))
351     constraints.addBound(FlatAffineConstraints::EQ, 2, *constStep);
352 
353   // Add loop peeling invariant. This is the main piece of knowledge that
354   // enables AffineMinOp simplification.
355   if (insideLoop) {
356     // ub - iv >= step (equiv.: -iv + ub - step + 0 >= 0)
357     // Intuitively: Inside the peeled loop, every iteration is a "full"
358     // iteration, i.e., step divides the iteration space `ub - lb` evenly.
359     constraints.addInequality({-1, 1, -1, 0});
360   } else {
361     // ub - iv < step (equiv.: iv + -ub + step - 1 >= 0)
362     // Intuitively: `iv` is the split bound here, i.e., the iteration variable
363     // value of the very last iteration (in the unpeeled loop). At that point,
364     // there are less than `step` elements remaining. (Otherwise, the peeled
365     // loop would run for at least one more iteration.)
366     constraints.addInequality({1, -1, 1, -1});
367   }
368 
369   return canonicalizeMinMaxOp(rewriter, op, map, operands, isMin, constraints);
370 }
371 
372 template <typename OpTy, bool IsMin>
373 static void
374 rewriteAffineOpAfterPeeling(RewriterBase &rewriter, ForOp forOp, scf::IfOp ifOp,
375                             Value iv, Value splitBound, Value ub, Value step) {
376   forOp.walk([&](OpTy affineOp) {
377     (void)rewritePeeledMinMaxOp(rewriter, affineOp, affineOp.getAffineMap(),
378                                 affineOp.operands(), IsMin, iv, ub, step,
379                                 /*insideLoop=*/true);
380   });
381   ifOp.walk([&](OpTy affineOp) {
382     (void)rewritePeeledMinMaxOp(rewriter, affineOp, affineOp.getAffineMap(),
383                                 affineOp.operands(), IsMin, splitBound, ub,
384                                 step, /*insideLoop=*/false);
385   });
386 }
387 
388 LogicalResult mlir::scf::peelAndCanonicalizeForLoop(RewriterBase &rewriter,
389                                                     ForOp forOp,
390                                                     scf::IfOp &ifOp) {
391   Value ub = forOp.upperBound();
392   Value splitBound;
393   if (failed(peelForLoop(rewriter, forOp, ifOp, splitBound)))
394     return failure();
395 
396   // Rewrite affine.min and affine.max ops.
397   Value iv = forOp.getInductionVar(), step = forOp.step();
398   rewriteAffineOpAfterPeeling<AffineMinOp, /*IsMin=*/true>(
399       rewriter, forOp, ifOp, iv, splitBound, ub, step);
400   rewriteAffineOpAfterPeeling<AffineMaxOp, /*IsMin=*/false>(
401       rewriter, forOp, ifOp, iv, splitBound, ub, step);
402 
403   return success();
404 }
405 
406 /// Canonicalize min/max operations in the context of for loops with a known
407 /// range. Call `canonicalizeMinMaxOp` and add the following constraints to
408 /// the constraint system (along with the missing dimensions):
409 ///
410 /// * iv >= lb
411 /// * iv < lb + step * ((ub - lb - 1) floorDiv step) + 1
412 ///
413 /// Note: Due to limitations of FlatAffineConstraints, only constant step sizes
414 /// are currently supported.
415 LogicalResult
416 mlir::scf::canonicalizeMinMaxOpInLoop(RewriterBase &rewriter, Operation *op,
417                                       AffineMap map, ValueRange operands,
418                                       bool isMin, LoopMatcherFn loopMatcher) {
419   FlatAffineValueConstraints constraints;
420   DenseSet<Value> allIvs;
421 
422   // Find all iteration variables among `minOp`'s operands add constrain them.
423   for (Value operand : operands) {
424     // Skip duplicate ivs.
425     if (llvm::find(allIvs, operand) != allIvs.end())
426       continue;
427 
428     // If `operand` is an iteration variable: Find corresponding loop
429     // bounds and step.
430     Value iv = operand;
431     Value lb, ub, step;
432     if (failed(loopMatcher(operand, lb, ub, step)))
433       continue;
434     allIvs.insert(iv);
435 
436     // FlatAffineConstraints does not support semi-affine expressions.
437     // Therefore, only constant step values are supported.
438     auto stepInt = getConstantIntValue(step);
439     if (!stepInt)
440       continue;
441 
442     unsigned dimIv = constraints.appendDimId(iv);
443     unsigned dimLb = constraints.appendDimId(lb);
444     unsigned dimUb = constraints.appendDimId(ub);
445 
446     // If loop lower/upper bounds are constant: Add EQ constraint.
447     Optional<int64_t> lbInt = getConstantIntValue(lb);
448     Optional<int64_t> ubInt = getConstantIntValue(ub);
449     if (lbInt)
450       constraints.addBound(FlatAffineConstraints::EQ, dimLb, *lbInt);
451     if (ubInt)
452       constraints.addBound(FlatAffineConstraints::EQ, dimUb, *ubInt);
453 
454     // iv >= lb (equiv.: iv - lb >= 0)
455     SmallVector<int64_t> ineqLb(constraints.getNumCols(), 0);
456     ineqLb[dimIv] = 1;
457     ineqLb[dimLb] = -1;
458     constraints.addInequality(ineqLb);
459 
460     // iv < lb + step * ((ub - lb - 1) floorDiv step) + 1
461     AffineExpr exprLb = lbInt ? rewriter.getAffineConstantExpr(*lbInt)
462                               : rewriter.getAffineDimExpr(dimLb);
463     AffineExpr exprUb = ubInt ? rewriter.getAffineConstantExpr(*ubInt)
464                               : rewriter.getAffineDimExpr(dimUb);
465     AffineExpr ivUb =
466         exprLb + 1 + (*stepInt * ((exprUb - exprLb - 1).floorDiv(*stepInt)));
467     auto map = AffineMap::get(
468         /*dimCount=*/constraints.getNumDimIds(),
469         /*symbolCount=*/constraints.getNumSymbolIds(), /*result=*/ivUb);
470 
471     if (failed(constraints.addBound(FlatAffineConstraints::UB, dimIv, map)))
472       return failure();
473   }
474 
475   return canonicalizeMinMaxOp(rewriter, op, map, operands, isMin, constraints);
476 }
477 
478 static constexpr char kPeeledLoopLabel[] = "__peeled_loop__";
479 static constexpr char kPartialIterationLabel[] = "__partial_iteration__";
480 
481 namespace {
482 struct ForLoopPeelingPattern : public OpRewritePattern<ForOp> {
483   ForLoopPeelingPattern(MLIRContext *ctx, bool skipPartial)
484       : OpRewritePattern<ForOp>(ctx), skipPartial(skipPartial) {}
485 
486   LogicalResult matchAndRewrite(ForOp forOp,
487                                 PatternRewriter &rewriter) const override {
488     // Do not peel already peeled loops.
489     if (forOp->hasAttr(kPeeledLoopLabel))
490       return failure();
491     if (skipPartial) {
492       // No peeling of loops inside the partial iteration (scf.if) of another
493       // peeled loop.
494       Operation *op = forOp.getOperation();
495       while ((op = op->getParentOfType<scf::IfOp>())) {
496         if (op->hasAttr(kPartialIterationLabel))
497           return failure();
498       }
499     }
500     // Apply loop peeling.
501     scf::IfOp ifOp;
502     if (failed(peelAndCanonicalizeForLoop(rewriter, forOp, ifOp)))
503       return failure();
504     // Apply label, so that the same loop is not rewritten a second time.
505     rewriter.updateRootInPlace(forOp, [&]() {
506       forOp->setAttr(kPeeledLoopLabel, rewriter.getUnitAttr());
507     });
508     ifOp->setAttr(kPartialIterationLabel, rewriter.getUnitAttr());
509     return success();
510   }
511 
512   /// If set to true, loops inside partial iterations of another peeled loop
513   /// are not peeled. This reduces the size of the generated code. Partial
514   /// iterations are not usually performance critical.
515   /// Note: Takes into account the entire chain of parent operations, not just
516   /// the direct parent.
517   bool skipPartial;
518 };
519 } // namespace
520 
521 namespace {
522 struct ParallelLoopSpecialization
523     : public SCFParallelLoopSpecializationBase<ParallelLoopSpecialization> {
524   void runOnFunction() override {
525     getFunction().walk(
526         [](ParallelOp op) { specializeParallelLoopForUnrolling(op); });
527   }
528 };
529 
530 struct ForLoopSpecialization
531     : public SCFForLoopSpecializationBase<ForLoopSpecialization> {
532   void runOnFunction() override {
533     getFunction().walk([](ForOp op) { specializeForLoopForUnrolling(op); });
534   }
535 };
536 
537 struct ForLoopPeeling : public SCFForLoopPeelingBase<ForLoopPeeling> {
538   void runOnFunction() override {
539     FuncOp funcOp = getFunction();
540     MLIRContext *ctx = funcOp.getContext();
541     RewritePatternSet patterns(ctx);
542     patterns.add<ForLoopPeelingPattern>(ctx, skipPartial);
543     (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
544 
545     // Drop the markers.
546     funcOp.walk([](Operation *op) {
547       op->removeAttr(kPeeledLoopLabel);
548       op->removeAttr(kPartialIterationLabel);
549     });
550   }
551 };
552 } // namespace
553 
554 std::unique_ptr<Pass> mlir::createParallelLoopSpecializationPass() {
555   return std::make_unique<ParallelLoopSpecialization>();
556 }
557 
558 std::unique_ptr<Pass> mlir::createForLoopSpecializationPass() {
559   return std::make_unique<ForLoopSpecialization>();
560 }
561 
562 std::unique_ptr<Pass> mlir::createForLoopPeelingPass() {
563   return std::make_unique<ForLoopPeeling>();
564 }
565