1 //===- ConstantRange.cpp - ConstantRange implementation -------------------===// 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 // Represent a range of possible values that may occur when the program is run 10 // for an integral value. This keeps track of a lower and upper bound for the 11 // constant, which MAY wrap around the end of the numeric range. To do this, it 12 // keeps track of a [lower, upper) bound, which specifies an interval just like 13 // STL iterators. When used with boolean values, the following are important 14 // ranges (other integral ranges use min/max values for special range values): 15 // 16 // [F, F) = {} = Empty set 17 // [T, F) = {T} 18 // [F, T) = {F} 19 // [T, T) = {F, T} = Full set 20 // 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ADT/APInt.h" 24 #include "llvm/Config/llvm-config.h" 25 #include "llvm/IR/ConstantRange.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/InstrTypes.h" 28 #include "llvm/IR/Instruction.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/Metadata.h" 31 #include "llvm/IR/Operator.h" 32 #include "llvm/Support/Compiler.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/KnownBits.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> 38 #include <cassert> 39 #include <cstdint> 40 41 using namespace llvm; 42 43 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) 44 : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)), 45 Upper(Lower) {} 46 47 ConstantRange::ConstantRange(APInt V) 48 : Lower(std::move(V)), Upper(Lower + 1) {} 49 50 ConstantRange::ConstantRange(APInt L, APInt U) 51 : Lower(std::move(L)), Upper(std::move(U)) { 52 assert(Lower.getBitWidth() == Upper.getBitWidth() && 53 "ConstantRange with unequal bit widths"); 54 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) && 55 "Lower == Upper, but they aren't min or max value!"); 56 } 57 58 ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known, 59 bool IsSigned) { 60 assert(!Known.hasConflict() && "Expected valid KnownBits"); 61 62 if (Known.isUnknown()) 63 return getFull(Known.getBitWidth()); 64 65 // For unsigned ranges, or signed ranges with known sign bit, create a simple 66 // range between the smallest and largest possible value. 67 if (!IsSigned || Known.isNegative() || Known.isNonNegative()) 68 return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1); 69 70 // If we don't know the sign bit, pick the lower bound as a negative number 71 // and the upper bound as a non-negative one. 72 APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue(); 73 Lower.setSignBit(); 74 Upper.clearSignBit(); 75 return ConstantRange(Lower, Upper + 1); 76 } 77 78 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred, 79 const ConstantRange &CR) { 80 if (CR.isEmptySet()) 81 return CR; 82 83 uint32_t W = CR.getBitWidth(); 84 switch (Pred) { 85 default: 86 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()"); 87 case CmpInst::ICMP_EQ: 88 return CR; 89 case CmpInst::ICMP_NE: 90 if (CR.isSingleElement()) 91 return ConstantRange(CR.getUpper(), CR.getLower()); 92 return getFull(W); 93 case CmpInst::ICMP_ULT: { 94 APInt UMax(CR.getUnsignedMax()); 95 if (UMax.isMinValue()) 96 return getEmpty(W); 97 return ConstantRange(APInt::getMinValue(W), std::move(UMax)); 98 } 99 case CmpInst::ICMP_SLT: { 100 APInt SMax(CR.getSignedMax()); 101 if (SMax.isMinSignedValue()) 102 return getEmpty(W); 103 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax)); 104 } 105 case CmpInst::ICMP_ULE: 106 return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1); 107 case CmpInst::ICMP_SLE: 108 return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1); 109 case CmpInst::ICMP_UGT: { 110 APInt UMin(CR.getUnsignedMin()); 111 if (UMin.isMaxValue()) 112 return getEmpty(W); 113 return ConstantRange(std::move(UMin) + 1, APInt::getZero(W)); 114 } 115 case CmpInst::ICMP_SGT: { 116 APInt SMin(CR.getSignedMin()); 117 if (SMin.isMaxSignedValue()) 118 return getEmpty(W); 119 return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W)); 120 } 121 case CmpInst::ICMP_UGE: 122 return getNonEmpty(CR.getUnsignedMin(), APInt::getZero(W)); 123 case CmpInst::ICMP_SGE: 124 return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W)); 125 } 126 } 127 128 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred, 129 const ConstantRange &CR) { 130 // Follows from De-Morgan's laws: 131 // 132 // ~(~A union ~B) == A intersect B. 133 // 134 return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR) 135 .inverse(); 136 } 137 138 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred, 139 const APInt &C) { 140 // Computes the exact range that is equal to both the constant ranges returned 141 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true 142 // when RHS is a singleton such as an APInt and so the assert is valid. 143 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion 144 // returns [0,4) but makeSatisfyICmpRegion returns [0,2). 145 // 146 assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C)); 147 return makeAllowedICmpRegion(Pred, C); 148 } 149 150 bool ConstantRange::areInsensitiveToSignednessOfICmpPredicate( 151 const ConstantRange &CR1, const ConstantRange &CR2) { 152 if (CR1.isEmptySet() || CR2.isEmptySet()) 153 return true; 154 155 return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) || 156 (CR1.isAllNegative() && CR2.isAllNegative()); 157 } 158 159 bool ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate( 160 const ConstantRange &CR1, const ConstantRange &CR2) { 161 if (CR1.isEmptySet() || CR2.isEmptySet()) 162 return true; 163 164 return (CR1.isAllNonNegative() && CR2.isAllNegative()) || 165 (CR1.isAllNegative() && CR2.isAllNonNegative()); 166 } 167 168 CmpInst::Predicate ConstantRange::getEquivalentPredWithFlippedSignedness( 169 CmpInst::Predicate Pred, const ConstantRange &CR1, 170 const ConstantRange &CR2) { 171 assert(CmpInst::isIntPredicate(Pred) && CmpInst::isRelational(Pred) && 172 "Only for relational integer predicates!"); 173 174 CmpInst::Predicate FlippedSignednessPred = 175 CmpInst::getFlippedSignednessPredicate(Pred); 176 177 if (areInsensitiveToSignednessOfICmpPredicate(CR1, CR2)) 178 return FlippedSignednessPred; 179 180 if (areInsensitiveToSignednessOfInvertedICmpPredicate(CR1, CR2)) 181 return CmpInst::getInversePredicate(FlippedSignednessPred); 182 183 return CmpInst::Predicate::BAD_ICMP_PREDICATE; 184 } 185 186 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred, 187 APInt &RHS) const { 188 bool Success = false; 189 190 if (isFullSet() || isEmptySet()) { 191 Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE; 192 RHS = APInt(getBitWidth(), 0); 193 Success = true; 194 } else if (auto *OnlyElt = getSingleElement()) { 195 Pred = CmpInst::ICMP_EQ; 196 RHS = *OnlyElt; 197 Success = true; 198 } else if (auto *OnlyMissingElt = getSingleMissingElement()) { 199 Pred = CmpInst::ICMP_NE; 200 RHS = *OnlyMissingElt; 201 Success = true; 202 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) { 203 Pred = 204 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT; 205 RHS = getUpper(); 206 Success = true; 207 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) { 208 Pred = 209 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE; 210 RHS = getLower(); 211 Success = true; 212 } 213 214 assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) && 215 "Bad result!"); 216 217 return Success; 218 } 219 220 bool ConstantRange::icmp(CmpInst::Predicate Pred, 221 const ConstantRange &Other) const { 222 return makeSatisfyingICmpRegion(Pred, Other).contains(*this); 223 } 224 225 /// Exact mul nuw region for single element RHS. 226 static ConstantRange makeExactMulNUWRegion(const APInt &V) { 227 unsigned BitWidth = V.getBitWidth(); 228 if (V == 0) 229 return ConstantRange::getFull(V.getBitWidth()); 230 231 return ConstantRange::getNonEmpty( 232 APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V, 233 APInt::Rounding::UP), 234 APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V, 235 APInt::Rounding::DOWN) + 1); 236 } 237 238 /// Exact mul nsw region for single element RHS. 239 static ConstantRange makeExactMulNSWRegion(const APInt &V) { 240 // Handle special case for 0, -1 and 1. See the last for reason why we 241 // specialize -1 and 1. 242 unsigned BitWidth = V.getBitWidth(); 243 if (V == 0 || V.isOne()) 244 return ConstantRange::getFull(BitWidth); 245 246 APInt MinValue = APInt::getSignedMinValue(BitWidth); 247 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 248 // e.g. Returning [-127, 127], represented as [-127, -128). 249 if (V.isAllOnes()) 250 return ConstantRange(-MaxValue, MinValue); 251 252 APInt Lower, Upper; 253 if (V.isNegative()) { 254 Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP); 255 Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN); 256 } else { 257 Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP); 258 Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN); 259 } 260 // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1). 261 // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1, 262 // and 1 are already handled as special cases. 263 return ConstantRange(Lower, Upper + 1); 264 } 265 266 ConstantRange 267 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, 268 const ConstantRange &Other, 269 unsigned NoWrapKind) { 270 using OBO = OverflowingBinaryOperator; 271 272 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!"); 273 274 assert((NoWrapKind == OBO::NoSignedWrap || 275 NoWrapKind == OBO::NoUnsignedWrap) && 276 "NoWrapKind invalid!"); 277 278 bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap; 279 unsigned BitWidth = Other.getBitWidth(); 280 281 switch (BinOp) { 282 default: 283 llvm_unreachable("Unsupported binary op"); 284 285 case Instruction::Add: { 286 if (Unsigned) 287 return getNonEmpty(APInt::getZero(BitWidth), -Other.getUnsignedMax()); 288 289 APInt SignedMinVal = APInt::getSignedMinValue(BitWidth); 290 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax(); 291 return getNonEmpty( 292 SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal, 293 SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal); 294 } 295 296 case Instruction::Sub: { 297 if (Unsigned) 298 return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth)); 299 300 APInt SignedMinVal = APInt::getSignedMinValue(BitWidth); 301 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax(); 302 return getNonEmpty( 303 SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal, 304 SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal); 305 } 306 307 case Instruction::Mul: 308 if (Unsigned) 309 return makeExactMulNUWRegion(Other.getUnsignedMax()); 310 311 return makeExactMulNSWRegion(Other.getSignedMin()) 312 .intersectWith(makeExactMulNSWRegion(Other.getSignedMax())); 313 314 case Instruction::Shl: { 315 // For given range of shift amounts, if we ignore all illegal shift amounts 316 // (that always produce poison), what shift amount range is left? 317 ConstantRange ShAmt = Other.intersectWith( 318 ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1))); 319 if (ShAmt.isEmptySet()) { 320 // If the entire range of shift amounts is already poison-producing, 321 // then we can freely add more poison-producing flags ontop of that. 322 return getFull(BitWidth); 323 } 324 // There are some legal shift amounts, we can compute conservatively-correct 325 // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax 326 // to be at most bitwidth-1, which results in most conservative range. 327 APInt ShAmtUMax = ShAmt.getUnsignedMax(); 328 if (Unsigned) 329 return getNonEmpty(APInt::getZero(BitWidth), 330 APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1); 331 return getNonEmpty(APInt::getSignedMinValue(BitWidth).ashr(ShAmtUMax), 332 APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1); 333 } 334 } 335 } 336 337 ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp, 338 const APInt &Other, 339 unsigned NoWrapKind) { 340 // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as 341 // "for all" and "for any" coincide in this case. 342 return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind); 343 } 344 345 bool ConstantRange::isFullSet() const { 346 return Lower == Upper && Lower.isMaxValue(); 347 } 348 349 bool ConstantRange::isEmptySet() const { 350 return Lower == Upper && Lower.isMinValue(); 351 } 352 353 bool ConstantRange::isWrappedSet() const { 354 return Lower.ugt(Upper) && !Upper.isZero(); 355 } 356 357 bool ConstantRange::isUpperWrapped() const { 358 return Lower.ugt(Upper); 359 } 360 361 bool ConstantRange::isSignWrappedSet() const { 362 return Lower.sgt(Upper) && !Upper.isMinSignedValue(); 363 } 364 365 bool ConstantRange::isUpperSignWrapped() const { 366 return Lower.sgt(Upper); 367 } 368 369 bool 370 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const { 371 assert(getBitWidth() == Other.getBitWidth()); 372 if (isFullSet()) 373 return false; 374 if (Other.isFullSet()) 375 return true; 376 return (Upper - Lower).ult(Other.Upper - Other.Lower); 377 } 378 379 bool 380 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const { 381 assert(MaxSize && "MaxSize can't be 0."); 382 // If this a full set, we need special handling to avoid needing an extra bit 383 // to represent the size. 384 if (isFullSet()) 385 return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1); 386 387 return (Upper - Lower).ugt(MaxSize); 388 } 389 390 bool ConstantRange::isAllNegative() const { 391 // Empty set is all negative, full set is not. 392 if (isEmptySet()) 393 return true; 394 if (isFullSet()) 395 return false; 396 397 return !isUpperSignWrapped() && !Upper.isStrictlyPositive(); 398 } 399 400 bool ConstantRange::isAllNonNegative() const { 401 // Empty and full set are automatically treated correctly. 402 return !isSignWrappedSet() && Lower.isNonNegative(); 403 } 404 405 APInt ConstantRange::getUnsignedMax() const { 406 if (isFullSet() || isUpperWrapped()) 407 return APInt::getMaxValue(getBitWidth()); 408 return getUpper() - 1; 409 } 410 411 APInt ConstantRange::getUnsignedMin() const { 412 if (isFullSet() || isWrappedSet()) 413 return APInt::getMinValue(getBitWidth()); 414 return getLower(); 415 } 416 417 APInt ConstantRange::getSignedMax() const { 418 if (isFullSet() || isUpperSignWrapped()) 419 return APInt::getSignedMaxValue(getBitWidth()); 420 return getUpper() - 1; 421 } 422 423 APInt ConstantRange::getSignedMin() const { 424 if (isFullSet() || isSignWrappedSet()) 425 return APInt::getSignedMinValue(getBitWidth()); 426 return getLower(); 427 } 428 429 bool ConstantRange::contains(const APInt &V) const { 430 if (Lower == Upper) 431 return isFullSet(); 432 433 if (!isUpperWrapped()) 434 return Lower.ule(V) && V.ult(Upper); 435 return Lower.ule(V) || V.ult(Upper); 436 } 437 438 bool ConstantRange::contains(const ConstantRange &Other) const { 439 if (isFullSet() || Other.isEmptySet()) return true; 440 if (isEmptySet() || Other.isFullSet()) return false; 441 442 if (!isUpperWrapped()) { 443 if (Other.isUpperWrapped()) 444 return false; 445 446 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper); 447 } 448 449 if (!Other.isUpperWrapped()) 450 return Other.getUpper().ule(Upper) || 451 Lower.ule(Other.getLower()); 452 453 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower()); 454 } 455 456 unsigned ConstantRange::getActiveBits() const { 457 if (isEmptySet()) 458 return 0; 459 460 return getUnsignedMax().getActiveBits(); 461 } 462 463 unsigned ConstantRange::getMinSignedBits() const { 464 if (isEmptySet()) 465 return 0; 466 467 return std::max(getSignedMin().getMinSignedBits(), 468 getSignedMax().getMinSignedBits()); 469 } 470 471 ConstantRange ConstantRange::subtract(const APInt &Val) const { 472 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width"); 473 // If the set is empty or full, don't modify the endpoints. 474 if (Lower == Upper) 475 return *this; 476 return ConstantRange(Lower - Val, Upper - Val); 477 } 478 479 ConstantRange ConstantRange::difference(const ConstantRange &CR) const { 480 return intersectWith(CR.inverse()); 481 } 482 483 static ConstantRange getPreferredRange( 484 const ConstantRange &CR1, const ConstantRange &CR2, 485 ConstantRange::PreferredRangeType Type) { 486 if (Type == ConstantRange::Unsigned) { 487 if (!CR1.isWrappedSet() && CR2.isWrappedSet()) 488 return CR1; 489 if (CR1.isWrappedSet() && !CR2.isWrappedSet()) 490 return CR2; 491 } else if (Type == ConstantRange::Signed) { 492 if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet()) 493 return CR1; 494 if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet()) 495 return CR2; 496 } 497 498 if (CR1.isSizeStrictlySmallerThan(CR2)) 499 return CR1; 500 return CR2; 501 } 502 503 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR, 504 PreferredRangeType Type) const { 505 assert(getBitWidth() == CR.getBitWidth() && 506 "ConstantRange types don't agree!"); 507 508 // Handle common cases. 509 if ( isEmptySet() || CR.isFullSet()) return *this; 510 if (CR.isEmptySet() || isFullSet()) return CR; 511 512 if (!isUpperWrapped() && CR.isUpperWrapped()) 513 return CR.intersectWith(*this, Type); 514 515 if (!isUpperWrapped() && !CR.isUpperWrapped()) { 516 if (Lower.ult(CR.Lower)) { 517 // L---U : this 518 // L---U : CR 519 if (Upper.ule(CR.Lower)) 520 return getEmpty(); 521 522 // L---U : this 523 // L---U : CR 524 if (Upper.ult(CR.Upper)) 525 return ConstantRange(CR.Lower, Upper); 526 527 // L-------U : this 528 // L---U : CR 529 return CR; 530 } 531 // L---U : this 532 // L-------U : CR 533 if (Upper.ult(CR.Upper)) 534 return *this; 535 536 // L-----U : this 537 // L-----U : CR 538 if (Lower.ult(CR.Upper)) 539 return ConstantRange(Lower, CR.Upper); 540 541 // L---U : this 542 // L---U : CR 543 return getEmpty(); 544 } 545 546 if (isUpperWrapped() && !CR.isUpperWrapped()) { 547 if (CR.Lower.ult(Upper)) { 548 // ------U L--- : this 549 // L--U : CR 550 if (CR.Upper.ult(Upper)) 551 return CR; 552 553 // ------U L--- : this 554 // L------U : CR 555 if (CR.Upper.ule(Lower)) 556 return ConstantRange(CR.Lower, Upper); 557 558 // ------U L--- : this 559 // L----------U : CR 560 return getPreferredRange(*this, CR, Type); 561 } 562 if (CR.Lower.ult(Lower)) { 563 // --U L---- : this 564 // L--U : CR 565 if (CR.Upper.ule(Lower)) 566 return getEmpty(); 567 568 // --U L---- : this 569 // L------U : CR 570 return ConstantRange(Lower, CR.Upper); 571 } 572 573 // --U L------ : this 574 // L--U : CR 575 return CR; 576 } 577 578 if (CR.Upper.ult(Upper)) { 579 // ------U L-- : this 580 // --U L------ : CR 581 if (CR.Lower.ult(Upper)) 582 return getPreferredRange(*this, CR, Type); 583 584 // ----U L-- : this 585 // --U L---- : CR 586 if (CR.Lower.ult(Lower)) 587 return ConstantRange(Lower, CR.Upper); 588 589 // ----U L---- : this 590 // --U L-- : CR 591 return CR; 592 } 593 if (CR.Upper.ule(Lower)) { 594 // --U L-- : this 595 // ----U L---- : CR 596 if (CR.Lower.ult(Lower)) 597 return *this; 598 599 // --U L---- : this 600 // ----U L-- : CR 601 return ConstantRange(CR.Lower, Upper); 602 } 603 604 // --U L------ : this 605 // ------U L-- : CR 606 return getPreferredRange(*this, CR, Type); 607 } 608 609 ConstantRange ConstantRange::unionWith(const ConstantRange &CR, 610 PreferredRangeType Type) const { 611 assert(getBitWidth() == CR.getBitWidth() && 612 "ConstantRange types don't agree!"); 613 614 if ( isFullSet() || CR.isEmptySet()) return *this; 615 if (CR.isFullSet() || isEmptySet()) return CR; 616 617 if (!isUpperWrapped() && CR.isUpperWrapped()) 618 return CR.unionWith(*this, Type); 619 620 if (!isUpperWrapped() && !CR.isUpperWrapped()) { 621 // L---U and L---U : this 622 // L---U L---U : CR 623 // result in one of 624 // L---------U 625 // -----U L----- 626 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) 627 return getPreferredRange( 628 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type); 629 630 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower; 631 APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper; 632 633 if (L.isZero() && U.isZero()) 634 return getFull(); 635 636 return ConstantRange(std::move(L), std::move(U)); 637 } 638 639 if (!CR.isUpperWrapped()) { 640 // ------U L----- and ------U L----- : this 641 // L--U L--U : CR 642 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower)) 643 return *this; 644 645 // ------U L----- : this 646 // L---------U : CR 647 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper)) 648 return getFull(); 649 650 // ----U L---- : this 651 // L---U : CR 652 // results in one of 653 // ----------U L---- 654 // ----U L---------- 655 if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower)) 656 return getPreferredRange( 657 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type); 658 659 // ----U L----- : this 660 // L----U : CR 661 if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper)) 662 return ConstantRange(CR.Lower, Upper); 663 664 // ------U L---- : this 665 // L-----U : CR 666 assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) && 667 "ConstantRange::unionWith missed a case with one range wrapped"); 668 return ConstantRange(Lower, CR.Upper); 669 } 670 671 // ------U L---- and ------U L---- : this 672 // -U L----------- and ------------U L : CR 673 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper)) 674 return getFull(); 675 676 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower; 677 APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper; 678 679 return ConstantRange(std::move(L), std::move(U)); 680 } 681 682 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp, 683 uint32_t ResultBitWidth) const { 684 switch (CastOp) { 685 default: 686 llvm_unreachable("unsupported cast type"); 687 case Instruction::Trunc: 688 return truncate(ResultBitWidth); 689 case Instruction::SExt: 690 return signExtend(ResultBitWidth); 691 case Instruction::ZExt: 692 return zeroExtend(ResultBitWidth); 693 case Instruction::BitCast: 694 return *this; 695 case Instruction::FPToUI: 696 case Instruction::FPToSI: 697 if (getBitWidth() == ResultBitWidth) 698 return *this; 699 else 700 return getFull(ResultBitWidth); 701 case Instruction::UIToFP: { 702 // TODO: use input range if available 703 auto BW = getBitWidth(); 704 APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth); 705 APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth); 706 return ConstantRange(std::move(Min), std::move(Max)); 707 } 708 case Instruction::SIToFP: { 709 // TODO: use input range if available 710 auto BW = getBitWidth(); 711 APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth); 712 APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth); 713 return ConstantRange(std::move(SMin), std::move(SMax)); 714 } 715 case Instruction::FPTrunc: 716 case Instruction::FPExt: 717 case Instruction::IntToPtr: 718 case Instruction::PtrToInt: 719 case Instruction::AddrSpaceCast: 720 // Conservatively return getFull set. 721 return getFull(ResultBitWidth); 722 }; 723 } 724 725 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const { 726 if (isEmptySet()) return getEmpty(DstTySize); 727 728 unsigned SrcTySize = getBitWidth(); 729 assert(SrcTySize < DstTySize && "Not a value extension"); 730 if (isFullSet() || isUpperWrapped()) { 731 // Change into [0, 1 << src bit width) 732 APInt LowerExt(DstTySize, 0); 733 if (!Upper) // special case: [X, 0) -- not really wrapping around 734 LowerExt = Lower.zext(DstTySize); 735 return ConstantRange(std::move(LowerExt), 736 APInt::getOneBitSet(DstTySize, SrcTySize)); 737 } 738 739 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize)); 740 } 741 742 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const { 743 if (isEmptySet()) return getEmpty(DstTySize); 744 745 unsigned SrcTySize = getBitWidth(); 746 assert(SrcTySize < DstTySize && "Not a value extension"); 747 748 // special case: [X, INT_MIN) -- not really wrapping around 749 if (Upper.isMinSignedValue()) 750 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize)); 751 752 if (isFullSet() || isSignWrappedSet()) { 753 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1), 754 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1); 755 } 756 757 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize)); 758 } 759 760 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const { 761 assert(getBitWidth() > DstTySize && "Not a value truncation"); 762 if (isEmptySet()) 763 return getEmpty(DstTySize); 764 if (isFullSet()) 765 return getFull(DstTySize); 766 767 APInt LowerDiv(Lower), UpperDiv(Upper); 768 ConstantRange Union(DstTySize, /*isFullSet=*/false); 769 770 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue] 771 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and 772 // then we do the union with [MaxValue, Upper) 773 if (isUpperWrapped()) { 774 // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole 775 // truncated range. 776 if (Upper.getActiveBits() > DstTySize || 777 Upper.countTrailingOnes() == DstTySize) 778 return getFull(DstTySize); 779 780 Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize)); 781 UpperDiv.setAllBits(); 782 783 // Union covers the MaxValue case, so return if the remaining range is just 784 // MaxValue(DstTy). 785 if (LowerDiv == UpperDiv) 786 return Union; 787 } 788 789 // Chop off the most significant bits that are past the destination bitwidth. 790 if (LowerDiv.getActiveBits() > DstTySize) { 791 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv. 792 APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize); 793 LowerDiv -= Adjust; 794 UpperDiv -= Adjust; 795 } 796 797 unsigned UpperDivWidth = UpperDiv.getActiveBits(); 798 if (UpperDivWidth <= DstTySize) 799 return ConstantRange(LowerDiv.trunc(DstTySize), 800 UpperDiv.trunc(DstTySize)).unionWith(Union); 801 802 // The truncated value wraps around. Check if we can do better than fullset. 803 if (UpperDivWidth == DstTySize + 1) { 804 // Clear the MSB so that UpperDiv wraps around. 805 UpperDiv.clearBit(DstTySize); 806 if (UpperDiv.ult(LowerDiv)) 807 return ConstantRange(LowerDiv.trunc(DstTySize), 808 UpperDiv.trunc(DstTySize)).unionWith(Union); 809 } 810 811 return getFull(DstTySize); 812 } 813 814 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const { 815 unsigned SrcTySize = getBitWidth(); 816 if (SrcTySize > DstTySize) 817 return truncate(DstTySize); 818 if (SrcTySize < DstTySize) 819 return zeroExtend(DstTySize); 820 return *this; 821 } 822 823 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const { 824 unsigned SrcTySize = getBitWidth(); 825 if (SrcTySize > DstTySize) 826 return truncate(DstTySize); 827 if (SrcTySize < DstTySize) 828 return signExtend(DstTySize); 829 return *this; 830 } 831 832 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp, 833 const ConstantRange &Other) const { 834 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!"); 835 836 switch (BinOp) { 837 case Instruction::Add: 838 return add(Other); 839 case Instruction::Sub: 840 return sub(Other); 841 case Instruction::Mul: 842 return multiply(Other); 843 case Instruction::UDiv: 844 return udiv(Other); 845 case Instruction::SDiv: 846 return sdiv(Other); 847 case Instruction::URem: 848 return urem(Other); 849 case Instruction::SRem: 850 return srem(Other); 851 case Instruction::Shl: 852 return shl(Other); 853 case Instruction::LShr: 854 return lshr(Other); 855 case Instruction::AShr: 856 return ashr(Other); 857 case Instruction::And: 858 return binaryAnd(Other); 859 case Instruction::Or: 860 return binaryOr(Other); 861 case Instruction::Xor: 862 return binaryXor(Other); 863 // Note: floating point operations applied to abstract ranges are just 864 // ideal integer operations with a lossy representation 865 case Instruction::FAdd: 866 return add(Other); 867 case Instruction::FSub: 868 return sub(Other); 869 case Instruction::FMul: 870 return multiply(Other); 871 default: 872 // Conservatively return getFull set. 873 return getFull(); 874 } 875 } 876 877 ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp, 878 const ConstantRange &Other, 879 unsigned NoWrapKind) const { 880 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!"); 881 882 switch (BinOp) { 883 case Instruction::Add: 884 return addWithNoWrap(Other, NoWrapKind); 885 case Instruction::Sub: 886 return subWithNoWrap(Other, NoWrapKind); 887 default: 888 // Don't know about this Overflowing Binary Operation. 889 // Conservatively fallback to plain binop handling. 890 return binaryOp(BinOp, Other); 891 } 892 } 893 894 bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) { 895 switch (IntrinsicID) { 896 case Intrinsic::uadd_sat: 897 case Intrinsic::usub_sat: 898 case Intrinsic::sadd_sat: 899 case Intrinsic::ssub_sat: 900 case Intrinsic::umin: 901 case Intrinsic::umax: 902 case Intrinsic::smin: 903 case Intrinsic::smax: 904 case Intrinsic::abs: 905 return true; 906 default: 907 return false; 908 } 909 } 910 911 ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID, 912 ArrayRef<ConstantRange> Ops) { 913 switch (IntrinsicID) { 914 case Intrinsic::uadd_sat: 915 return Ops[0].uadd_sat(Ops[1]); 916 case Intrinsic::usub_sat: 917 return Ops[0].usub_sat(Ops[1]); 918 case Intrinsic::sadd_sat: 919 return Ops[0].sadd_sat(Ops[1]); 920 case Intrinsic::ssub_sat: 921 return Ops[0].ssub_sat(Ops[1]); 922 case Intrinsic::umin: 923 return Ops[0].umin(Ops[1]); 924 case Intrinsic::umax: 925 return Ops[0].umax(Ops[1]); 926 case Intrinsic::smin: 927 return Ops[0].smin(Ops[1]); 928 case Intrinsic::smax: 929 return Ops[0].smax(Ops[1]); 930 case Intrinsic::abs: { 931 const APInt *IntMinIsPoison = Ops[1].getSingleElement(); 932 assert(IntMinIsPoison && "Must be known (immarg)"); 933 assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean"); 934 return Ops[0].abs(IntMinIsPoison->getBoolValue()); 935 } 936 default: 937 assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported"); 938 llvm_unreachable("Unsupported intrinsic"); 939 } 940 } 941 942 ConstantRange 943 ConstantRange::add(const ConstantRange &Other) const { 944 if (isEmptySet() || Other.isEmptySet()) 945 return getEmpty(); 946 if (isFullSet() || Other.isFullSet()) 947 return getFull(); 948 949 APInt NewLower = getLower() + Other.getLower(); 950 APInt NewUpper = getUpper() + Other.getUpper() - 1; 951 if (NewLower == NewUpper) 952 return getFull(); 953 954 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper)); 955 if (X.isSizeStrictlySmallerThan(*this) || 956 X.isSizeStrictlySmallerThan(Other)) 957 // We've wrapped, therefore, full set. 958 return getFull(); 959 return X; 960 } 961 962 ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other, 963 unsigned NoWrapKind, 964 PreferredRangeType RangeType) const { 965 // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow). 966 // (X is from this, and Y is from Other) 967 if (isEmptySet() || Other.isEmptySet()) 968 return getEmpty(); 969 if (isFullSet() && Other.isFullSet()) 970 return getFull(); 971 972 using OBO = OverflowingBinaryOperator; 973 ConstantRange Result = add(Other); 974 975 // If an overflow happens for every value pair in these two constant ranges, 976 // we must return Empty set. In this case, we get that for free, because we 977 // get lucky that intersection of add() with uadd_sat()/sadd_sat() results 978 // in an empty set. 979 980 if (NoWrapKind & OBO::NoSignedWrap) 981 Result = Result.intersectWith(sadd_sat(Other), RangeType); 982 983 if (NoWrapKind & OBO::NoUnsignedWrap) 984 Result = Result.intersectWith(uadd_sat(Other), RangeType); 985 986 return Result; 987 } 988 989 ConstantRange 990 ConstantRange::sub(const ConstantRange &Other) const { 991 if (isEmptySet() || Other.isEmptySet()) 992 return getEmpty(); 993 if (isFullSet() || Other.isFullSet()) 994 return getFull(); 995 996 APInt NewLower = getLower() - Other.getUpper() + 1; 997 APInt NewUpper = getUpper() - Other.getLower(); 998 if (NewLower == NewUpper) 999 return getFull(); 1000 1001 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper)); 1002 if (X.isSizeStrictlySmallerThan(*this) || 1003 X.isSizeStrictlySmallerThan(Other)) 1004 // We've wrapped, therefore, full set. 1005 return getFull(); 1006 return X; 1007 } 1008 1009 ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other, 1010 unsigned NoWrapKind, 1011 PreferredRangeType RangeType) const { 1012 // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow). 1013 // (X is from this, and Y is from Other) 1014 if (isEmptySet() || Other.isEmptySet()) 1015 return getEmpty(); 1016 if (isFullSet() && Other.isFullSet()) 1017 return getFull(); 1018 1019 using OBO = OverflowingBinaryOperator; 1020 ConstantRange Result = sub(Other); 1021 1022 // If an overflow happens for every value pair in these two constant ranges, 1023 // we must return Empty set. In signed case, we get that for free, because we 1024 // get lucky that intersection of sub() with ssub_sat() results in an 1025 // empty set. But for unsigned we must perform the overflow check manually. 1026 1027 if (NoWrapKind & OBO::NoSignedWrap) 1028 Result = Result.intersectWith(ssub_sat(Other), RangeType); 1029 1030 if (NoWrapKind & OBO::NoUnsignedWrap) { 1031 if (getUnsignedMax().ult(Other.getUnsignedMin())) 1032 return getEmpty(); // Always overflows. 1033 Result = Result.intersectWith(usub_sat(Other), RangeType); 1034 } 1035 1036 return Result; 1037 } 1038 1039 ConstantRange 1040 ConstantRange::multiply(const ConstantRange &Other) const { 1041 // TODO: If either operand is a single element and the multiply is known to 1042 // be non-wrapping, round the result min and max value to the appropriate 1043 // multiple of that element. If wrapping is possible, at least adjust the 1044 // range according to the greatest power-of-two factor of the single element. 1045 1046 if (isEmptySet() || Other.isEmptySet()) 1047 return getEmpty(); 1048 1049 // Multiplication is signedness-independent. However different ranges can be 1050 // obtained depending on how the input ranges are treated. These different 1051 // ranges are all conservatively correct, but one might be better than the 1052 // other. We calculate two ranges; one treating the inputs as unsigned 1053 // and the other signed, then return the smallest of these ranges. 1054 1055 // Unsigned range first. 1056 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2); 1057 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2); 1058 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2); 1059 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2); 1060 1061 ConstantRange Result_zext = ConstantRange(this_min * Other_min, 1062 this_max * Other_max + 1); 1063 ConstantRange UR = Result_zext.truncate(getBitWidth()); 1064 1065 // If the unsigned range doesn't wrap, and isn't negative then it's a range 1066 // from one positive number to another which is as good as we can generate. 1067 // In this case, skip the extra work of generating signed ranges which aren't 1068 // going to be better than this range. 1069 if (!UR.isUpperWrapped() && 1070 (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue())) 1071 return UR; 1072 1073 // Now the signed range. Because we could be dealing with negative numbers 1074 // here, the lower bound is the smallest of the cartesian product of the 1075 // lower and upper ranges; for example: 1076 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6. 1077 // Similarly for the upper bound, swapping min for max. 1078 1079 this_min = getSignedMin().sext(getBitWidth() * 2); 1080 this_max = getSignedMax().sext(getBitWidth() * 2); 1081 Other_min = Other.getSignedMin().sext(getBitWidth() * 2); 1082 Other_max = Other.getSignedMax().sext(getBitWidth() * 2); 1083 1084 auto L = {this_min * Other_min, this_min * Other_max, 1085 this_max * Other_min, this_max * Other_max}; 1086 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); }; 1087 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1); 1088 ConstantRange SR = Result_sext.truncate(getBitWidth()); 1089 1090 return UR.isSizeStrictlySmallerThan(SR) ? UR : SR; 1091 } 1092 1093 ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const { 1094 if (isEmptySet() || Other.isEmptySet()) 1095 return getEmpty(); 1096 1097 APInt Min = getSignedMin(); 1098 APInt Max = getSignedMax(); 1099 APInt OtherMin = Other.getSignedMin(); 1100 APInt OtherMax = Other.getSignedMax(); 1101 1102 bool O1, O2, O3, O4; 1103 auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2), 1104 Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)}; 1105 if (O1 || O2 || O3 || O4) 1106 return getFull(); 1107 1108 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); }; 1109 return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1); 1110 } 1111 1112 ConstantRange 1113 ConstantRange::smax(const ConstantRange &Other) const { 1114 // X smax Y is: range(smax(X_smin, Y_smin), 1115 // smax(X_smax, Y_smax)) 1116 if (isEmptySet() || Other.isEmptySet()) 1117 return getEmpty(); 1118 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin()); 1119 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1; 1120 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU)); 1121 if (isSignWrappedSet() || Other.isSignWrappedSet()) 1122 return Res.intersectWith(unionWith(Other, Signed), Signed); 1123 return Res; 1124 } 1125 1126 ConstantRange 1127 ConstantRange::umax(const ConstantRange &Other) const { 1128 // X umax Y is: range(umax(X_umin, Y_umin), 1129 // umax(X_umax, Y_umax)) 1130 if (isEmptySet() || Other.isEmptySet()) 1131 return getEmpty(); 1132 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()); 1133 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1; 1134 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU)); 1135 if (isWrappedSet() || Other.isWrappedSet()) 1136 return Res.intersectWith(unionWith(Other, Unsigned), Unsigned); 1137 return Res; 1138 } 1139 1140 ConstantRange 1141 ConstantRange::smin(const ConstantRange &Other) const { 1142 // X smin Y is: range(smin(X_smin, Y_smin), 1143 // smin(X_smax, Y_smax)) 1144 if (isEmptySet() || Other.isEmptySet()) 1145 return getEmpty(); 1146 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin()); 1147 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1; 1148 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU)); 1149 if (isSignWrappedSet() || Other.isSignWrappedSet()) 1150 return Res.intersectWith(unionWith(Other, Signed), Signed); 1151 return Res; 1152 } 1153 1154 ConstantRange 1155 ConstantRange::umin(const ConstantRange &Other) const { 1156 // X umin Y is: range(umin(X_umin, Y_umin), 1157 // umin(X_umax, Y_umax)) 1158 if (isEmptySet() || Other.isEmptySet()) 1159 return getEmpty(); 1160 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin()); 1161 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1; 1162 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU)); 1163 if (isWrappedSet() || Other.isWrappedSet()) 1164 return Res.intersectWith(unionWith(Other, Unsigned), Unsigned); 1165 return Res; 1166 } 1167 1168 ConstantRange 1169 ConstantRange::udiv(const ConstantRange &RHS) const { 1170 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero()) 1171 return getEmpty(); 1172 1173 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax()); 1174 1175 APInt RHS_umin = RHS.getUnsignedMin(); 1176 if (RHS_umin.isZero()) { 1177 // We want the lowest value in RHS excluding zero. Usually that would be 1 1178 // except for a range in the form of [X, 1) in which case it would be X. 1179 if (RHS.getUpper() == 1) 1180 RHS_umin = RHS.getLower(); 1181 else 1182 RHS_umin = 1; 1183 } 1184 1185 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1; 1186 return getNonEmpty(std::move(Lower), std::move(Upper)); 1187 } 1188 1189 ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const { 1190 // We split up the LHS and RHS into positive and negative components 1191 // and then also compute the positive and negative components of the result 1192 // separately by combining division results with the appropriate signs. 1193 APInt Zero = APInt::getZero(getBitWidth()); 1194 APInt SignedMin = APInt::getSignedMinValue(getBitWidth()); 1195 ConstantRange PosFilter(APInt(getBitWidth(), 1), SignedMin); 1196 ConstantRange NegFilter(SignedMin, Zero); 1197 ConstantRange PosL = intersectWith(PosFilter); 1198 ConstantRange NegL = intersectWith(NegFilter); 1199 ConstantRange PosR = RHS.intersectWith(PosFilter); 1200 ConstantRange NegR = RHS.intersectWith(NegFilter); 1201 1202 ConstantRange PosRes = getEmpty(); 1203 if (!PosL.isEmptySet() && !PosR.isEmptySet()) 1204 // pos / pos = pos. 1205 PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1), 1206 (PosL.Upper - 1).sdiv(PosR.Lower) + 1); 1207 1208 if (!NegL.isEmptySet() && !NegR.isEmptySet()) { 1209 // neg / neg = pos. 1210 // 1211 // We need to deal with one tricky case here: SignedMin / -1 is UB on the 1212 // IR level, so we'll want to exclude this case when calculating bounds. 1213 // (For APInts the operation is well-defined and yields SignedMin.) We 1214 // handle this by dropping either SignedMin from the LHS or -1 from the RHS. 1215 APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower); 1216 if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) { 1217 // Remove -1 from the LHS. Skip if it's the only element, as this would 1218 // leave us with an empty set. 1219 if (!NegR.Lower.isAllOnes()) { 1220 APInt AdjNegRUpper; 1221 if (RHS.Lower.isAllOnes()) 1222 // Negative part of [-1, X] without -1 is [SignedMin, X]. 1223 AdjNegRUpper = RHS.Upper; 1224 else 1225 // [X, -1] without -1 is [X, -2]. 1226 AdjNegRUpper = NegR.Upper - 1; 1227 1228 PosRes = PosRes.unionWith( 1229 ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1)); 1230 } 1231 1232 // Remove SignedMin from the RHS. Skip if it's the only element, as this 1233 // would leave us with an empty set. 1234 if (NegL.Upper != SignedMin + 1) { 1235 APInt AdjNegLLower; 1236 if (Upper == SignedMin + 1) 1237 // Negative part of [X, SignedMin] without SignedMin is [X, -1]. 1238 AdjNegLLower = Lower; 1239 else 1240 // [SignedMin, X] without SignedMin is [SignedMin + 1, X]. 1241 AdjNegLLower = NegL.Lower + 1; 1242 1243 PosRes = PosRes.unionWith( 1244 ConstantRange(std::move(Lo), 1245 AdjNegLLower.sdiv(NegR.Upper - 1) + 1)); 1246 } 1247 } else { 1248 PosRes = PosRes.unionWith( 1249 ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1)); 1250 } 1251 } 1252 1253 ConstantRange NegRes = getEmpty(); 1254 if (!PosL.isEmptySet() && !NegR.isEmptySet()) 1255 // pos / neg = neg. 1256 NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1), 1257 PosL.Lower.sdiv(NegR.Lower) + 1); 1258 1259 if (!NegL.isEmptySet() && !PosR.isEmptySet()) 1260 // neg / pos = neg. 1261 NegRes = NegRes.unionWith( 1262 ConstantRange(NegL.Lower.sdiv(PosR.Lower), 1263 (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1)); 1264 1265 // Prefer a non-wrapping signed range here. 1266 ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed); 1267 1268 // Preserve the zero that we dropped when splitting the LHS by sign. 1269 if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet())) 1270 Res = Res.unionWith(ConstantRange(Zero)); 1271 return Res; 1272 } 1273 1274 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const { 1275 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero()) 1276 return getEmpty(); 1277 1278 if (const APInt *RHSInt = RHS.getSingleElement()) { 1279 // UREM by null is UB. 1280 if (RHSInt->isZero()) 1281 return getEmpty(); 1282 // Use APInt's implementation of UREM for single element ranges. 1283 if (const APInt *LHSInt = getSingleElement()) 1284 return {LHSInt->urem(*RHSInt)}; 1285 } 1286 1287 // L % R for L < R is L. 1288 if (getUnsignedMax().ult(RHS.getUnsignedMin())) 1289 return *this; 1290 1291 // L % R is <= L and < R. 1292 APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1; 1293 return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper)); 1294 } 1295 1296 ConstantRange ConstantRange::srem(const ConstantRange &RHS) const { 1297 if (isEmptySet() || RHS.isEmptySet()) 1298 return getEmpty(); 1299 1300 if (const APInt *RHSInt = RHS.getSingleElement()) { 1301 // SREM by null is UB. 1302 if (RHSInt->isZero()) 1303 return getEmpty(); 1304 // Use APInt's implementation of SREM for single element ranges. 1305 if (const APInt *LHSInt = getSingleElement()) 1306 return {LHSInt->srem(*RHSInt)}; 1307 } 1308 1309 ConstantRange AbsRHS = RHS.abs(); 1310 APInt MinAbsRHS = AbsRHS.getUnsignedMin(); 1311 APInt MaxAbsRHS = AbsRHS.getUnsignedMax(); 1312 1313 // Modulus by zero is UB. 1314 if (MaxAbsRHS.isZero()) 1315 return getEmpty(); 1316 1317 if (MinAbsRHS.isZero()) 1318 ++MinAbsRHS; 1319 1320 APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax(); 1321 1322 if (MinLHS.isNonNegative()) { 1323 // L % R for L < R is L. 1324 if (MaxLHS.ult(MinAbsRHS)) 1325 return *this; 1326 1327 // L % R is <= L and < R. 1328 APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1; 1329 return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper)); 1330 } 1331 1332 // Same basic logic as above, but the result is negative. 1333 if (MaxLHS.isNegative()) { 1334 if (MinLHS.ugt(-MinAbsRHS)) 1335 return *this; 1336 1337 APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1); 1338 return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1)); 1339 } 1340 1341 // LHS range crosses zero. 1342 APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1); 1343 APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1; 1344 return ConstantRange(std::move(Lower), std::move(Upper)); 1345 } 1346 1347 ConstantRange ConstantRange::binaryNot() const { 1348 return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this); 1349 } 1350 1351 ConstantRange 1352 ConstantRange::binaryAnd(const ConstantRange &Other) const { 1353 if (isEmptySet() || Other.isEmptySet()) 1354 return getEmpty(); 1355 1356 // Use APInt's implementation of AND for single element ranges. 1357 if (isSingleElement() && Other.isSingleElement()) 1358 return {*getSingleElement() & *Other.getSingleElement()}; 1359 1360 // TODO: replace this with something less conservative 1361 1362 APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax()); 1363 return getNonEmpty(APInt::getZero(getBitWidth()), std::move(umin) + 1); 1364 } 1365 1366 ConstantRange 1367 ConstantRange::binaryOr(const ConstantRange &Other) const { 1368 if (isEmptySet() || Other.isEmptySet()) 1369 return getEmpty(); 1370 1371 // Use APInt's implementation of OR for single element ranges. 1372 if (isSingleElement() && Other.isSingleElement()) 1373 return {*getSingleElement() | *Other.getSingleElement()}; 1374 1375 // TODO: replace this with something less conservative 1376 1377 APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()); 1378 return getNonEmpty(std::move(umax), APInt::getZero(getBitWidth())); 1379 } 1380 1381 ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const { 1382 if (isEmptySet() || Other.isEmptySet()) 1383 return getEmpty(); 1384 1385 // Use APInt's implementation of XOR for single element ranges. 1386 if (isSingleElement() && Other.isSingleElement()) 1387 return {*getSingleElement() ^ *Other.getSingleElement()}; 1388 1389 // Special-case binary complement, since we can give a precise answer. 1390 if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes()) 1391 return binaryNot(); 1392 if (isSingleElement() && getSingleElement()->isAllOnes()) 1393 return Other.binaryNot(); 1394 1395 // TODO: replace this with something less conservative 1396 return getFull(); 1397 } 1398 1399 ConstantRange 1400 ConstantRange::shl(const ConstantRange &Other) const { 1401 if (isEmptySet() || Other.isEmptySet()) 1402 return getEmpty(); 1403 1404 APInt Min = getUnsignedMin(); 1405 APInt Max = getUnsignedMax(); 1406 if (const APInt *RHS = Other.getSingleElement()) { 1407 unsigned BW = getBitWidth(); 1408 if (RHS->uge(BW)) 1409 return getEmpty(); 1410 1411 unsigned EqualLeadingBits = (Min ^ Max).countLeadingZeros(); 1412 if (RHS->ule(EqualLeadingBits)) 1413 return getNonEmpty(Min << *RHS, (Max << *RHS) + 1); 1414 1415 return getNonEmpty(APInt::getZero(BW), 1416 APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1); 1417 } 1418 1419 APInt OtherMax = Other.getUnsignedMax(); 1420 1421 // There's overflow! 1422 if (OtherMax.ugt(Max.countLeadingZeros())) 1423 return getFull(); 1424 1425 // FIXME: implement the other tricky cases 1426 1427 Min <<= Other.getUnsignedMin(); 1428 Max <<= OtherMax; 1429 1430 return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1); 1431 } 1432 1433 ConstantRange 1434 ConstantRange::lshr(const ConstantRange &Other) const { 1435 if (isEmptySet() || Other.isEmptySet()) 1436 return getEmpty(); 1437 1438 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1; 1439 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax()); 1440 return getNonEmpty(std::move(min), std::move(max)); 1441 } 1442 1443 ConstantRange 1444 ConstantRange::ashr(const ConstantRange &Other) const { 1445 if (isEmptySet() || Other.isEmptySet()) 1446 return getEmpty(); 1447 1448 // May straddle zero, so handle both positive and negative cases. 1449 // 'PosMax' is the upper bound of the result of the ashr 1450 // operation, when Upper of the LHS of ashr is a non-negative. 1451 // number. Since ashr of a non-negative number will result in a 1452 // smaller number, the Upper value of LHS is shifted right with 1453 // the minimum value of 'Other' instead of the maximum value. 1454 APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1; 1455 1456 // 'PosMin' is the lower bound of the result of the ashr 1457 // operation, when Lower of the LHS is a non-negative number. 1458 // Since ashr of a non-negative number will result in a smaller 1459 // number, the Lower value of LHS is shifted right with the 1460 // maximum value of 'Other'. 1461 APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax()); 1462 1463 // 'NegMax' is the upper bound of the result of the ashr 1464 // operation, when Upper of the LHS of ashr is a negative number. 1465 // Since 'ashr' of a negative number will result in a bigger 1466 // number, the Upper value of LHS is shifted right with the 1467 // maximum value of 'Other'. 1468 APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1; 1469 1470 // 'NegMin' is the lower bound of the result of the ashr 1471 // operation, when Lower of the LHS of ashr is a negative number. 1472 // Since 'ashr' of a negative number will result in a bigger 1473 // number, the Lower value of LHS is shifted right with the 1474 // minimum value of 'Other'. 1475 APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin()); 1476 1477 APInt max, min; 1478 if (getSignedMin().isNonNegative()) { 1479 // Upper and Lower of LHS are non-negative. 1480 min = PosMin; 1481 max = PosMax; 1482 } else if (getSignedMax().isNegative()) { 1483 // Upper and Lower of LHS are negative. 1484 min = NegMin; 1485 max = NegMax; 1486 } else { 1487 // Upper is non-negative and Lower is negative. 1488 min = NegMin; 1489 max = PosMax; 1490 } 1491 return getNonEmpty(std::move(min), std::move(max)); 1492 } 1493 1494 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const { 1495 if (isEmptySet() || Other.isEmptySet()) 1496 return getEmpty(); 1497 1498 APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin()); 1499 APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1; 1500 return getNonEmpty(std::move(NewL), std::move(NewU)); 1501 } 1502 1503 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const { 1504 if (isEmptySet() || Other.isEmptySet()) 1505 return getEmpty(); 1506 1507 APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin()); 1508 APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1; 1509 return getNonEmpty(std::move(NewL), std::move(NewU)); 1510 } 1511 1512 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const { 1513 if (isEmptySet() || Other.isEmptySet()) 1514 return getEmpty(); 1515 1516 APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax()); 1517 APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1; 1518 return getNonEmpty(std::move(NewL), std::move(NewU)); 1519 } 1520 1521 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const { 1522 if (isEmptySet() || Other.isEmptySet()) 1523 return getEmpty(); 1524 1525 APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax()); 1526 APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1; 1527 return getNonEmpty(std::move(NewL), std::move(NewU)); 1528 } 1529 1530 ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const { 1531 if (isEmptySet() || Other.isEmptySet()) 1532 return getEmpty(); 1533 1534 APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin()); 1535 APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1; 1536 return getNonEmpty(std::move(NewL), std::move(NewU)); 1537 } 1538 1539 ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const { 1540 if (isEmptySet() || Other.isEmptySet()) 1541 return getEmpty(); 1542 1543 // Because we could be dealing with negative numbers here, the lower bound is 1544 // the smallest of the cartesian product of the lower and upper ranges; 1545 // for example: 1546 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6. 1547 // Similarly for the upper bound, swapping min for max. 1548 1549 APInt Min = getSignedMin(); 1550 APInt Max = getSignedMax(); 1551 APInt OtherMin = Other.getSignedMin(); 1552 APInt OtherMax = Other.getSignedMax(); 1553 1554 auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax), 1555 Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)}; 1556 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); }; 1557 return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1); 1558 } 1559 1560 ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const { 1561 if (isEmptySet() || Other.isEmptySet()) 1562 return getEmpty(); 1563 1564 APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin()); 1565 APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1; 1566 return getNonEmpty(std::move(NewL), std::move(NewU)); 1567 } 1568 1569 ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const { 1570 if (isEmptySet() || Other.isEmptySet()) 1571 return getEmpty(); 1572 1573 APInt Min = getSignedMin(), Max = getSignedMax(); 1574 APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax(); 1575 APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax); 1576 APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1; 1577 return getNonEmpty(std::move(NewL), std::move(NewU)); 1578 } 1579 1580 ConstantRange ConstantRange::inverse() const { 1581 if (isFullSet()) 1582 return getEmpty(); 1583 if (isEmptySet()) 1584 return getFull(); 1585 return ConstantRange(Upper, Lower); 1586 } 1587 1588 ConstantRange ConstantRange::abs(bool IntMinIsPoison) const { 1589 if (isEmptySet()) 1590 return getEmpty(); 1591 1592 if (isSignWrappedSet()) { 1593 APInt Lo; 1594 // Check whether the range crosses zero. 1595 if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive()) 1596 Lo = APInt::getZero(getBitWidth()); 1597 else 1598 Lo = APIntOps::umin(Lower, -Upper + 1); 1599 1600 // If SignedMin is not poison, then it is included in the result range. 1601 if (IntMinIsPoison) 1602 return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth())); 1603 else 1604 return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1); 1605 } 1606 1607 APInt SMin = getSignedMin(), SMax = getSignedMax(); 1608 1609 // Skip SignedMin if it is poison. 1610 if (IntMinIsPoison && SMin.isMinSignedValue()) { 1611 // The range may become empty if it *only* contains SignedMin. 1612 if (SMax.isMinSignedValue()) 1613 return getEmpty(); 1614 ++SMin; 1615 } 1616 1617 // All non-negative. 1618 if (SMin.isNonNegative()) 1619 return *this; 1620 1621 // All negative. 1622 if (SMax.isNegative()) 1623 return ConstantRange(-SMax, -SMin + 1); 1624 1625 // Range crosses zero. 1626 return ConstantRange(APInt::getZero(getBitWidth()), 1627 APIntOps::umax(-SMin, SMax) + 1); 1628 } 1629 1630 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow( 1631 const ConstantRange &Other) const { 1632 if (isEmptySet() || Other.isEmptySet()) 1633 return OverflowResult::MayOverflow; 1634 1635 APInt Min = getUnsignedMin(), Max = getUnsignedMax(); 1636 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax(); 1637 1638 // a u+ b overflows high iff a u> ~b. 1639 if (Min.ugt(~OtherMin)) 1640 return OverflowResult::AlwaysOverflowsHigh; 1641 if (Max.ugt(~OtherMax)) 1642 return OverflowResult::MayOverflow; 1643 return OverflowResult::NeverOverflows; 1644 } 1645 1646 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow( 1647 const ConstantRange &Other) const { 1648 if (isEmptySet() || Other.isEmptySet()) 1649 return OverflowResult::MayOverflow; 1650 1651 APInt Min = getSignedMin(), Max = getSignedMax(); 1652 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax(); 1653 1654 APInt SignedMin = APInt::getSignedMinValue(getBitWidth()); 1655 APInt SignedMax = APInt::getSignedMaxValue(getBitWidth()); 1656 1657 // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b. 1658 // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b. 1659 if (Min.isNonNegative() && OtherMin.isNonNegative() && 1660 Min.sgt(SignedMax - OtherMin)) 1661 return OverflowResult::AlwaysOverflowsHigh; 1662 if (Max.isNegative() && OtherMax.isNegative() && 1663 Max.slt(SignedMin - OtherMax)) 1664 return OverflowResult::AlwaysOverflowsLow; 1665 1666 if (Max.isNonNegative() && OtherMax.isNonNegative() && 1667 Max.sgt(SignedMax - OtherMax)) 1668 return OverflowResult::MayOverflow; 1669 if (Min.isNegative() && OtherMin.isNegative() && 1670 Min.slt(SignedMin - OtherMin)) 1671 return OverflowResult::MayOverflow; 1672 1673 return OverflowResult::NeverOverflows; 1674 } 1675 1676 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow( 1677 const ConstantRange &Other) const { 1678 if (isEmptySet() || Other.isEmptySet()) 1679 return OverflowResult::MayOverflow; 1680 1681 APInt Min = getUnsignedMin(), Max = getUnsignedMax(); 1682 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax(); 1683 1684 // a u- b overflows low iff a u< b. 1685 if (Max.ult(OtherMin)) 1686 return OverflowResult::AlwaysOverflowsLow; 1687 if (Min.ult(OtherMax)) 1688 return OverflowResult::MayOverflow; 1689 return OverflowResult::NeverOverflows; 1690 } 1691 1692 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow( 1693 const ConstantRange &Other) const { 1694 if (isEmptySet() || Other.isEmptySet()) 1695 return OverflowResult::MayOverflow; 1696 1697 APInt Min = getSignedMin(), Max = getSignedMax(); 1698 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax(); 1699 1700 APInt SignedMin = APInt::getSignedMinValue(getBitWidth()); 1701 APInt SignedMax = APInt::getSignedMaxValue(getBitWidth()); 1702 1703 // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b. 1704 // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b. 1705 if (Min.isNonNegative() && OtherMax.isNegative() && 1706 Min.sgt(SignedMax + OtherMax)) 1707 return OverflowResult::AlwaysOverflowsHigh; 1708 if (Max.isNegative() && OtherMin.isNonNegative() && 1709 Max.slt(SignedMin + OtherMin)) 1710 return OverflowResult::AlwaysOverflowsLow; 1711 1712 if (Max.isNonNegative() && OtherMin.isNegative() && 1713 Max.sgt(SignedMax + OtherMin)) 1714 return OverflowResult::MayOverflow; 1715 if (Min.isNegative() && OtherMax.isNonNegative() && 1716 Min.slt(SignedMin + OtherMax)) 1717 return OverflowResult::MayOverflow; 1718 1719 return OverflowResult::NeverOverflows; 1720 } 1721 1722 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow( 1723 const ConstantRange &Other) const { 1724 if (isEmptySet() || Other.isEmptySet()) 1725 return OverflowResult::MayOverflow; 1726 1727 APInt Min = getUnsignedMin(), Max = getUnsignedMax(); 1728 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax(); 1729 bool Overflow; 1730 1731 (void) Min.umul_ov(OtherMin, Overflow); 1732 if (Overflow) 1733 return OverflowResult::AlwaysOverflowsHigh; 1734 1735 (void) Max.umul_ov(OtherMax, Overflow); 1736 if (Overflow) 1737 return OverflowResult::MayOverflow; 1738 1739 return OverflowResult::NeverOverflows; 1740 } 1741 1742 void ConstantRange::print(raw_ostream &OS) const { 1743 if (isFullSet()) 1744 OS << "full-set"; 1745 else if (isEmptySet()) 1746 OS << "empty-set"; 1747 else 1748 OS << "[" << Lower << "," << Upper << ")"; 1749 } 1750 1751 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1752 LLVM_DUMP_METHOD void ConstantRange::dump() const { 1753 print(dbgs()); 1754 } 1755 #endif 1756 1757 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) { 1758 const unsigned NumRanges = Ranges.getNumOperands() / 2; 1759 assert(NumRanges >= 1 && "Must have at least one range!"); 1760 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs"); 1761 1762 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0)); 1763 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1)); 1764 1765 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue()); 1766 1767 for (unsigned i = 1; i < NumRanges; ++i) { 1768 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0)); 1769 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1)); 1770 1771 // Note: unionWith will potentially create a range that contains values not 1772 // contained in any of the original N ranges. 1773 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue())); 1774 } 1775 1776 return CR; 1777 } 1778