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 302 APInt umin = APInt::getZero(rhsMin.getBitWidth()); 303 if (lhsMin.uge(rhsMax) && !rhsMax.isZero()) 304 umin = lhsMin.udiv(rhsMax); 305 306 // X u/ Y u<= X. 307 APInt umax = lhsMax; 308 return ConstantIntRanges::fromUnsigned(umin, umax); 309 } 310 311 ConstantIntRanges 312 mlir::intrange::inferDivU(ArrayRef<ConstantIntRanges> argRanges) { 313 return inferDivURange(argRanges[0], argRanges[1], 314 [](const APInt &lhs, const APInt &rhs, 315 const APInt &result) { return result; }); 316 } 317 318 ConstantIntRanges 319 mlir::intrange::inferCeilDivU(ArrayRef<ConstantIntRanges> argRanges) { 320 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 321 322 auto ceilDivUIFix = [](const APInt &lhs, const APInt &rhs, 323 const APInt &result) -> std::optional<APInt> { 324 if (!lhs.urem(rhs).isZero()) { 325 bool overflowed = false; 326 APInt corrected = 327 result.uadd_ov(APInt(result.getBitWidth(), 1), overflowed); 328 return overflowed ? std::optional<APInt>() : corrected; 329 } 330 return result; 331 }; 332 return inferDivURange(lhs, rhs, ceilDivUIFix); 333 } 334 335 //===----------------------------------------------------------------------===// 336 // DivS, CeilDivS, FloorDivS (Signed division) 337 //===----------------------------------------------------------------------===// 338 339 static ConstantIntRanges inferDivSRange(const ConstantIntRanges &lhs, 340 const ConstantIntRanges &rhs, 341 DivisionFixupFn fixup) { 342 const APInt &lhsMin = lhs.smin(), &lhsMax = lhs.smax(), &rhsMin = rhs.smin(), 343 &rhsMax = rhs.smax(); 344 bool canDivide = rhsMin.isStrictlyPositive() || rhsMax.isNegative(); 345 346 if (canDivide) { 347 auto sdiv = [&fixup](const APInt &a, 348 const APInt &b) -> std::optional<APInt> { 349 bool overflowed = false; 350 APInt result = a.sdiv_ov(b, overflowed); 351 return overflowed ? std::optional<APInt>() : fixup(a, b, result); 352 }; 353 return minMaxBy(sdiv, {lhsMin, lhsMax}, {rhsMin, rhsMax}, 354 /*isSigned=*/true); 355 } 356 return ConstantIntRanges::maxRange(rhsMin.getBitWidth()); 357 } 358 359 ConstantIntRanges 360 mlir::intrange::inferDivS(ArrayRef<ConstantIntRanges> argRanges) { 361 return inferDivSRange(argRanges[0], argRanges[1], 362 [](const APInt &lhs, const APInt &rhs, 363 const APInt &result) { return result; }); 364 } 365 366 ConstantIntRanges 367 mlir::intrange::inferCeilDivS(ArrayRef<ConstantIntRanges> argRanges) { 368 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 369 370 auto ceilDivSIFix = [](const APInt &lhs, const APInt &rhs, 371 const APInt &result) -> std::optional<APInt> { 372 if (!lhs.srem(rhs).isZero() && lhs.isNonNegative() == rhs.isNonNegative()) { 373 bool overflowed = false; 374 APInt corrected = 375 result.sadd_ov(APInt(result.getBitWidth(), 1), overflowed); 376 return overflowed ? std::optional<APInt>() : corrected; 377 } 378 // Special case where the usual implementation of ceilDiv causes 379 // INT_MIN / [positive number] to be positive. This doesn't match the 380 // definition of signed ceiling division mathematically, but it prevents 381 // inconsistent constant-folding results. This arises because (-int_min) is 382 // still negative, so -(-int_min / b) is -(int_min / b), which is 383 // positive See #115293. 384 if (lhs.isMinSignedValue() && rhs.sgt(1)) { 385 return -result; 386 } 387 return result; 388 }; 389 return inferDivSRange(lhs, rhs, ceilDivSIFix); 390 } 391 392 ConstantIntRanges 393 mlir::intrange::inferFloorDivS(ArrayRef<ConstantIntRanges> argRanges) { 394 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 395 396 auto floorDivSIFix = [](const APInt &lhs, const APInt &rhs, 397 const APInt &result) -> std::optional<APInt> { 398 if (!lhs.srem(rhs).isZero() && lhs.isNonNegative() != rhs.isNonNegative()) { 399 bool overflowed = false; 400 APInt corrected = 401 result.ssub_ov(APInt(result.getBitWidth(), 1), overflowed); 402 return overflowed ? std::optional<APInt>() : corrected; 403 } 404 return result; 405 }; 406 return inferDivSRange(lhs, rhs, floorDivSIFix); 407 } 408 409 //===----------------------------------------------------------------------===// 410 // Signed remainder (RemS) 411 //===----------------------------------------------------------------------===// 412 413 ConstantIntRanges 414 mlir::intrange::inferRemS(ArrayRef<ConstantIntRanges> argRanges) { 415 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 416 const APInt &lhsMin = lhs.smin(), &lhsMax = lhs.smax(), &rhsMin = rhs.smin(), 417 &rhsMax = rhs.smax(); 418 419 unsigned width = rhsMax.getBitWidth(); 420 APInt smin = APInt::getSignedMinValue(width); 421 APInt smax = APInt::getSignedMaxValue(width); 422 // No bounds if zero could be a divisor. 423 bool canBound = (rhsMin.isStrictlyPositive() || rhsMax.isNegative()); 424 if (canBound) { 425 APInt maxDivisor = rhsMin.isStrictlyPositive() ? rhsMax : rhsMin.abs(); 426 bool canNegativeDividend = lhsMin.isNegative(); 427 bool canPositiveDividend = lhsMax.isStrictlyPositive(); 428 APInt zero = APInt::getZero(maxDivisor.getBitWidth()); 429 APInt maxPositiveResult = maxDivisor - 1; 430 APInt minNegativeResult = -maxPositiveResult; 431 smin = canNegativeDividend ? minNegativeResult : zero; 432 smax = canPositiveDividend ? maxPositiveResult : zero; 433 // Special case: sweeping out a contiguous range in N/[modulus]. 434 if (rhsMin == rhsMax) { 435 if ((lhsMax - lhsMin).ult(maxDivisor)) { 436 APInt minRem = lhsMin.srem(maxDivisor); 437 APInt maxRem = lhsMax.srem(maxDivisor); 438 if (minRem.sle(maxRem)) { 439 smin = minRem; 440 smax = maxRem; 441 } 442 } 443 } 444 } 445 return ConstantIntRanges::fromSigned(smin, smax); 446 } 447 448 //===----------------------------------------------------------------------===// 449 // Unsigned remainder (RemU) 450 //===----------------------------------------------------------------------===// 451 452 ConstantIntRanges 453 mlir::intrange::inferRemU(ArrayRef<ConstantIntRanges> argRanges) { 454 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 455 const APInt &rhsMin = rhs.umin(), &rhsMax = rhs.umax(); 456 457 unsigned width = rhsMin.getBitWidth(); 458 APInt umin = APInt::getZero(width); 459 // Remainder can't be larger than either of its arguments. 460 APInt umax = llvm::APIntOps::umin((rhsMax - 1), lhs.umax()); 461 462 if (!rhsMin.isZero()) { 463 // Special case: sweeping out a contiguous range in N/[modulus] 464 if (rhsMin == rhsMax) { 465 const APInt &lhsMin = lhs.umin(), &lhsMax = lhs.umax(); 466 if ((lhsMax - lhsMin).ult(rhsMax)) { 467 APInt minRem = lhsMin.urem(rhsMax); 468 APInt maxRem = lhsMax.urem(rhsMax); 469 if (minRem.ule(maxRem)) { 470 umin = minRem; 471 umax = maxRem; 472 } 473 } 474 } 475 } 476 return ConstantIntRanges::fromUnsigned(umin, umax); 477 } 478 479 //===----------------------------------------------------------------------===// 480 // Max and min (MaxS, MaxU, MinS, MinU) 481 //===----------------------------------------------------------------------===// 482 483 ConstantIntRanges 484 mlir::intrange::inferMaxS(ArrayRef<ConstantIntRanges> argRanges) { 485 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 486 487 const APInt &smin = lhs.smin().sgt(rhs.smin()) ? lhs.smin() : rhs.smin(); 488 const APInt &smax = lhs.smax().sgt(rhs.smax()) ? lhs.smax() : rhs.smax(); 489 return ConstantIntRanges::fromSigned(smin, smax); 490 } 491 492 ConstantIntRanges 493 mlir::intrange::inferMaxU(ArrayRef<ConstantIntRanges> argRanges) { 494 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 495 496 const APInt &umin = lhs.umin().ugt(rhs.umin()) ? lhs.umin() : rhs.umin(); 497 const APInt &umax = lhs.umax().ugt(rhs.umax()) ? lhs.umax() : rhs.umax(); 498 return ConstantIntRanges::fromUnsigned(umin, umax); 499 } 500 501 ConstantIntRanges 502 mlir::intrange::inferMinS(ArrayRef<ConstantIntRanges> argRanges) { 503 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 504 505 const APInt &smin = lhs.smin().slt(rhs.smin()) ? lhs.smin() : rhs.smin(); 506 const APInt &smax = lhs.smax().slt(rhs.smax()) ? lhs.smax() : rhs.smax(); 507 return ConstantIntRanges::fromSigned(smin, smax); 508 } 509 510 ConstantIntRanges 511 mlir::intrange::inferMinU(ArrayRef<ConstantIntRanges> argRanges) { 512 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 513 514 const APInt &umin = lhs.umin().ult(rhs.umin()) ? lhs.umin() : rhs.umin(); 515 const APInt &umax = lhs.umax().ult(rhs.umax()) ? lhs.umax() : rhs.umax(); 516 return ConstantIntRanges::fromUnsigned(umin, umax); 517 } 518 519 //===----------------------------------------------------------------------===// 520 // Bitwise operators (And, Or, Xor) 521 //===----------------------------------------------------------------------===// 522 523 /// "Widen" bounds - if 0bvvvvv??? <= a <= 0bvvvvv???, 524 /// relax the bounds to 0bvvvvv000 <= a <= 0bvvvvv111, where vvvvv are the bits 525 /// that both bonuds have in common. This gives us a consertive approximation 526 /// for what values can be passed to bitwise operations. 527 static std::tuple<APInt, APInt> 528 widenBitwiseBounds(const ConstantIntRanges &bound) { 529 APInt leftVal = bound.umin(), rightVal = bound.umax(); 530 unsigned bitwidth = leftVal.getBitWidth(); 531 unsigned differingBits = bitwidth - (leftVal ^ rightVal).countl_zero(); 532 leftVal.clearLowBits(differingBits); 533 rightVal.setLowBits(differingBits); 534 return std::make_tuple(std::move(leftVal), std::move(rightVal)); 535 } 536 537 ConstantIntRanges 538 mlir::intrange::inferAnd(ArrayRef<ConstantIntRanges> argRanges) { 539 auto [lhsZeros, lhsOnes] = widenBitwiseBounds(argRanges[0]); 540 auto [rhsZeros, rhsOnes] = widenBitwiseBounds(argRanges[1]); 541 auto andi = [](const APInt &a, const APInt &b) -> std::optional<APInt> { 542 return a & b; 543 }; 544 return minMaxBy(andi, {lhsZeros, lhsOnes}, {rhsZeros, rhsOnes}, 545 /*isSigned=*/false); 546 } 547 548 ConstantIntRanges 549 mlir::intrange::inferOr(ArrayRef<ConstantIntRanges> argRanges) { 550 auto [lhsZeros, lhsOnes] = widenBitwiseBounds(argRanges[0]); 551 auto [rhsZeros, rhsOnes] = widenBitwiseBounds(argRanges[1]); 552 auto ori = [](const APInt &a, const APInt &b) -> std::optional<APInt> { 553 return a | b; 554 }; 555 return minMaxBy(ori, {lhsZeros, lhsOnes}, {rhsZeros, rhsOnes}, 556 /*isSigned=*/false); 557 } 558 559 ConstantIntRanges 560 mlir::intrange::inferXor(ArrayRef<ConstantIntRanges> argRanges) { 561 auto [lhsZeros, lhsOnes] = widenBitwiseBounds(argRanges[0]); 562 auto [rhsZeros, rhsOnes] = widenBitwiseBounds(argRanges[1]); 563 auto xori = [](const APInt &a, const APInt &b) -> std::optional<APInt> { 564 return a ^ b; 565 }; 566 return minMaxBy(xori, {lhsZeros, lhsOnes}, {rhsZeros, rhsOnes}, 567 /*isSigned=*/false); 568 } 569 570 //===----------------------------------------------------------------------===// 571 // Shifts (Shl, ShrS, ShrU) 572 //===----------------------------------------------------------------------===// 573 574 ConstantIntRanges 575 mlir::intrange::inferShl(ArrayRef<ConstantIntRanges> argRanges, 576 OverflowFlags ovfFlags) { 577 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 578 const APInt &rhsUMin = rhs.umin(), &rhsUMax = rhs.umax(); 579 580 // The signed/unsigned overflow behavior of shl by `rhs` matches a mul with 581 // 2^rhs. 582 ConstArithStdFn ushl = [=](const APInt &l, 583 const APInt &r) -> std::optional<APInt> { 584 bool overflowed = false; 585 APInt result = any(ovfFlags & OverflowFlags::Nuw) 586 ? l.ushl_sat(r) 587 : l.ushl_ov(r, overflowed); 588 return overflowed ? std::optional<APInt>() : result; 589 }; 590 ConstArithStdFn sshl = [=](const APInt &l, 591 const APInt &r) -> std::optional<APInt> { 592 bool overflowed = false; 593 APInt result = any(ovfFlags & OverflowFlags::Nsw) 594 ? l.sshl_sat(r) 595 : l.sshl_ov(r, overflowed); 596 return overflowed ? std::optional<APInt>() : result; 597 }; 598 599 ConstantIntRanges urange = 600 minMaxBy(ushl, {lhs.umin(), lhs.umax()}, {rhsUMin, rhsUMax}, 601 /*isSigned=*/false); 602 ConstantIntRanges srange = 603 minMaxBy(sshl, {lhs.smin(), lhs.smax()}, {rhsUMin, rhsUMax}, 604 /*isSigned=*/true); 605 return urange.intersection(srange); 606 } 607 608 ConstantIntRanges 609 mlir::intrange::inferShrS(ArrayRef<ConstantIntRanges> argRanges) { 610 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 611 612 auto ashr = [](const APInt &l, const APInt &r) -> std::optional<APInt> { 613 return r.uge(r.getBitWidth()) ? std::optional<APInt>() : l.ashr(r); 614 }; 615 616 return minMaxBy(ashr, {lhs.smin(), lhs.smax()}, {rhs.umin(), rhs.umax()}, 617 /*isSigned=*/true); 618 } 619 620 ConstantIntRanges 621 mlir::intrange::inferShrU(ArrayRef<ConstantIntRanges> argRanges) { 622 const ConstantIntRanges &lhs = argRanges[0], &rhs = argRanges[1]; 623 624 auto lshr = [](const APInt &l, const APInt &r) -> std::optional<APInt> { 625 return r.uge(r.getBitWidth()) ? std::optional<APInt>() : l.lshr(r); 626 }; 627 return minMaxBy(lshr, {lhs.umin(), lhs.umax()}, {rhs.umin(), rhs.umax()}, 628 /*isSigned=*/false); 629 } 630 631 //===----------------------------------------------------------------------===// 632 // Comparisons (Cmp) 633 //===----------------------------------------------------------------------===// 634 635 static intrange::CmpPredicate invertPredicate(intrange::CmpPredicate pred) { 636 switch (pred) { 637 case intrange::CmpPredicate::eq: 638 return intrange::CmpPredicate::ne; 639 case intrange::CmpPredicate::ne: 640 return intrange::CmpPredicate::eq; 641 case intrange::CmpPredicate::slt: 642 return intrange::CmpPredicate::sge; 643 case intrange::CmpPredicate::sle: 644 return intrange::CmpPredicate::sgt; 645 case intrange::CmpPredicate::sgt: 646 return intrange::CmpPredicate::sle; 647 case intrange::CmpPredicate::sge: 648 return intrange::CmpPredicate::slt; 649 case intrange::CmpPredicate::ult: 650 return intrange::CmpPredicate::uge; 651 case intrange::CmpPredicate::ule: 652 return intrange::CmpPredicate::ugt; 653 case intrange::CmpPredicate::ugt: 654 return intrange::CmpPredicate::ule; 655 case intrange::CmpPredicate::uge: 656 return intrange::CmpPredicate::ult; 657 } 658 llvm_unreachable("unknown cmp predicate value"); 659 } 660 661 static bool isStaticallyTrue(intrange::CmpPredicate pred, 662 const ConstantIntRanges &lhs, 663 const ConstantIntRanges &rhs) { 664 switch (pred) { 665 case intrange::CmpPredicate::sle: 666 return lhs.smax().sle(rhs.smin()); 667 case intrange::CmpPredicate::slt: 668 return lhs.smax().slt(rhs.smin()); 669 case intrange::CmpPredicate::ule: 670 return lhs.umax().ule(rhs.umin()); 671 case intrange::CmpPredicate::ult: 672 return lhs.umax().ult(rhs.umin()); 673 case intrange::CmpPredicate::sge: 674 return lhs.smin().sge(rhs.smax()); 675 case intrange::CmpPredicate::sgt: 676 return lhs.smin().sgt(rhs.smax()); 677 case intrange::CmpPredicate::uge: 678 return lhs.umin().uge(rhs.umax()); 679 case intrange::CmpPredicate::ugt: 680 return lhs.umin().ugt(rhs.umax()); 681 case intrange::CmpPredicate::eq: { 682 std::optional<APInt> lhsConst = lhs.getConstantValue(); 683 std::optional<APInt> rhsConst = rhs.getConstantValue(); 684 return lhsConst && rhsConst && lhsConst == rhsConst; 685 } 686 case intrange::CmpPredicate::ne: { 687 // While equality requires that there is an interpration of the preceeding 688 // computations that produces equal constants, whether that be signed or 689 // unsigned, statically determining inequality requires that neither 690 // interpretation produce potentially overlapping ranges. 691 bool sne = isStaticallyTrue(intrange::CmpPredicate::slt, lhs, rhs) || 692 isStaticallyTrue(intrange::CmpPredicate::sgt, lhs, rhs); 693 bool une = isStaticallyTrue(intrange::CmpPredicate::ult, lhs, rhs) || 694 isStaticallyTrue(intrange::CmpPredicate::ugt, lhs, rhs); 695 return sne && une; 696 } 697 } 698 return false; 699 } 700 701 std::optional<bool> mlir::intrange::evaluatePred(CmpPredicate pred, 702 const ConstantIntRanges &lhs, 703 const ConstantIntRanges &rhs) { 704 if (isStaticallyTrue(pred, lhs, rhs)) 705 return true; 706 if (isStaticallyTrue(invertPredicate(pred), lhs, rhs)) 707 return false; 708 return std::nullopt; 709 } 710