xref: /llvm-project/mlir/lib/Interfaces/Utils/InferIntRangeCommon.cpp (revision 93ce8e10870429695a6a1aa8f16446ec1b042445)
1 //===- InferIntRangeCommon.cpp - Inference for common ops ------------===//
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 file contains implementations of range inference for operations that are
10 // common to both the `arith` and `index` dialects to facilitate reuse.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Interfaces/Utils/InferIntRangeCommon.h"
15 
16 #include "mlir/Interfaces/InferIntRangeInterface.h"
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/STLExtras.h"
20 
21 #include "llvm/Support/Debug.h"
22 
23 #include <iterator>
24 #include <optional>
25 
26 using namespace mlir;
27 
28 #define DEBUG_TYPE "int-range-analysis"
29 
30 //===----------------------------------------------------------------------===//
31 // General utilities
32 //===----------------------------------------------------------------------===//
33 
34 /// Function that evaluates the result of doing something on arithmetic
35 /// constants and returns std::nullopt on overflow.
36 using ConstArithFn =
37     function_ref<std::optional<APInt>(const APInt &, const APInt &)>;
38 using ConstArithStdFn =
39     std::function<std::optional<APInt>(const APInt &, const APInt &)>;
40 
41 /// Compute op(minLeft, minRight) and op(maxLeft, maxRight) if possible,
42 /// If either computation overflows, make the result unbounded.
43 static ConstantIntRanges computeBoundsBy(ConstArithFn op, const APInt &minLeft,
44                                          const APInt &minRight,
45                                          const APInt &maxLeft,
46                                          const APInt &maxRight, bool isSigned) {
47   std::optional<APInt> maybeMin = op(minLeft, minRight);
48   std::optional<APInt> maybeMax = op(maxLeft, maxRight);
49   if (maybeMin && maybeMax)
50     return ConstantIntRanges::range(*maybeMin, *maybeMax, isSigned);
51   return ConstantIntRanges::maxRange(minLeft.getBitWidth());
52 }
53 
54 /// Compute the minimum and maximum of `(op(l, r) for l in lhs for r in rhs)`,
55 /// ignoring unbounded values. Returns the maximal range if `op` overflows.
56 static ConstantIntRanges minMaxBy(ConstArithFn op, ArrayRef<APInt> lhs,
57                                   ArrayRef<APInt> rhs, bool isSigned) {
58   unsigned width = lhs[0].getBitWidth();
59   APInt min =
60       isSigned ? APInt::getSignedMaxValue(width) : APInt::getMaxValue(width);
61   APInt max =
62       isSigned ? APInt::getSignedMinValue(width) : APInt::getZero(width);
63   for (const APInt &left : lhs) {
64     for (const APInt &right : rhs) {
65       std::optional<APInt> maybeThisResult = op(left, right);
66       if (!maybeThisResult)
67         return ConstantIntRanges::maxRange(width);
68       APInt result = std::move(*maybeThisResult);
69       min = (isSigned ? result.slt(min) : result.ult(min)) ? result : min;
70       max = (isSigned ? result.sgt(max) : result.ugt(max)) ? result : max;
71     }
72   }
73   return ConstantIntRanges::range(min, max, isSigned);
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // Ext, trunc, index op handling
78 //===----------------------------------------------------------------------===//
79 
80 ConstantIntRanges
81 mlir::intrange::inferIndexOp(const InferRangeFn &inferFn,
82                              ArrayRef<ConstantIntRanges> argRanges,
83                              intrange::CmpMode mode) {
84   ConstantIntRanges sixtyFour = inferFn(argRanges);
85   SmallVector<ConstantIntRanges, 2> truncated;
86   llvm::transform(argRanges, std::back_inserter(truncated),
87                   [](const ConstantIntRanges &range) {
88                     return truncRange(range, /*destWidth=*/indexMinWidth);
89                   });
90   ConstantIntRanges thirtyTwo = inferFn(truncated);
91   ConstantIntRanges thirtyTwoAsSixtyFour =
92       extRange(thirtyTwo, /*destWidth=*/indexMaxWidth);
93   ConstantIntRanges sixtyFourAsThirtyTwo =
94       truncRange(sixtyFour, /*destWidth=*/indexMinWidth);
95 
96   LLVM_DEBUG(llvm::dbgs() << "Index handling: 64-bit result = " << sixtyFour
97                           << " 32-bit = " << thirtyTwo << "\n");
98   bool truncEqual = false;
99   switch (mode) {
100   case intrange::CmpMode::Both:
101     truncEqual = (thirtyTwo == sixtyFourAsThirtyTwo);
102     break;
103   case intrange::CmpMode::Signed:
104     truncEqual = (thirtyTwo.smin() == sixtyFourAsThirtyTwo.smin() &&
105                   thirtyTwo.smax() == sixtyFourAsThirtyTwo.smax());
106     break;
107   case intrange::CmpMode::Unsigned:
108     truncEqual = (thirtyTwo.umin() == sixtyFourAsThirtyTwo.umin() &&
109                   thirtyTwo.umax() == sixtyFourAsThirtyTwo.umax());
110     break;
111   }
112   if (truncEqual)
113     // Returing the 64-bit result preserves more information.
114     return sixtyFour;
115   ConstantIntRanges merged = sixtyFour.rangeUnion(thirtyTwoAsSixtyFour);
116   return merged;
117 }
118 
119 ConstantIntRanges mlir::intrange::extRange(const ConstantIntRanges &range,
120                                            unsigned int destWidth) {
121   APInt umin = range.umin().zext(destWidth);
122   APInt umax = range.umax().zext(destWidth);
123   APInt smin = range.smin().sext(destWidth);
124   APInt smax = range.smax().sext(destWidth);
125   return {umin, umax, smin, smax};
126 }
127 
128 ConstantIntRanges mlir::intrange::extUIRange(const ConstantIntRanges &range,
129                                              unsigned destWidth) {
130   APInt umin = range.umin().zext(destWidth);
131   APInt umax = range.umax().zext(destWidth);
132   return ConstantIntRanges::fromUnsigned(umin, umax);
133 }
134 
135 ConstantIntRanges mlir::intrange::extSIRange(const ConstantIntRanges &range,
136                                              unsigned destWidth) {
137   APInt smin = range.smin().sext(destWidth);
138   APInt smax = range.smax().sext(destWidth);
139   return ConstantIntRanges::fromSigned(smin, smax);
140 }
141 
142 ConstantIntRanges mlir::intrange::truncRange(const ConstantIntRanges &range,
143                                              unsigned int destWidth) {
144   // If you truncate the first four bytes in [0xaaaabbbb, 0xccccbbbb],
145   // the range of the resulting value is not contiguous ind includes 0.
146   // Ex. If you truncate [256, 258] from i16 to i8, you validly get [0, 2],
147   // but you can't truncate [255, 257] similarly.
148   bool hasUnsignedRollover =
149       range.umin().lshr(destWidth) != range.umax().lshr(destWidth);
150   APInt umin = hasUnsignedRollover ? APInt::getZero(destWidth)
151                                    : range.umin().trunc(destWidth);
152   APInt umax = hasUnsignedRollover ? APInt::getMaxValue(destWidth)
153                                    : range.umax().trunc(destWidth);
154 
155   // Signed post-truncation rollover will not occur when either:
156   // - The high parts of the min and max, plus the sign bit, are the same
157   // - The high halves + sign bit of the min and max are either all 1s or all 0s
158   //  and you won't create a [positive, negative] range by truncating.
159   // For example, you can truncate the ranges [256, 258]_i16 to [0, 2]_i8
160   // but not [255, 257]_i16 to a range of i8s. You can also truncate
161   // [-256, -256]_i16 to [-2, 0]_i8, but not [-257, -255]_i16.
162   // You can also truncate [-130, 0]_i16 to i8 because -130_i16 (0xff7e)
163   // will truncate to 0x7e, which is greater than 0
164   APInt sminHighPart = range.smin().ashr(destWidth - 1);
165   APInt smaxHighPart = range.smax().ashr(destWidth - 1);
166   bool hasSignedOverflow =
167       (sminHighPart != smaxHighPart) &&
168       !(sminHighPart.isAllOnes() &&
169         (smaxHighPart.isAllOnes() || smaxHighPart.isZero())) &&
170       !(sminHighPart.isZero() && smaxHighPart.isZero());
171   APInt smin = hasSignedOverflow ? APInt::getSignedMinValue(destWidth)
172                                  : range.smin().trunc(destWidth);
173   APInt smax = hasSignedOverflow ? APInt::getSignedMaxValue(destWidth)
174                                  : range.smax().trunc(destWidth);
175   return {umin, umax, smin, smax};
176 }
177 
178 //===----------------------------------------------------------------------===//
179 // Addition
180 //===----------------------------------------------------------------------===//
181 
182 ConstantIntRanges
183 mlir::intrange::inferAdd(ArrayRef<ConstantIntRanges> argRanges,
184                          OverflowFlags ovfFlags) {
185   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
186 
187   ConstArithStdFn uadd = [=](const APInt &a,
188                              const APInt &b) -> std::optional<APInt> {
189     bool overflowed = false;
190     APInt result = any(ovfFlags & OverflowFlags::Nuw)
191                        ? a.uadd_sat(b)
192                        : a.uadd_ov(b, overflowed);
193     return overflowed ? std::optional<APInt>() : result;
194   };
195   ConstArithStdFn sadd = [=](const APInt &a,
196                              const APInt &b) -> std::optional<APInt> {
197     bool overflowed = false;
198     APInt result = any(ovfFlags & OverflowFlags::Nsw)
199                        ? a.sadd_sat(b)
200                        : a.sadd_ov(b, overflowed);
201     return overflowed ? std::optional<APInt>() : result;
202   };
203 
204   ConstantIntRanges urange = computeBoundsBy(
205       uadd, lhs.umin(), rhs.umin(), lhs.umax(), rhs.umax(), /*isSigned=*/false);
206   ConstantIntRanges srange = computeBoundsBy(
207       sadd, lhs.smin(), rhs.smin(), lhs.smax(), rhs.smax(), /*isSigned=*/true);
208   return urange.intersection(srange);
209 }
210 
211 //===----------------------------------------------------------------------===//
212 // Subtraction
213 //===----------------------------------------------------------------------===//
214 
215 ConstantIntRanges
216 mlir::intrange::inferSub(ArrayRef<ConstantIntRanges> argRanges,
217                          OverflowFlags ovfFlags) {
218   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
219 
220   ConstArithStdFn usub = [=](const APInt &a,
221                              const APInt &b) -> std::optional<APInt> {
222     bool overflowed = false;
223     APInt result = any(ovfFlags & OverflowFlags::Nuw)
224                        ? a.usub_sat(b)
225                        : a.usub_ov(b, overflowed);
226     return overflowed ? std::optional<APInt>() : result;
227   };
228   ConstArithStdFn ssub = [=](const APInt &a,
229                              const APInt &b) -> std::optional<APInt> {
230     bool overflowed = false;
231     APInt result = any(ovfFlags & OverflowFlags::Nsw)
232                        ? a.ssub_sat(b)
233                        : a.ssub_ov(b, overflowed);
234     return overflowed ? std::optional<APInt>() : result;
235   };
236   ConstantIntRanges urange = computeBoundsBy(
237       usub, lhs.umin(), rhs.umax(), lhs.umax(), rhs.umin(), /*isSigned=*/false);
238   ConstantIntRanges srange = computeBoundsBy(
239       ssub, lhs.smin(), rhs.smax(), lhs.smax(), rhs.smin(), /*isSigned=*/true);
240   return urange.intersection(srange);
241 }
242 
243 //===----------------------------------------------------------------------===//
244 // Multiplication
245 //===----------------------------------------------------------------------===//
246 
247 ConstantIntRanges
248 mlir::intrange::inferMul(ArrayRef<ConstantIntRanges> argRanges,
249                          OverflowFlags ovfFlags) {
250   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
251 
252   ConstArithStdFn umul = [=](const APInt &a,
253                              const APInt &b) -> std::optional<APInt> {
254     bool overflowed = false;
255     APInt result = any(ovfFlags & OverflowFlags::Nuw)
256                        ? a.umul_sat(b)
257                        : a.umul_ov(b, overflowed);
258     return overflowed ? std::optional<APInt>() : result;
259   };
260   ConstArithStdFn smul = [=](const APInt &a,
261                              const APInt &b) -> std::optional<APInt> {
262     bool overflowed = false;
263     APInt result = any(ovfFlags & OverflowFlags::Nsw)
264                        ? a.smul_sat(b)
265                        : a.smul_ov(b, overflowed);
266     return overflowed ? std::optional<APInt>() : result;
267   };
268 
269   ConstantIntRanges urange =
270       minMaxBy(umul, {lhs.umin(), lhs.umax()}, {rhs.umin(), rhs.umax()},
271                /*isSigned=*/false);
272   ConstantIntRanges srange =
273       minMaxBy(smul, {lhs.smin(), lhs.smax()}, {rhs.smin(), rhs.smax()},
274                /*isSigned=*/true);
275   return urange.intersection(srange);
276 }
277 
278 //===----------------------------------------------------------------------===//
279 // DivU, CeilDivU (Unsigned division)
280 //===----------------------------------------------------------------------===//
281 
282 /// Fix up division results (ex. for ceiling and floor), returning an APInt
283 /// if there has been no overflow
284 using DivisionFixupFn = function_ref<std::optional<APInt>(
285     const APInt &lhs, const APInt &rhs, const APInt &result)>;
286 
287 static ConstantIntRanges inferDivURange(const ConstantIntRanges &lhs,
288                                         const ConstantIntRanges &rhs,
289                                         DivisionFixupFn fixup) {
290   const APInt &lhsMin = lhs.umin(), &lhsMax = lhs.umax(), &rhsMin = rhs.umin(),
291               &rhsMax = rhs.umax();
292 
293   if (!rhsMin.isZero()) {
294     auto udiv = [&fixup](const APInt &a,
295                          const APInt &b) -> std::optional<APInt> {
296       return fixup(a, b, a.udiv(b));
297     };
298     return minMaxBy(udiv, {lhsMin, lhsMax}, {rhsMin, rhsMax},
299                     /*isSigned=*/false);
300   }
301   // Otherwise, it's possible we might divide by 0.
302   return ConstantIntRanges::maxRange(rhsMin.getBitWidth());
303 }
304 
305 ConstantIntRanges
306 mlir::intrange::inferDivU(ArrayRef<ConstantIntRanges> argRanges) {
307   return inferDivURange(argRanges[0], argRanges[1],
308                         [](const APInt &lhs, const APInt &rhs,
309                            const APInt &result) { return result; });
310 }
311 
312 ConstantIntRanges
313 mlir::intrange::inferCeilDivU(ArrayRef<ConstantIntRanges> argRanges) {
314   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
315 
316   DivisionFixupFn ceilDivUIFix =
317       [](const APInt &lhs, const APInt &rhs,
318          const APInt &result) -> std::optional<APInt> {
319     if (!lhs.urem(rhs).isZero()) {
320       bool overflowed = false;
321       APInt corrected =
322           result.uadd_ov(APInt(result.getBitWidth(), 1), overflowed);
323       return overflowed ? std::optional<APInt>() : corrected;
324     }
325     return result;
326   };
327   return inferDivURange(lhs, rhs, ceilDivUIFix);
328 }
329 
330 //===----------------------------------------------------------------------===//
331 // DivS, CeilDivS, FloorDivS (Signed division)
332 //===----------------------------------------------------------------------===//
333 
334 static ConstantIntRanges inferDivSRange(const ConstantIntRanges &lhs,
335                                         const ConstantIntRanges &rhs,
336                                         DivisionFixupFn fixup) {
337   const APInt &lhsMin = lhs.smin(), &lhsMax = lhs.smax(), &rhsMin = rhs.smin(),
338               &rhsMax = rhs.smax();
339   bool canDivide = rhsMin.isStrictlyPositive() || rhsMax.isNegative();
340 
341   if (canDivide) {
342     auto sdiv = [&fixup](const APInt &a,
343                          const APInt &b) -> std::optional<APInt> {
344       bool overflowed = false;
345       APInt result = a.sdiv_ov(b, overflowed);
346       return overflowed ? std::optional<APInt>() : fixup(a, b, result);
347     };
348     return minMaxBy(sdiv, {lhsMin, lhsMax}, {rhsMin, rhsMax},
349                     /*isSigned=*/true);
350   }
351   return ConstantIntRanges::maxRange(rhsMin.getBitWidth());
352 }
353 
354 ConstantIntRanges
355 mlir::intrange::inferDivS(ArrayRef<ConstantIntRanges> argRanges) {
356   return inferDivSRange(argRanges[0], argRanges[1],
357                         [](const APInt &lhs, const APInt &rhs,
358                            const APInt &result) { return result; });
359 }
360 
361 ConstantIntRanges
362 mlir::intrange::inferCeilDivS(ArrayRef<ConstantIntRanges> argRanges) {
363   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
364 
365   DivisionFixupFn ceilDivSIFix =
366       [](const APInt &lhs, const APInt &rhs,
367          const APInt &result) -> std::optional<APInt> {
368     if (!lhs.srem(rhs).isZero() && lhs.isNonNegative() == rhs.isNonNegative()) {
369       bool overflowed = false;
370       APInt corrected =
371           result.sadd_ov(APInt(result.getBitWidth(), 1), overflowed);
372       return overflowed ? std::optional<APInt>() : corrected;
373     }
374     return result;
375   };
376   return inferDivSRange(lhs, rhs, ceilDivSIFix);
377 }
378 
379 ConstantIntRanges
380 mlir::intrange::inferFloorDivS(ArrayRef<ConstantIntRanges> argRanges) {
381   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
382 
383   DivisionFixupFn floorDivSIFix =
384       [](const APInt &lhs, const APInt &rhs,
385          const APInt &result) -> std::optional<APInt> {
386     if (!lhs.srem(rhs).isZero() && lhs.isNonNegative() != rhs.isNonNegative()) {
387       bool overflowed = false;
388       APInt corrected =
389           result.ssub_ov(APInt(result.getBitWidth(), 1), overflowed);
390       return overflowed ? std::optional<APInt>() : corrected;
391     }
392     return result;
393   };
394   return inferDivSRange(lhs, rhs, floorDivSIFix);
395 }
396 
397 //===----------------------------------------------------------------------===//
398 // Signed remainder (RemS)
399 //===----------------------------------------------------------------------===//
400 
401 ConstantIntRanges
402 mlir::intrange::inferRemS(ArrayRef<ConstantIntRanges> argRanges) {
403   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
404   const APInt &lhsMin = lhs.smin(), &lhsMax = lhs.smax(), &rhsMin = rhs.smin(),
405               &rhsMax = rhs.smax();
406 
407   unsigned width = rhsMax.getBitWidth();
408   APInt smin = APInt::getSignedMinValue(width);
409   APInt smax = APInt::getSignedMaxValue(width);
410   // No bounds if zero could be a divisor.
411   bool canBound = (rhsMin.isStrictlyPositive() || rhsMax.isNegative());
412   if (canBound) {
413     APInt maxDivisor = rhsMin.isStrictlyPositive() ? rhsMax : rhsMin.abs();
414     bool canNegativeDividend = lhsMin.isNegative();
415     bool canPositiveDividend = lhsMax.isStrictlyPositive();
416     APInt zero = APInt::getZero(maxDivisor.getBitWidth());
417     APInt maxPositiveResult = maxDivisor - 1;
418     APInt minNegativeResult = -maxPositiveResult;
419     smin = canNegativeDividend ? minNegativeResult : zero;
420     smax = canPositiveDividend ? maxPositiveResult : zero;
421     // Special case: sweeping out a contiguous range in N/[modulus].
422     if (rhsMin == rhsMax) {
423       if ((lhsMax - lhsMin).ult(maxDivisor)) {
424         APInt minRem = lhsMin.srem(maxDivisor);
425         APInt maxRem = lhsMax.srem(maxDivisor);
426         if (minRem.sle(maxRem)) {
427           smin = minRem;
428           smax = maxRem;
429         }
430       }
431     }
432   }
433   return ConstantIntRanges::fromSigned(smin, smax);
434 }
435 
436 //===----------------------------------------------------------------------===//
437 // Unsigned remainder (RemU)
438 //===----------------------------------------------------------------------===//
439 
440 ConstantIntRanges
441 mlir::intrange::inferRemU(ArrayRef<ConstantIntRanges> argRanges) {
442   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
443   const APInt &rhsMin = rhs.umin(), &rhsMax = rhs.umax();
444 
445   unsigned width = rhsMin.getBitWidth();
446   APInt umin = APInt::getZero(width);
447   APInt umax = APInt::getMaxValue(width);
448 
449   if (!rhsMin.isZero()) {
450     umax = rhsMax - 1;
451     // Special case: sweeping out a contiguous range in N/[modulus]
452     if (rhsMin == rhsMax) {
453       const APInt &lhsMin = lhs.umin(), &lhsMax = lhs.umax();
454       if ((lhsMax - lhsMin).ult(rhsMax)) {
455         APInt minRem = lhsMin.urem(rhsMax);
456         APInt maxRem = lhsMax.urem(rhsMax);
457         if (minRem.ule(maxRem)) {
458           umin = minRem;
459           umax = maxRem;
460         }
461       }
462     }
463   }
464   return ConstantIntRanges::fromUnsigned(umin, umax);
465 }
466 
467 //===----------------------------------------------------------------------===//
468 // Max and min (MaxS, MaxU, MinS, MinU)
469 //===----------------------------------------------------------------------===//
470 
471 ConstantIntRanges
472 mlir::intrange::inferMaxS(ArrayRef<ConstantIntRanges> argRanges) {
473   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
474 
475   const APInt &smin = lhs.smin().sgt(rhs.smin()) ? lhs.smin() : rhs.smin();
476   const APInt &smax = lhs.smax().sgt(rhs.smax()) ? lhs.smax() : rhs.smax();
477   return ConstantIntRanges::fromSigned(smin, smax);
478 }
479 
480 ConstantIntRanges
481 mlir::intrange::inferMaxU(ArrayRef<ConstantIntRanges> argRanges) {
482   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
483 
484   const APInt &umin = lhs.umin().ugt(rhs.umin()) ? lhs.umin() : rhs.umin();
485   const APInt &umax = lhs.umax().ugt(rhs.umax()) ? lhs.umax() : rhs.umax();
486   return ConstantIntRanges::fromUnsigned(umin, umax);
487 }
488 
489 ConstantIntRanges
490 mlir::intrange::inferMinS(ArrayRef<ConstantIntRanges> argRanges) {
491   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
492 
493   const APInt &smin = lhs.smin().slt(rhs.smin()) ? lhs.smin() : rhs.smin();
494   const APInt &smax = lhs.smax().slt(rhs.smax()) ? lhs.smax() : rhs.smax();
495   return ConstantIntRanges::fromSigned(smin, smax);
496 }
497 
498 ConstantIntRanges
499 mlir::intrange::inferMinU(ArrayRef<ConstantIntRanges> argRanges) {
500   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
501 
502   const APInt &umin = lhs.umin().ult(rhs.umin()) ? lhs.umin() : rhs.umin();
503   const APInt &umax = lhs.umax().ult(rhs.umax()) ? lhs.umax() : rhs.umax();
504   return ConstantIntRanges::fromUnsigned(umin, umax);
505 }
506 
507 //===----------------------------------------------------------------------===//
508 // Bitwise operators (And, Or, Xor)
509 //===----------------------------------------------------------------------===//
510 
511 /// "Widen" bounds - if 0bvvvvv??? <= a <= 0bvvvvv???,
512 /// relax the bounds to 0bvvvvv000 <= a <= 0bvvvvv111, where vvvvv are the bits
513 /// that both bonuds have in common. This gives us a consertive approximation
514 /// for what values can be passed to bitwise operations.
515 static std::tuple<APInt, APInt>
516 widenBitwiseBounds(const ConstantIntRanges &bound) {
517   APInt leftVal = bound.umin(), rightVal = bound.umax();
518   unsigned bitwidth = leftVal.getBitWidth();
519   unsigned differingBits = bitwidth - (leftVal ^ rightVal).countl_zero();
520   leftVal.clearLowBits(differingBits);
521   rightVal.setLowBits(differingBits);
522   return std::make_tuple(std::move(leftVal), std::move(rightVal));
523 }
524 
525 ConstantIntRanges
526 mlir::intrange::inferAnd(ArrayRef<ConstantIntRanges> argRanges) {
527   auto [lhsZeros, lhsOnes] = widenBitwiseBounds(argRanges[0]);
528   auto [rhsZeros, rhsOnes] = widenBitwiseBounds(argRanges[1]);
529   auto andi = [](const APInt &a, const APInt &b) -> std::optional<APInt> {
530     return a & b;
531   };
532   return minMaxBy(andi, {lhsZeros, lhsOnes}, {rhsZeros, rhsOnes},
533                   /*isSigned=*/false);
534 }
535 
536 ConstantIntRanges
537 mlir::intrange::inferOr(ArrayRef<ConstantIntRanges> argRanges) {
538   auto [lhsZeros, lhsOnes] = widenBitwiseBounds(argRanges[0]);
539   auto [rhsZeros, rhsOnes] = widenBitwiseBounds(argRanges[1]);
540   auto ori = [](const APInt &a, const APInt &b) -> std::optional<APInt> {
541     return a | b;
542   };
543   return minMaxBy(ori, {lhsZeros, lhsOnes}, {rhsZeros, rhsOnes},
544                   /*isSigned=*/false);
545 }
546 
547 ConstantIntRanges
548 mlir::intrange::inferXor(ArrayRef<ConstantIntRanges> argRanges) {
549   auto [lhsZeros, lhsOnes] = widenBitwiseBounds(argRanges[0]);
550   auto [rhsZeros, rhsOnes] = widenBitwiseBounds(argRanges[1]);
551   auto xori = [](const APInt &a, const APInt &b) -> std::optional<APInt> {
552     return a ^ b;
553   };
554   return minMaxBy(xori, {lhsZeros, lhsOnes}, {rhsZeros, rhsOnes},
555                   /*isSigned=*/false);
556 }
557 
558 //===----------------------------------------------------------------------===//
559 // Shifts (Shl, ShrS, ShrU)
560 //===----------------------------------------------------------------------===//
561 
562 ConstantIntRanges
563 mlir::intrange::inferShl(ArrayRef<ConstantIntRanges> argRanges,
564                          OverflowFlags ovfFlags) {
565   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
566   const APInt &rhsUMin = rhs.umin(), &rhsUMax = rhs.umax();
567 
568   // The signed/unsigned overflow behavior of shl by `rhs` matches a mul with
569   // 2^rhs.
570   ConstArithStdFn ushl = [=](const APInt &l,
571                              const APInt &r) -> std::optional<APInt> {
572     bool overflowed = false;
573     APInt result = any(ovfFlags & OverflowFlags::Nuw)
574                        ? l.ushl_sat(r)
575                        : l.ushl_ov(r, overflowed);
576     return overflowed ? std::optional<APInt>() : result;
577   };
578   ConstArithStdFn sshl = [=](const APInt &l,
579                              const APInt &r) -> std::optional<APInt> {
580     bool overflowed = false;
581     APInt result = any(ovfFlags & OverflowFlags::Nsw)
582                        ? l.sshl_sat(r)
583                        : l.sshl_ov(r, overflowed);
584     return overflowed ? std::optional<APInt>() : result;
585   };
586 
587   ConstantIntRanges urange =
588       minMaxBy(ushl, {lhs.umin(), lhs.umax()}, {rhsUMin, rhsUMax},
589                /*isSigned=*/false);
590   ConstantIntRanges srange =
591       minMaxBy(sshl, {lhs.smin(), lhs.smax()}, {rhsUMin, rhsUMax},
592                /*isSigned=*/true);
593   return urange.intersection(srange);
594 }
595 
596 ConstantIntRanges
597 mlir::intrange::inferShrS(ArrayRef<ConstantIntRanges> argRanges) {
598   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
599 
600   ConstArithFn ashr = [](const APInt &l,
601                          const APInt &r) -> std::optional<APInt> {
602     return r.uge(r.getBitWidth()) ? std::optional<APInt>() : l.ashr(r);
603   };
604 
605   return minMaxBy(ashr, {lhs.smin(), lhs.smax()}, {rhs.umin(), rhs.umax()},
606                   /*isSigned=*/true);
607 }
608 
609 ConstantIntRanges
610 mlir::intrange::inferShrU(ArrayRef<ConstantIntRanges> argRanges) {
611   const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1];
612 
613   ConstArithFn lshr = [](const APInt &l,
614                          const APInt &r) -> std::optional<APInt> {
615     return r.uge(r.getBitWidth()) ? std::optional<APInt>() : l.lshr(r);
616   };
617   return minMaxBy(lshr, {lhs.umin(), lhs.umax()}, {rhs.umin(), rhs.umax()},
618                   /*isSigned=*/false);
619 }
620 
621 //===----------------------------------------------------------------------===//
622 // Comparisons (Cmp)
623 //===----------------------------------------------------------------------===//
624 
625 static intrange::CmpPredicate invertPredicate(intrange::CmpPredicate pred) {
626   switch (pred) {
627   case intrange::CmpPredicate::eq:
628     return intrange::CmpPredicate::ne;
629   case intrange::CmpPredicate::ne:
630     return intrange::CmpPredicate::eq;
631   case intrange::CmpPredicate::slt:
632     return intrange::CmpPredicate::sge;
633   case intrange::CmpPredicate::sle:
634     return intrange::CmpPredicate::sgt;
635   case intrange::CmpPredicate::sgt:
636     return intrange::CmpPredicate::sle;
637   case intrange::CmpPredicate::sge:
638     return intrange::CmpPredicate::slt;
639   case intrange::CmpPredicate::ult:
640     return intrange::CmpPredicate::uge;
641   case intrange::CmpPredicate::ule:
642     return intrange::CmpPredicate::ugt;
643   case intrange::CmpPredicate::ugt:
644     return intrange::CmpPredicate::ule;
645   case intrange::CmpPredicate::uge:
646     return intrange::CmpPredicate::ult;
647   }
648   llvm_unreachable("unknown cmp predicate value");
649 }
650 
651 static bool isStaticallyTrue(intrange::CmpPredicate pred,
652                              const ConstantIntRanges &lhs,
653                              const ConstantIntRanges &rhs) {
654   switch (pred) {
655   case intrange::CmpPredicate::sle:
656     return lhs.smax().sle(rhs.smin());
657   case intrange::CmpPredicate::slt:
658     return lhs.smax().slt(rhs.smin());
659   case intrange::CmpPredicate::ule:
660     return lhs.umax().ule(rhs.umin());
661   case intrange::CmpPredicate::ult:
662     return lhs.umax().ult(rhs.umin());
663   case intrange::CmpPredicate::sge:
664     return lhs.smin().sge(rhs.smax());
665   case intrange::CmpPredicate::sgt:
666     return lhs.smin().sgt(rhs.smax());
667   case intrange::CmpPredicate::uge:
668     return lhs.umin().uge(rhs.umax());
669   case intrange::CmpPredicate::ugt:
670     return lhs.umin().ugt(rhs.umax());
671   case intrange::CmpPredicate::eq: {
672     std::optional<APInt> lhsConst = lhs.getConstantValue();
673     std::optional<APInt> rhsConst = rhs.getConstantValue();
674     return lhsConst && rhsConst && lhsConst == rhsConst;
675   }
676   case intrange::CmpPredicate::ne: {
677     // While equality requires that there is an interpration of the preceeding
678     // computations that produces equal constants, whether that be signed or
679     // unsigned, statically determining inequality requires that neither
680     // interpretation produce potentially overlapping ranges.
681     bool sne = isStaticallyTrue(intrange::CmpPredicate::slt, lhs, rhs) ||
682                isStaticallyTrue(intrange::CmpPredicate::sgt, lhs, rhs);
683     bool une = isStaticallyTrue(intrange::CmpPredicate::ult, lhs, rhs) ||
684                isStaticallyTrue(intrange::CmpPredicate::ugt, lhs, rhs);
685     return sne && une;
686   }
687   }
688   return false;
689 }
690 
691 std::optional<bool> mlir::intrange::evaluatePred(CmpPredicate pred,
692                                                  const ConstantIntRanges &lhs,
693                                                  const ConstantIntRanges &rhs) {
694   if (isStaticallyTrue(pred, lhs, rhs))
695     return true;
696   if (isStaticallyTrue(invertPredicate(pred), lhs, rhs))
697     return false;
698   return std::nullopt;
699 }
700