1 //===- AffineCanonicalizationUtils.cpp - Affine Canonicalization in SCF ---===//
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 // Utility functions to canonicalize affine ops within SCF op regions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/SCF/Utils/AffineCanonicalizationUtils.h"
14 #include "mlir/Dialect/Affine/Analysis/AffineStructures.h"
15 #include "mlir/Dialect/Affine/IR/AffineOps.h"
16 #include "mlir/Dialect/SCF/SCF.h"
17 #include "mlir/Dialect/Utils/StaticValueUtils.h"
18 #include "mlir/IR/AffineMap.h"
19 #include "mlir/IR/Matchers.h"
20 #include "mlir/IR/PatternMatch.h"
21 #include "llvm/Support/Debug.h"
22 
23 #define DEBUG_TYPE "mlir-scf-affine-utils"
24 
25 using namespace mlir;
26 
27 static void unpackOptionalValues(ArrayRef<Optional<Value>> source,
28                                  SmallVector<Value> &target) {
29   target = llvm::to_vector<4>(llvm::map_range(source, [](Optional<Value> val) {
30     return val.hasValue() ? *val : Value();
31   }));
32 }
33 
34 /// Bound an identifier `pos` in a given FlatAffineValueConstraints with
35 /// constraints drawn from an affine map. Before adding the constraint, the
36 /// dimensions/symbols of the affine map are aligned with `constraints`.
37 /// `operands` are the SSA Value operands used with the affine map.
38 /// Note: This function adds a new symbol column to the `constraints` for each
39 /// dimension/symbol that exists in the affine map but not in `constraints`.
40 static LogicalResult alignAndAddBound(FlatAffineValueConstraints &constraints,
41                                       FlatAffineConstraints::BoundType type,
42                                       unsigned pos, AffineMap map,
43                                       ValueRange operands) {
44   SmallVector<Value> dims, syms, newSyms;
45   unpackOptionalValues(constraints.getMaybeDimValues(), dims);
46   unpackOptionalValues(constraints.getMaybeSymbolValues(), syms);
47 
48   AffineMap alignedMap =
49       alignAffineMapWithValues(map, operands, dims, syms, &newSyms);
50   for (unsigned i = syms.size(); i < newSyms.size(); ++i)
51     constraints.appendSymbolId(newSyms[i]);
52   return constraints.addBound(type, pos, alignedMap);
53 }
54 
55 /// Add `val` to each result of `map`.
56 static AffineMap addConstToResults(AffineMap map, int64_t val) {
57   SmallVector<AffineExpr> newResults;
58   for (AffineExpr r : map.getResults())
59     newResults.push_back(r + val);
60   return AffineMap::get(map.getNumDims(), map.getNumSymbols(), newResults,
61                         map.getContext());
62 }
63 
64 /// This function tries to canonicalize min/max operations by proving that their
65 /// value is bounded by the same lower and upper bound. In that case, the
66 /// operation can be folded away.
67 ///
68 /// Bounds are computed by FlatAffineValueConstraints. Invariants required for
69 /// finding/proving bounds should be supplied via `constraints`.
70 ///
71 /// 1. Add dimensions for `op` and `opBound` (lower or upper bound of `op`).
72 /// 2. Compute an upper bound of `op` (in case of `isMin`) or a lower bound (in
73 ///    case of `!isMin`) and bind it to `opBound`. SSA values that are used in
74 ///    `op` but are not part of `constraints`, are added as extra symbols.
75 /// 3. For each result of `op`: Add result as a dimension `r_i`. Prove that:
76 ///    * If `isMin`: r_i >= opBound
77 ///    * If `isMax`: r_i <= opBound
78 ///    If this is the case, ub(op) == lb(op).
79 /// 4. Replace `op` with `opBound`.
80 ///
81 /// In summary, the following constraints are added throughout this function.
82 /// Note: `invar` are dimensions added by the caller to express the invariants.
83 /// (Showing only the case where `isMin`.)
84 ///
85 ///  invar |    op | opBound | r_i | extra syms... | const |           eq/ineq
86 ///  ------+-------+---------+-----+---------------+-------+-------------------
87 ///   (various eq./ineq. constraining `invar`, added by the caller)
88 ///    ... |     0 |       0 |   0 |             0 |   ... |               ...
89 ///  ------+-------+---------+-----+---------------+-------+-------------------
90 ///   (various ineq. constraining `op` in terms of `op` operands (`invar` and
91 ///    extra `op` operands "extra syms" that are not in `invar`)).
92 ///    ... |    -1 |       0 |   0 |           ... |   ... |              >= 0
93 ///  ------+-------+---------+-----+---------------+-------+-------------------
94 ///   (set `opBound` to `op` upper bound in terms of `invar` and "extra syms")
95 ///    ... |     0 |      -1 |   0 |           ... |   ... |               = 0
96 ///  ------+-------+---------+-----+---------------+-------+-------------------
97 ///   (for each `op` map result r_i: set r_i to corresponding map result,
98 ///    prove that r_i >= minOpUb via contradiction)
99 ///    ... |     0 |       0 |  -1 |           ... |   ... |               = 0
100 ///      0 |     0 |       1 |  -1 |             0 |    -1 |              >= 0
101 ///
102 static LogicalResult
103 canonicalizeMinMaxOp(RewriterBase &rewriter, Operation *op, AffineMap map,
104                      ValueRange operands, bool isMin,
105                      FlatAffineValueConstraints constraints) {
106   RewriterBase::InsertionGuard guard(rewriter);
107   unsigned numResults = map.getNumResults();
108 
109   // Add a few extra dimensions.
110   unsigned dimOp = constraints.appendDimId();      // `op`
111   unsigned dimOpBound = constraints.appendDimId(); // `op` lower/upper bound
112   unsigned resultDimStart = constraints.appendDimId(/*num=*/numResults);
113 
114   // Add an inequality for each result expr_i of map:
115   // isMin: op <= expr_i, !isMin: op >= expr_i
116   auto boundType =
117       isMin ? FlatAffineConstraints::UB : FlatAffineConstraints::LB;
118   // Upper bounds are exclusive, so add 1. (`affine.min` ops are inclusive.)
119   AffineMap mapLbUb = isMin ? addConstToResults(map, 1) : map;
120   if (failed(
121           alignAndAddBound(constraints, boundType, dimOp, mapLbUb, operands)))
122     return failure();
123 
124   // Try to compute a lower/upper bound for op, expressed in terms of the other
125   // `dims` and extra symbols.
126   SmallVector<AffineMap> opLb(1), opUb(1);
127   constraints.getSliceBounds(dimOp, 1, rewriter.getContext(), &opLb, &opUb);
128   AffineMap sliceBound = isMin ? opUb[0] : opLb[0];
129   // TODO: `getSliceBounds` may return multiple bounds at the moment. This is
130   // a TODO of `getSliceBounds` and not handled here.
131   if (!sliceBound || sliceBound.getNumResults() != 1)
132     return failure(); // No or multiple bounds found.
133   // Recover the inclusive UB in the case of an `affine.min`.
134   AffineMap boundMap = isMin ? addConstToResults(sliceBound, -1) : sliceBound;
135 
136   // Add an equality: Set dimOpBound to computed bound.
137   // Add back dimension for op. (Was removed by `getSliceBounds`.)
138   AffineMap alignedBoundMap = boundMap.shiftDims(/*shift=*/1, /*offset=*/dimOp);
139   if (failed(constraints.addBound(FlatAffineConstraints::EQ, dimOpBound,
140                                   alignedBoundMap)))
141     return failure();
142 
143   // If the constraint system is empty, there is an inconsistency. (E.g., this
144   // can happen if loop lb > ub.)
145   if (constraints.isEmpty())
146     return failure();
147 
148   // In the case of `isMin` (`!isMin` is inversed):
149   // Prove that each result of `map` has a lower bound that is equal to (or
150   // greater than) the upper bound of `op` (`dimOpBound`). In that case, `op`
151   // can be replaced with the bound. I.e., prove that for each result
152   // expr_i (represented by dimension r_i):
153   //
154   // r_i >= opBound
155   //
156   // To prove this inequality, add its negation to the constraint set and prove
157   // that the constraint set is empty.
158   for (unsigned i = resultDimStart; i < resultDimStart + numResults; ++i) {
159     FlatAffineValueConstraints newConstr(constraints);
160 
161     // Add an equality: r_i = expr_i
162     // Note: These equalities could have been added earlier and used to express
163     // minOp <= expr_i. However, then we run the risk that `getSliceBounds`
164     // computes minOpUb in terms of r_i dims, which is not desired.
165     if (failed(alignAndAddBound(newConstr, FlatAffineConstraints::EQ, i,
166                                 map.getSubMap({i - resultDimStart}), operands)))
167       return failure();
168 
169     // If `isMin`:  Add inequality: r_i < opBound
170     //              equiv.: opBound - r_i - 1 >= 0
171     // If `!isMin`: Add inequality: r_i > opBound
172     //              equiv.: -opBound + r_i - 1 >= 0
173     SmallVector<int64_t> ineq(newConstr.getNumCols(), 0);
174     ineq[dimOpBound] = isMin ? 1 : -1;
175     ineq[i] = isMin ? -1 : 1;
176     ineq[newConstr.getNumCols() - 1] = -1;
177     newConstr.addInequality(ineq);
178     if (!newConstr.isEmpty())
179       return failure();
180   }
181 
182   // Lower and upper bound of `op` are equal. Replace `minOp` with its bound.
183   AffineMap newMap = alignedBoundMap;
184   SmallVector<Value> newOperands;
185   unpackOptionalValues(constraints.getMaybeDimAndSymbolValues(), newOperands);
186   mlir::canonicalizeMapAndOperands(&newMap, &newOperands);
187   rewriter.setInsertionPoint(op);
188   rewriter.replaceOpWithNewOp<AffineApplyOp>(op, newMap, newOperands);
189   return success();
190 }
191 
192 static LogicalResult
193 addLoopRangeConstraints(FlatAffineValueConstraints &constraints, Value iv,
194                         Value lb, Value ub, Value step,
195                         RewriterBase &rewriter) {
196   // FlatAffineConstraints does not support semi-affine expressions.
197   // Therefore, only constant step values are supported.
198   auto stepInt = getConstantIntValue(step);
199   if (!stepInt)
200     return failure();
201 
202   unsigned dimIv = constraints.appendDimId(iv);
203   unsigned dimLb = constraints.appendDimId(lb);
204   unsigned dimUb = constraints.appendDimId(ub);
205 
206   // If loop lower/upper bounds are constant: Add EQ constraint.
207   Optional<int64_t> lbInt = getConstantIntValue(lb);
208   Optional<int64_t> ubInt = getConstantIntValue(ub);
209   if (lbInt)
210     constraints.addBound(FlatAffineConstraints::EQ, dimLb, *lbInt);
211   if (ubInt)
212     constraints.addBound(FlatAffineConstraints::EQ, dimUb, *ubInt);
213 
214   // iv >= lb (equiv.: iv - lb >= 0)
215   SmallVector<int64_t> ineqLb(constraints.getNumCols(), 0);
216   ineqLb[dimIv] = 1;
217   ineqLb[dimLb] = -1;
218   constraints.addInequality(ineqLb);
219 
220   // iv < lb + step * ((ub - lb - 1) floorDiv step) + 1
221   AffineExpr exprLb = lbInt ? rewriter.getAffineConstantExpr(*lbInt)
222                             : rewriter.getAffineDimExpr(dimLb);
223   AffineExpr exprUb = ubInt ? rewriter.getAffineConstantExpr(*ubInt)
224                             : rewriter.getAffineDimExpr(dimUb);
225   AffineExpr ivUb =
226       exprLb + 1 + (*stepInt * ((exprUb - exprLb - 1).floorDiv(*stepInt)));
227   auto map = AffineMap::get(
228       /*dimCount=*/constraints.getNumDimIds(),
229       /*symbolCount=*/constraints.getNumSymbolIds(), /*result=*/ivUb);
230 
231   return constraints.addBound(FlatAffineConstraints::UB, dimIv, map);
232 }
233 
234 /// Canonicalize min/max operations in the context of for loops with a known
235 /// range. Call `canonicalizeMinMaxOp` and add the following constraints to
236 /// the constraint system (along with the missing dimensions):
237 ///
238 /// * iv >= lb
239 /// * iv < lb + step * ((ub - lb - 1) floorDiv step) + 1
240 ///
241 /// Note: Due to limitations of FlatAffineConstraints, only constant step sizes
242 /// are currently supported.
243 LogicalResult scf::canonicalizeMinMaxOpInLoop(RewriterBase &rewriter,
244                                               Operation *op, AffineMap map,
245                                               ValueRange operands, bool isMin,
246                                               LoopMatcherFn loopMatcher) {
247   FlatAffineValueConstraints constraints;
248   DenseSet<Value> allIvs;
249 
250   // Find all iteration variables among `minOp`'s operands add constrain them.
251   for (Value operand : operands) {
252     // Skip duplicate ivs.
253     if (llvm::find(allIvs, operand) != allIvs.end())
254       continue;
255 
256     // If `operand` is an iteration variable: Find corresponding loop
257     // bounds and step.
258     Value iv = operand;
259     Value lb, ub, step;
260     if (failed(loopMatcher(operand, lb, ub, step)))
261       continue;
262     allIvs.insert(iv);
263 
264     if (failed(
265             addLoopRangeConstraints(constraints, iv, lb, ub, step, rewriter)))
266       return failure();
267   }
268 
269   return canonicalizeMinMaxOp(rewriter, op, map, operands, isMin, constraints);
270 }
271 
272 /// Try to simplify a min/max operation `op` after loop peeling. This function
273 /// can simplify min/max operations such as (ub is the previous upper bound of
274 /// the unpeeled loop):
275 /// ```
276 /// #map = affine_map<(d0)[s0, s1] -> (s0, -d0 + s1)>
277 /// %r = affine.min #affine.min #map(%iv)[%step, %ub]
278 /// ```
279 /// and rewrites them into (in the case the peeled loop):
280 /// ```
281 /// %r = %step
282 /// ```
283 /// min/max operations inside the partial iteration are rewritten in a similar
284 /// way.
285 ///
286 /// This function builds up a set of constraints, capable of proving that:
287 /// * Inside the peeled loop: min(step, ub - iv) == step
288 /// * Inside the partial iteration: min(step, ub - iv) == ub - iv
289 ///
290 /// Returns `success` if the given operation was replaced by a new operation;
291 /// `failure` otherwise.
292 ///
293 /// Note: `ub` is the previous upper bound of the loop (before peeling).
294 /// `insideLoop` must be true for min/max ops inside the loop and false for
295 /// affine.min ops inside the partial iteration. For an explanation of the other
296 /// parameters, see comment of `canonicalizeMinMaxOpInLoop`.
297 LogicalResult scf::rewritePeeledMinMaxOp(RewriterBase &rewriter, Operation *op,
298                                          AffineMap map, ValueRange operands,
299                                          bool isMin, Value iv, Value ub,
300                                          Value step, bool insideLoop) {
301   FlatAffineValueConstraints constraints;
302   constraints.appendDimId({iv, ub, step});
303   if (auto constUb = getConstantIntValue(ub))
304     constraints.addBound(FlatAffineConstraints::EQ, 1, *constUb);
305   if (auto constStep = getConstantIntValue(step))
306     constraints.addBound(FlatAffineConstraints::EQ, 2, *constStep);
307 
308   // Add loop peeling invariant. This is the main piece of knowledge that
309   // enables AffineMinOp simplification.
310   if (insideLoop) {
311     // ub - iv >= step (equiv.: -iv + ub - step + 0 >= 0)
312     // Intuitively: Inside the peeled loop, every iteration is a "full"
313     // iteration, i.e., step divides the iteration space `ub - lb` evenly.
314     constraints.addInequality({-1, 1, -1, 0});
315   } else {
316     // ub - iv < step (equiv.: iv + -ub + step - 1 >= 0)
317     // Intuitively: `iv` is the split bound here, i.e., the iteration variable
318     // value of the very last iteration (in the unpeeled loop). At that point,
319     // there are less than `step` elements remaining. (Otherwise, the peeled
320     // loop would run for at least one more iteration.)
321     constraints.addInequality({1, -1, 1, -1});
322   }
323 
324   return canonicalizeMinMaxOp(rewriter, op, map, operands, isMin, constraints);
325 }
326