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