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/Metadata.h" 30 #include "llvm/IR/Operator.h" 31 #include "llvm/Support/Compiler.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/KnownBits.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <algorithm> 37 #include <cassert> 38 #include <cstdint> 39 40 using namespace llvm; 41 42 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) 43 : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)), 44 Upper(Lower) {} 45 46 ConstantRange::ConstantRange(APInt V) 47 : Lower(std::move(V)), Upper(Lower + 1) {} 48 49 ConstantRange::ConstantRange(APInt L, APInt U) 50 : Lower(std::move(L)), Upper(std::move(U)) { 51 assert(Lower.getBitWidth() == Upper.getBitWidth() && 52 "ConstantRange with unequal bit widths"); 53 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) && 54 "Lower == Upper, but they aren't min or max value!"); 55 } 56 57 ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known, 58 bool IsSigned) { 59 assert(!Known.hasConflict() && "Expected valid KnownBits"); 60 61 if (Known.isUnknown()) 62 return getFull(Known.getBitWidth()); 63 64 // For unsigned ranges, or signed ranges with known sign bit, create a simple 65 // range between the smallest and largest possible value. 66 if (!IsSigned || Known.isNegative() || Known.isNonNegative()) 67 return ConstantRange(Known.One, ~Known.Zero + 1); 68 69 // If we don't know the sign bit, pick the lower bound as a negative number 70 // and the upper bound as a non-negative one. 71 APInt Lower = Known.One, Upper = ~Known.Zero; 72 Lower.setSignBit(); 73 Upper.clearSignBit(); 74 return ConstantRange(Lower, Upper + 1); 75 } 76 77 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred, 78 const ConstantRange &CR) { 79 if (CR.isEmptySet()) 80 return CR; 81 82 uint32_t W = CR.getBitWidth(); 83 switch (Pred) { 84 default: 85 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()"); 86 case CmpInst::ICMP_EQ: 87 return CR; 88 case CmpInst::ICMP_NE: 89 if (CR.isSingleElement()) 90 return ConstantRange(CR.getUpper(), CR.getLower()); 91 return getFull(W); 92 case CmpInst::ICMP_ULT: { 93 APInt UMax(CR.getUnsignedMax()); 94 if (UMax.isMinValue()) 95 return getEmpty(W); 96 return ConstantRange(APInt::getMinValue(W), std::move(UMax)); 97 } 98 case CmpInst::ICMP_SLT: { 99 APInt SMax(CR.getSignedMax()); 100 if (SMax.isMinSignedValue()) 101 return getEmpty(W); 102 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax)); 103 } 104 case CmpInst::ICMP_ULE: { 105 APInt UMax(CR.getUnsignedMax()); 106 if (UMax.isMaxValue()) 107 return getFull(W); 108 return ConstantRange(APInt::getMinValue(W), std::move(UMax) + 1); 109 } 110 case CmpInst::ICMP_SLE: { 111 APInt SMax(CR.getSignedMax()); 112 if (SMax.isMaxSignedValue()) 113 return getFull(W); 114 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax) + 1); 115 } 116 case CmpInst::ICMP_UGT: { 117 APInt UMin(CR.getUnsignedMin()); 118 if (UMin.isMaxValue()) 119 return getEmpty(W); 120 return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W)); 121 } 122 case CmpInst::ICMP_SGT: { 123 APInt SMin(CR.getSignedMin()); 124 if (SMin.isMaxSignedValue()) 125 return getEmpty(W); 126 return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W)); 127 } 128 case CmpInst::ICMP_UGE: { 129 APInt UMin(CR.getUnsignedMin()); 130 if (UMin.isMinValue()) 131 return getFull(W); 132 return ConstantRange(std::move(UMin), APInt::getNullValue(W)); 133 } 134 case CmpInst::ICMP_SGE: { 135 APInt SMin(CR.getSignedMin()); 136 if (SMin.isMinSignedValue()) 137 return getFull(W); 138 return ConstantRange(std::move(SMin), APInt::getSignedMinValue(W)); 139 } 140 } 141 } 142 143 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred, 144 const ConstantRange &CR) { 145 // Follows from De-Morgan's laws: 146 // 147 // ~(~A union ~B) == A intersect B. 148 // 149 return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR) 150 .inverse(); 151 } 152 153 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred, 154 const APInt &C) { 155 // Computes the exact range that is equal to both the constant ranges returned 156 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true 157 // when RHS is a singleton such as an APInt and so the assert is valid. 158 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion 159 // returns [0,4) but makeSatisfyICmpRegion returns [0,2). 160 // 161 assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C)); 162 return makeAllowedICmpRegion(Pred, C); 163 } 164 165 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred, 166 APInt &RHS) const { 167 bool Success = false; 168 169 if (isFullSet() || isEmptySet()) { 170 Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE; 171 RHS = APInt(getBitWidth(), 0); 172 Success = true; 173 } else if (auto *OnlyElt = getSingleElement()) { 174 Pred = CmpInst::ICMP_EQ; 175 RHS = *OnlyElt; 176 Success = true; 177 } else if (auto *OnlyMissingElt = getSingleMissingElement()) { 178 Pred = CmpInst::ICMP_NE; 179 RHS = *OnlyMissingElt; 180 Success = true; 181 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) { 182 Pred = 183 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT; 184 RHS = getUpper(); 185 Success = true; 186 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) { 187 Pred = 188 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE; 189 RHS = getLower(); 190 Success = true; 191 } 192 193 assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) && 194 "Bad result!"); 195 196 return Success; 197 } 198 199 ConstantRange 200 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, 201 const ConstantRange &Other, 202 unsigned NoWrapKind) { 203 using OBO = OverflowingBinaryOperator; 204 205 // Computes the intersection of CR0 and CR1. It is different from 206 // intersectWith in that the ConstantRange returned will only contain elements 207 // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or 208 // not, of both X and Y). 209 auto SubsetIntersect = 210 [](const ConstantRange &CR0, const ConstantRange &CR1) { 211 return CR0.inverse().unionWith(CR1.inverse()).inverse(); 212 }; 213 214 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!"); 215 216 assert((NoWrapKind == OBO::NoSignedWrap || 217 NoWrapKind == OBO::NoUnsignedWrap || 218 NoWrapKind == (OBO::NoUnsignedWrap | OBO::NoSignedWrap)) && 219 "NoWrapKind invalid!"); 220 221 unsigned BitWidth = Other.getBitWidth(); 222 ConstantRange Result(BitWidth, /* full */ true); 223 224 switch (BinOp) { 225 default: 226 // Conservative answer: empty set 227 return getEmpty(BitWidth); 228 229 case Instruction::Add: 230 if (auto *C = Other.getSingleElement()) 231 if (C->isNullValue()) 232 // Full set: nothing signed / unsigned wraps when added to 0. 233 return getFull(BitWidth); 234 if (NoWrapKind & OBO::NoUnsignedWrap) 235 Result = 236 SubsetIntersect(Result, ConstantRange(APInt::getNullValue(BitWidth), 237 -Other.getUnsignedMax())); 238 if (NoWrapKind & OBO::NoSignedWrap) { 239 const APInt &SignedMin = Other.getSignedMin(); 240 const APInt &SignedMax = Other.getSignedMax(); 241 if (SignedMax.isStrictlyPositive()) 242 Result = SubsetIntersect( 243 Result, 244 ConstantRange(APInt::getSignedMinValue(BitWidth), 245 APInt::getSignedMinValue(BitWidth) - SignedMax)); 246 if (SignedMin.isNegative()) 247 Result = SubsetIntersect( 248 Result, 249 ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin, 250 APInt::getSignedMinValue(BitWidth))); 251 } 252 return Result; 253 254 case Instruction::Sub: 255 if (auto *C = Other.getSingleElement()) 256 if (C->isNullValue()) 257 // Full set: nothing signed / unsigned wraps when subtracting 0. 258 return getFull(BitWidth); 259 if (NoWrapKind & OBO::NoUnsignedWrap) 260 Result = 261 SubsetIntersect(Result, ConstantRange(Other.getUnsignedMax(), 262 APInt::getMinValue(BitWidth))); 263 if (NoWrapKind & OBO::NoSignedWrap) { 264 const APInt &SignedMin = Other.getSignedMin(); 265 const APInt &SignedMax = Other.getSignedMax(); 266 if (SignedMax.isStrictlyPositive()) 267 Result = SubsetIntersect( 268 Result, 269 ConstantRange(APInt::getSignedMinValue(BitWidth) + SignedMax, 270 APInt::getSignedMinValue(BitWidth))); 271 if (SignedMin.isNegative()) 272 Result = SubsetIntersect( 273 Result, 274 ConstantRange(APInt::getSignedMinValue(BitWidth), 275 APInt::getSignedMinValue(BitWidth) + SignedMin)); 276 } 277 return Result; 278 case Instruction::Mul: { 279 if (NoWrapKind == (OBO::NoSignedWrap | OBO::NoUnsignedWrap)) { 280 return SubsetIntersect( 281 makeGuaranteedNoWrapRegion(BinOp, Other, OBO::NoSignedWrap), 282 makeGuaranteedNoWrapRegion(BinOp, Other, OBO::NoUnsignedWrap)); 283 } 284 285 // Equivalent to calling makeGuaranteedNoWrapRegion() on [V, V+1). 286 const bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap; 287 const auto makeSingleValueRegion = [Unsigned, 288 BitWidth](APInt V) -> ConstantRange { 289 // Handle special case for 0, -1 and 1. See the last for reason why we 290 // specialize -1 and 1. 291 if (V == 0 || V.isOneValue()) 292 return getFull(BitWidth); 293 294 APInt MinValue, MaxValue; 295 if (Unsigned) { 296 MinValue = APInt::getMinValue(BitWidth); 297 MaxValue = APInt::getMaxValue(BitWidth); 298 } else { 299 MinValue = APInt::getSignedMinValue(BitWidth); 300 MaxValue = APInt::getSignedMaxValue(BitWidth); 301 } 302 // e.g. Returning [-127, 127], represented as [-127, -128). 303 if (!Unsigned && V.isAllOnesValue()) 304 return ConstantRange(-MaxValue, MinValue); 305 306 APInt Lower, Upper; 307 if (!Unsigned && V.isNegative()) { 308 Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP); 309 Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN); 310 } else if (Unsigned) { 311 Lower = APIntOps::RoundingUDiv(MinValue, V, APInt::Rounding::UP); 312 Upper = APIntOps::RoundingUDiv(MaxValue, V, APInt::Rounding::DOWN); 313 } else { 314 Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP); 315 Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN); 316 } 317 // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1). 318 // Upper + 1 is guanranteed not to overflow, because |divisor| > 1. 0, -1, 319 // and 1 are already handled as special cases. 320 return ConstantRange(Lower, Upper + 1); 321 }; 322 323 if (Unsigned) 324 return makeSingleValueRegion(Other.getUnsignedMax()); 325 326 return SubsetIntersect(makeSingleValueRegion(Other.getSignedMin()), 327 makeSingleValueRegion(Other.getSignedMax())); 328 } 329 } 330 } 331 332 bool ConstantRange::isFullSet() const { 333 return Lower == Upper && Lower.isMaxValue(); 334 } 335 336 bool ConstantRange::isEmptySet() const { 337 return Lower == Upper && Lower.isMinValue(); 338 } 339 340 bool ConstantRange::isWrappedSet() const { 341 return Lower.ugt(Upper) && !Upper.isNullValue(); 342 } 343 344 bool ConstantRange::isUpperWrapped() const { 345 return Lower.ugt(Upper); 346 } 347 348 bool ConstantRange::isSignWrappedSet() const { 349 return Lower.sgt(Upper) && !Upper.isMinSignedValue(); 350 } 351 352 bool ConstantRange::isUpperSignWrapped() const { 353 return Lower.sgt(Upper); 354 } 355 356 APInt ConstantRange::getSetSize() const { 357 if (isFullSet()) 358 return APInt::getOneBitSet(getBitWidth()+1, getBitWidth()); 359 360 // This is also correct for wrapped sets. 361 return (Upper - Lower).zext(getBitWidth()+1); 362 } 363 364 bool 365 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const { 366 assert(getBitWidth() == Other.getBitWidth()); 367 if (isFullSet()) 368 return false; 369 if (Other.isFullSet()) 370 return true; 371 return (Upper - Lower).ult(Other.Upper - Other.Lower); 372 } 373 374 bool 375 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const { 376 assert(MaxSize && "MaxSize can't be 0."); 377 // If this a full set, we need special handling to avoid needing an extra bit 378 // to represent the size. 379 if (isFullSet()) 380 return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1); 381 382 return (Upper - Lower).ugt(MaxSize); 383 } 384 385 bool ConstantRange::isAllNegative() const { 386 // Empty set is all negative, full set is not. 387 if (isEmptySet()) 388 return true; 389 if (isFullSet()) 390 return false; 391 392 return !isUpperSignWrapped() && !Upper.isStrictlyPositive(); 393 } 394 395 bool ConstantRange::isAllNonNegative() const { 396 // Empty and full set are automatically treated correctly. 397 return !isSignWrappedSet() && Lower.isNonNegative(); 398 } 399 400 APInt ConstantRange::getUnsignedMax() const { 401 if (isFullSet() || isUpperWrapped()) 402 return APInt::getMaxValue(getBitWidth()); 403 return getUpper() - 1; 404 } 405 406 APInt ConstantRange::getUnsignedMin() const { 407 if (isFullSet() || isWrappedSet()) 408 return APInt::getMinValue(getBitWidth()); 409 return getLower(); 410 } 411 412 APInt ConstantRange::getSignedMax() const { 413 if (isFullSet() || isUpperSignWrapped()) 414 return APInt::getSignedMaxValue(getBitWidth()); 415 return getUpper() - 1; 416 } 417 418 APInt ConstantRange::getSignedMin() const { 419 if (isFullSet() || isSignWrappedSet()) 420 return APInt::getSignedMinValue(getBitWidth()); 421 return getLower(); 422 } 423 424 bool ConstantRange::contains(const APInt &V) const { 425 if (Lower == Upper) 426 return isFullSet(); 427 428 if (!isUpperWrapped()) 429 return Lower.ule(V) && V.ult(Upper); 430 return Lower.ule(V) || V.ult(Upper); 431 } 432 433 bool ConstantRange::contains(const ConstantRange &Other) const { 434 if (isFullSet() || Other.isEmptySet()) return true; 435 if (isEmptySet() || Other.isFullSet()) return false; 436 437 if (!isUpperWrapped()) { 438 if (Other.isUpperWrapped()) 439 return false; 440 441 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper); 442 } 443 444 if (!Other.isUpperWrapped()) 445 return Other.getUpper().ule(Upper) || 446 Lower.ule(Other.getLower()); 447 448 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower()); 449 } 450 451 ConstantRange ConstantRange::subtract(const APInt &Val) const { 452 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width"); 453 // If the set is empty or full, don't modify the endpoints. 454 if (Lower == Upper) 455 return *this; 456 return ConstantRange(Lower - Val, Upper - Val); 457 } 458 459 ConstantRange ConstantRange::difference(const ConstantRange &CR) const { 460 return intersectWith(CR.inverse()); 461 } 462 463 static ConstantRange getPreferredRange( 464 const ConstantRange &CR1, const ConstantRange &CR2, 465 ConstantRange::PreferredRangeType Type) { 466 if (Type == ConstantRange::Unsigned) { 467 if (!CR1.isWrappedSet() && CR2.isWrappedSet()) 468 return CR1; 469 if (CR1.isWrappedSet() && !CR2.isWrappedSet()) 470 return CR2; 471 } else if (Type == ConstantRange::Signed) { 472 if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet()) 473 return CR1; 474 if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet()) 475 return CR2; 476 } 477 478 if (CR1.isSizeStrictlySmallerThan(CR2)) 479 return CR1; 480 return CR2; 481 } 482 483 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR, 484 PreferredRangeType Type) const { 485 assert(getBitWidth() == CR.getBitWidth() && 486 "ConstantRange types don't agree!"); 487 488 // Handle common cases. 489 if ( isEmptySet() || CR.isFullSet()) return *this; 490 if (CR.isEmptySet() || isFullSet()) return CR; 491 492 if (!isUpperWrapped() && CR.isUpperWrapped()) 493 return CR.intersectWith(*this, Type); 494 495 if (!isUpperWrapped() && !CR.isUpperWrapped()) { 496 if (Lower.ult(CR.Lower)) { 497 // L---U : this 498 // L---U : CR 499 if (Upper.ule(CR.Lower)) 500 return getEmpty(); 501 502 // L---U : this 503 // L---U : CR 504 if (Upper.ult(CR.Upper)) 505 return ConstantRange(CR.Lower, Upper); 506 507 // L-------U : this 508 // L---U : CR 509 return CR; 510 } 511 // L---U : this 512 // L-------U : CR 513 if (Upper.ult(CR.Upper)) 514 return *this; 515 516 // L-----U : this 517 // L-----U : CR 518 if (Lower.ult(CR.Upper)) 519 return ConstantRange(Lower, CR.Upper); 520 521 // L---U : this 522 // L---U : CR 523 return getEmpty(); 524 } 525 526 if (isUpperWrapped() && !CR.isUpperWrapped()) { 527 if (CR.Lower.ult(Upper)) { 528 // ------U L--- : this 529 // L--U : CR 530 if (CR.Upper.ult(Upper)) 531 return CR; 532 533 // ------U L--- : this 534 // L------U : CR 535 if (CR.Upper.ule(Lower)) 536 return ConstantRange(CR.Lower, Upper); 537 538 // ------U L--- : this 539 // L----------U : CR 540 return getPreferredRange(*this, CR, Type); 541 } 542 if (CR.Lower.ult(Lower)) { 543 // --U L---- : this 544 // L--U : CR 545 if (CR.Upper.ule(Lower)) 546 return getEmpty(); 547 548 // --U L---- : this 549 // L------U : CR 550 return ConstantRange(Lower, CR.Upper); 551 } 552 553 // --U L------ : this 554 // L--U : CR 555 return CR; 556 } 557 558 if (CR.Upper.ult(Upper)) { 559 // ------U L-- : this 560 // --U L------ : CR 561 if (CR.Lower.ult(Upper)) 562 return getPreferredRange(*this, CR, Type); 563 564 // ----U L-- : this 565 // --U L---- : CR 566 if (CR.Lower.ult(Lower)) 567 return ConstantRange(Lower, CR.Upper); 568 569 // ----U L---- : this 570 // --U L-- : CR 571 return CR; 572 } 573 if (CR.Upper.ule(Lower)) { 574 // --U L-- : this 575 // ----U L---- : CR 576 if (CR.Lower.ult(Lower)) 577 return *this; 578 579 // --U L---- : this 580 // ----U L-- : CR 581 return ConstantRange(CR.Lower, Upper); 582 } 583 584 // --U L------ : this 585 // ------U L-- : CR 586 return getPreferredRange(*this, CR, Type); 587 } 588 589 ConstantRange ConstantRange::unionWith(const ConstantRange &CR, 590 PreferredRangeType Type) const { 591 assert(getBitWidth() == CR.getBitWidth() && 592 "ConstantRange types don't agree!"); 593 594 if ( isFullSet() || CR.isEmptySet()) return *this; 595 if (CR.isFullSet() || isEmptySet()) return CR; 596 597 if (!isUpperWrapped() && CR.isUpperWrapped()) 598 return CR.unionWith(*this, Type); 599 600 if (!isUpperWrapped() && !CR.isUpperWrapped()) { 601 // L---U and L---U : this 602 // L---U L---U : CR 603 // result in one of 604 // L---------U 605 // -----U L----- 606 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) 607 return getPreferredRange( 608 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type); 609 610 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower; 611 APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper; 612 613 if (L.isNullValue() && U.isNullValue()) 614 return getFull(); 615 616 return ConstantRange(std::move(L), std::move(U)); 617 } 618 619 if (!CR.isUpperWrapped()) { 620 // ------U L----- and ------U L----- : this 621 // L--U L--U : CR 622 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower)) 623 return *this; 624 625 // ------U L----- : this 626 // L---------U : CR 627 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper)) 628 return getFull(); 629 630 // ----U L---- : this 631 // L---U : CR 632 // results in one of 633 // ----------U L---- 634 // ----U L---------- 635 if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower)) 636 return getPreferredRange( 637 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type); 638 639 // ----U L----- : this 640 // L----U : CR 641 if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper)) 642 return ConstantRange(CR.Lower, Upper); 643 644 // ------U L---- : this 645 // L-----U : CR 646 assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) && 647 "ConstantRange::unionWith missed a case with one range wrapped"); 648 return ConstantRange(Lower, CR.Upper); 649 } 650 651 // ------U L---- and ------U L---- : this 652 // -U L----------- and ------------U L : CR 653 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper)) 654 return getFull(); 655 656 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower; 657 APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper; 658 659 return ConstantRange(std::move(L), std::move(U)); 660 } 661 662 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp, 663 uint32_t ResultBitWidth) const { 664 switch (CastOp) { 665 default: 666 llvm_unreachable("unsupported cast type"); 667 case Instruction::Trunc: 668 return truncate(ResultBitWidth); 669 case Instruction::SExt: 670 return signExtend(ResultBitWidth); 671 case Instruction::ZExt: 672 return zeroExtend(ResultBitWidth); 673 case Instruction::BitCast: 674 return *this; 675 case Instruction::FPToUI: 676 case Instruction::FPToSI: 677 if (getBitWidth() == ResultBitWidth) 678 return *this; 679 else 680 return getFull(); 681 case Instruction::UIToFP: { 682 // TODO: use input range if available 683 auto BW = getBitWidth(); 684 APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth); 685 APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth); 686 return ConstantRange(std::move(Min), std::move(Max)); 687 } 688 case Instruction::SIToFP: { 689 // TODO: use input range if available 690 auto BW = getBitWidth(); 691 APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth); 692 APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth); 693 return ConstantRange(std::move(SMin), std::move(SMax)); 694 } 695 case Instruction::FPTrunc: 696 case Instruction::FPExt: 697 case Instruction::IntToPtr: 698 case Instruction::PtrToInt: 699 case Instruction::AddrSpaceCast: 700 // Conservatively return getFull set. 701 return getFull(); 702 }; 703 } 704 705 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const { 706 if (isEmptySet()) return getEmpty(DstTySize); 707 708 unsigned SrcTySize = getBitWidth(); 709 assert(SrcTySize < DstTySize && "Not a value extension"); 710 if (isFullSet() || isUpperWrapped()) { 711 // Change into [0, 1 << src bit width) 712 APInt LowerExt(DstTySize, 0); 713 if (!Upper) // special case: [X, 0) -- not really wrapping around 714 LowerExt = Lower.zext(DstTySize); 715 return ConstantRange(std::move(LowerExt), 716 APInt::getOneBitSet(DstTySize, SrcTySize)); 717 } 718 719 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize)); 720 } 721 722 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const { 723 if (isEmptySet()) return getEmpty(DstTySize); 724 725 unsigned SrcTySize = getBitWidth(); 726 assert(SrcTySize < DstTySize && "Not a value extension"); 727 728 // special case: [X, INT_MIN) -- not really wrapping around 729 if (Upper.isMinSignedValue()) 730 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize)); 731 732 if (isFullSet() || isSignWrappedSet()) { 733 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1), 734 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1); 735 } 736 737 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize)); 738 } 739 740 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const { 741 assert(getBitWidth() > DstTySize && "Not a value truncation"); 742 if (isEmptySet()) 743 return getEmpty(DstTySize); 744 if (isFullSet()) 745 return getFull(DstTySize); 746 747 APInt LowerDiv(Lower), UpperDiv(Upper); 748 ConstantRange Union(DstTySize, /*isFullSet=*/false); 749 750 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue] 751 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and 752 // then we do the union with [MaxValue, Upper) 753 if (isUpperWrapped()) { 754 // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole 755 // truncated range. 756 if (Upper.getActiveBits() > DstTySize || 757 Upper.countTrailingOnes() == DstTySize) 758 return getFull(DstTySize); 759 760 Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize)); 761 UpperDiv.setAllBits(); 762 763 // Union covers the MaxValue case, so return if the remaining range is just 764 // MaxValue(DstTy). 765 if (LowerDiv == UpperDiv) 766 return Union; 767 } 768 769 // Chop off the most significant bits that are past the destination bitwidth. 770 if (LowerDiv.getActiveBits() > DstTySize) { 771 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv. 772 APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize); 773 LowerDiv -= Adjust; 774 UpperDiv -= Adjust; 775 } 776 777 unsigned UpperDivWidth = UpperDiv.getActiveBits(); 778 if (UpperDivWidth <= DstTySize) 779 return ConstantRange(LowerDiv.trunc(DstTySize), 780 UpperDiv.trunc(DstTySize)).unionWith(Union); 781 782 // The truncated value wraps around. Check if we can do better than fullset. 783 if (UpperDivWidth == DstTySize + 1) { 784 // Clear the MSB so that UpperDiv wraps around. 785 UpperDiv.clearBit(DstTySize); 786 if (UpperDiv.ult(LowerDiv)) 787 return ConstantRange(LowerDiv.trunc(DstTySize), 788 UpperDiv.trunc(DstTySize)).unionWith(Union); 789 } 790 791 return getFull(DstTySize); 792 } 793 794 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const { 795 unsigned SrcTySize = getBitWidth(); 796 if (SrcTySize > DstTySize) 797 return truncate(DstTySize); 798 if (SrcTySize < DstTySize) 799 return zeroExtend(DstTySize); 800 return *this; 801 } 802 803 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const { 804 unsigned SrcTySize = getBitWidth(); 805 if (SrcTySize > DstTySize) 806 return truncate(DstTySize); 807 if (SrcTySize < DstTySize) 808 return signExtend(DstTySize); 809 return *this; 810 } 811 812 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp, 813 const ConstantRange &Other) const { 814 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!"); 815 816 switch (BinOp) { 817 case Instruction::Add: 818 return add(Other); 819 case Instruction::Sub: 820 return sub(Other); 821 case Instruction::Mul: 822 return multiply(Other); 823 case Instruction::UDiv: 824 return udiv(Other); 825 case Instruction::Shl: 826 return shl(Other); 827 case Instruction::LShr: 828 return lshr(Other); 829 case Instruction::AShr: 830 return ashr(Other); 831 case Instruction::And: 832 return binaryAnd(Other); 833 case Instruction::Or: 834 return binaryOr(Other); 835 // Note: floating point operations applied to abstract ranges are just 836 // ideal integer operations with a lossy representation 837 case Instruction::FAdd: 838 return add(Other); 839 case Instruction::FSub: 840 return sub(Other); 841 case Instruction::FMul: 842 return multiply(Other); 843 default: 844 // Conservatively return getFull set. 845 return getFull(); 846 } 847 } 848 849 ConstantRange 850 ConstantRange::add(const ConstantRange &Other) const { 851 if (isEmptySet() || Other.isEmptySet()) 852 return getEmpty(); 853 if (isFullSet() || Other.isFullSet()) 854 return getFull(); 855 856 APInt NewLower = getLower() + Other.getLower(); 857 APInt NewUpper = getUpper() + Other.getUpper() - 1; 858 if (NewLower == NewUpper) 859 return getFull(); 860 861 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper)); 862 if (X.isSizeStrictlySmallerThan(*this) || 863 X.isSizeStrictlySmallerThan(Other)) 864 // We've wrapped, therefore, full set. 865 return getFull(); 866 return X; 867 } 868 869 ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const { 870 // Calculate the subset of this range such that "X + Other" is 871 // guaranteed not to wrap (overflow) for all X in this subset. 872 // makeGuaranteedNoWrapRegion will produce an exact NSW range since we are 873 // passing a single element range. 874 auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(BinaryOperator::Add, 875 ConstantRange(Other), 876 OverflowingBinaryOperator::NoSignedWrap); 877 auto NSWConstrainedRange = intersectWith(NSWRange); 878 879 return NSWConstrainedRange.add(ConstantRange(Other)); 880 } 881 882 ConstantRange 883 ConstantRange::sub(const ConstantRange &Other) const { 884 if (isEmptySet() || Other.isEmptySet()) 885 return getEmpty(); 886 if (isFullSet() || Other.isFullSet()) 887 return getFull(); 888 889 APInt NewLower = getLower() - Other.getUpper() + 1; 890 APInt NewUpper = getUpper() - Other.getLower(); 891 if (NewLower == NewUpper) 892 return getFull(); 893 894 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper)); 895 if (X.isSizeStrictlySmallerThan(*this) || 896 X.isSizeStrictlySmallerThan(Other)) 897 // We've wrapped, therefore, full set. 898 return getFull(); 899 return X; 900 } 901 902 ConstantRange 903 ConstantRange::multiply(const ConstantRange &Other) const { 904 // TODO: If either operand is a single element and the multiply is known to 905 // be non-wrapping, round the result min and max value to the appropriate 906 // multiple of that element. If wrapping is possible, at least adjust the 907 // range according to the greatest power-of-two factor of the single element. 908 909 if (isEmptySet() || Other.isEmptySet()) 910 return getEmpty(); 911 912 // Multiplication is signedness-independent. However different ranges can be 913 // obtained depending on how the input ranges are treated. These different 914 // ranges are all conservatively correct, but one might be better than the 915 // other. We calculate two ranges; one treating the inputs as unsigned 916 // and the other signed, then return the smallest of these ranges. 917 918 // Unsigned range first. 919 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2); 920 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2); 921 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2); 922 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2); 923 924 ConstantRange Result_zext = ConstantRange(this_min * Other_min, 925 this_max * Other_max + 1); 926 ConstantRange UR = Result_zext.truncate(getBitWidth()); 927 928 // If the unsigned range doesn't wrap, and isn't negative then it's a range 929 // from one positive number to another which is as good as we can generate. 930 // In this case, skip the extra work of generating signed ranges which aren't 931 // going to be better than this range. 932 if (!UR.isUpperWrapped() && 933 (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue())) 934 return UR; 935 936 // Now the signed range. Because we could be dealing with negative numbers 937 // here, the lower bound is the smallest of the cartesian product of the 938 // lower and upper ranges; for example: 939 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6. 940 // Similarly for the upper bound, swapping min for max. 941 942 this_min = getSignedMin().sext(getBitWidth() * 2); 943 this_max = getSignedMax().sext(getBitWidth() * 2); 944 Other_min = Other.getSignedMin().sext(getBitWidth() * 2); 945 Other_max = Other.getSignedMax().sext(getBitWidth() * 2); 946 947 auto L = {this_min * Other_min, this_min * Other_max, 948 this_max * Other_min, this_max * Other_max}; 949 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); }; 950 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1); 951 ConstantRange SR = Result_sext.truncate(getBitWidth()); 952 953 return UR.isSizeStrictlySmallerThan(SR) ? UR : SR; 954 } 955 956 ConstantRange 957 ConstantRange::smax(const ConstantRange &Other) const { 958 // X smax Y is: range(smax(X_smin, Y_smin), 959 // smax(X_smax, Y_smax)) 960 if (isEmptySet() || Other.isEmptySet()) 961 return getEmpty(); 962 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin()); 963 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1; 964 if (NewU == NewL) 965 return getFull(); 966 return ConstantRange(std::move(NewL), std::move(NewU)); 967 } 968 969 ConstantRange 970 ConstantRange::umax(const ConstantRange &Other) const { 971 // X umax Y is: range(umax(X_umin, Y_umin), 972 // umax(X_umax, Y_umax)) 973 if (isEmptySet() || Other.isEmptySet()) 974 return getEmpty(); 975 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()); 976 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1; 977 if (NewU == NewL) 978 return getFull(); 979 return ConstantRange(std::move(NewL), std::move(NewU)); 980 } 981 982 ConstantRange 983 ConstantRange::smin(const ConstantRange &Other) const { 984 // X smin Y is: range(smin(X_smin, Y_smin), 985 // smin(X_smax, Y_smax)) 986 if (isEmptySet() || Other.isEmptySet()) 987 return getEmpty(); 988 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin()); 989 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1; 990 if (NewU == NewL) 991 return getFull(); 992 return ConstantRange(std::move(NewL), std::move(NewU)); 993 } 994 995 ConstantRange 996 ConstantRange::umin(const ConstantRange &Other) const { 997 // X umin Y is: range(umin(X_umin, Y_umin), 998 // umin(X_umax, Y_umax)) 999 if (isEmptySet() || Other.isEmptySet()) 1000 return getEmpty(); 1001 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin()); 1002 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1; 1003 if (NewU == NewL) 1004 return getFull(); 1005 return ConstantRange(std::move(NewL), std::move(NewU)); 1006 } 1007 1008 ConstantRange 1009 ConstantRange::udiv(const ConstantRange &RHS) const { 1010 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue()) 1011 return getEmpty(); 1012 if (RHS.isFullSet()) 1013 return getFull(); 1014 1015 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax()); 1016 1017 APInt RHS_umin = RHS.getUnsignedMin(); 1018 if (RHS_umin.isNullValue()) { 1019 // We want the lowest value in RHS excluding zero. Usually that would be 1 1020 // except for a range in the form of [X, 1) in which case it would be X. 1021 if (RHS.getUpper() == 1) 1022 RHS_umin = RHS.getLower(); 1023 else 1024 RHS_umin = 1; 1025 } 1026 1027 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1; 1028 1029 // If the LHS is Full and the RHS is a wrapped interval containing 1 then 1030 // this could occur. 1031 if (Lower == Upper) 1032 return getFull(); 1033 1034 return ConstantRange(std::move(Lower), std::move(Upper)); 1035 } 1036 1037 ConstantRange 1038 ConstantRange::binaryAnd(const ConstantRange &Other) const { 1039 if (isEmptySet() || Other.isEmptySet()) 1040 return getEmpty(); 1041 1042 // TODO: replace this with something less conservative 1043 1044 APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax()); 1045 if (umin.isAllOnesValue()) 1046 return getFull(); 1047 return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(umin) + 1); 1048 } 1049 1050 ConstantRange 1051 ConstantRange::binaryOr(const ConstantRange &Other) const { 1052 if (isEmptySet() || Other.isEmptySet()) 1053 return getEmpty(); 1054 1055 // TODO: replace this with something less conservative 1056 1057 APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()); 1058 if (umax.isNullValue()) 1059 return getFull(); 1060 return ConstantRange(std::move(umax), APInt::getNullValue(getBitWidth())); 1061 } 1062 1063 ConstantRange 1064 ConstantRange::shl(const ConstantRange &Other) const { 1065 if (isEmptySet() || Other.isEmptySet()) 1066 return getEmpty(); 1067 1068 APInt max = getUnsignedMax(); 1069 APInt Other_umax = Other.getUnsignedMax(); 1070 1071 // If we are shifting by maximum amount of 1072 // zero return return the original range. 1073 if (Other_umax.isNullValue()) 1074 return *this; 1075 // there's overflow! 1076 if (Other_umax.ugt(max.countLeadingZeros())) 1077 return getFull(); 1078 1079 // FIXME: implement the other tricky cases 1080 1081 APInt min = getUnsignedMin(); 1082 min <<= Other.getUnsignedMin(); 1083 max <<= Other_umax; 1084 1085 return ConstantRange(std::move(min), std::move(max) + 1); 1086 } 1087 1088 ConstantRange 1089 ConstantRange::lshr(const ConstantRange &Other) const { 1090 if (isEmptySet() || Other.isEmptySet()) 1091 return getEmpty(); 1092 1093 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1; 1094 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax()); 1095 if (min == max) 1096 return getFull(); 1097 1098 return ConstantRange(std::move(min), std::move(max)); 1099 } 1100 1101 ConstantRange 1102 ConstantRange::ashr(const ConstantRange &Other) const { 1103 if (isEmptySet() || Other.isEmptySet()) 1104 return getEmpty(); 1105 1106 // May straddle zero, so handle both positive and negative cases. 1107 // 'PosMax' is the upper bound of the result of the ashr 1108 // operation, when Upper of the LHS of ashr is a non-negative. 1109 // number. Since ashr of a non-negative number will result in a 1110 // smaller number, the Upper value of LHS is shifted right with 1111 // the minimum value of 'Other' instead of the maximum value. 1112 APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1; 1113 1114 // 'PosMin' is the lower bound of the result of the ashr 1115 // operation, when Lower of the LHS is a non-negative number. 1116 // Since ashr of a non-negative number will result in a smaller 1117 // number, the Lower value of LHS is shifted right with the 1118 // maximum value of 'Other'. 1119 APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax()); 1120 1121 // 'NegMax' is the upper bound of the result of the ashr 1122 // operation, when Upper of the LHS of ashr is a negative number. 1123 // Since 'ashr' of a negative number will result in a bigger 1124 // number, the Upper value of LHS is shifted right with the 1125 // maximum value of 'Other'. 1126 APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1; 1127 1128 // 'NegMin' is the lower bound of the result of the ashr 1129 // operation, when Lower of the LHS of ashr is a negative number. 1130 // Since 'ashr' of a negative number will result in a bigger 1131 // number, the Lower value of LHS is shifted right with the 1132 // minimum value of 'Other'. 1133 APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin()); 1134 1135 APInt max, min; 1136 if (getSignedMin().isNonNegative()) { 1137 // Upper and Lower of LHS are non-negative. 1138 min = PosMin; 1139 max = PosMax; 1140 } else if (getSignedMax().isNegative()) { 1141 // Upper and Lower of LHS are negative. 1142 min = NegMin; 1143 max = NegMax; 1144 } else { 1145 // Upper is non-negative and Lower is negative. 1146 min = NegMin; 1147 max = PosMax; 1148 } 1149 if (min == max) 1150 return getFull(); 1151 1152 return ConstantRange(std::move(min), std::move(max)); 1153 } 1154 1155 ConstantRange ConstantRange::inverse() const { 1156 if (isFullSet()) 1157 return getEmpty(); 1158 if (isEmptySet()) 1159 return getFull(); 1160 return ConstantRange(Upper, Lower); 1161 } 1162 1163 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow( 1164 const ConstantRange &Other) const { 1165 if (isEmptySet() || Other.isEmptySet()) 1166 return OverflowResult::MayOverflow; 1167 1168 APInt Min = getUnsignedMin(), Max = getUnsignedMax(); 1169 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax(); 1170 1171 // a u+ b overflows iff a u> ~b. 1172 if (Min.ugt(~OtherMin)) 1173 return OverflowResult::AlwaysOverflows; 1174 if (Max.ugt(~OtherMax)) 1175 return OverflowResult::MayOverflow; 1176 return OverflowResult::NeverOverflows; 1177 } 1178 1179 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow( 1180 const ConstantRange &Other) const { 1181 if (isEmptySet() || Other.isEmptySet()) 1182 return OverflowResult::MayOverflow; 1183 1184 APInt Min = getSignedMin(), Max = getSignedMax(); 1185 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax(); 1186 1187 APInt SignedMin = APInt::getSignedMinValue(getBitWidth()); 1188 APInt SignedMax = APInt::getSignedMaxValue(getBitWidth()); 1189 1190 // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b. 1191 // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b. 1192 if (Min.isNonNegative() && OtherMin.isNonNegative() && 1193 Min.sgt(SignedMax - OtherMin)) 1194 return OverflowResult::AlwaysOverflows; 1195 if (Max.isNegative() && OtherMax.isNegative() && 1196 Max.slt(SignedMin - OtherMax)) 1197 return OverflowResult::AlwaysOverflows; 1198 1199 if (Max.isNonNegative() && OtherMax.isNonNegative() && 1200 Max.sgt(SignedMax - OtherMax)) 1201 return OverflowResult::MayOverflow; 1202 if (Min.isNegative() && OtherMin.isNegative() && 1203 Min.slt(SignedMin - OtherMin)) 1204 return OverflowResult::MayOverflow; 1205 1206 return OverflowResult::NeverOverflows; 1207 } 1208 1209 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow( 1210 const ConstantRange &Other) const { 1211 if (isEmptySet() || Other.isEmptySet()) 1212 return OverflowResult::MayOverflow; 1213 1214 APInt Min = getUnsignedMin(), Max = getUnsignedMax(); 1215 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax(); 1216 1217 // a u- b overflows iff a u< b. 1218 if (Max.ult(OtherMin)) 1219 return OverflowResult::AlwaysOverflows; 1220 if (Min.ult(OtherMax)) 1221 return OverflowResult::MayOverflow; 1222 return OverflowResult::NeverOverflows; 1223 } 1224 1225 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow( 1226 const ConstantRange &Other) const { 1227 if (isEmptySet() || Other.isEmptySet()) 1228 return OverflowResult::MayOverflow; 1229 1230 APInt Min = getSignedMin(), Max = getSignedMax(); 1231 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax(); 1232 1233 APInt SignedMin = APInt::getSignedMinValue(getBitWidth()); 1234 APInt SignedMax = APInt::getSignedMaxValue(getBitWidth()); 1235 1236 // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b. 1237 // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b. 1238 if (Min.isNonNegative() && OtherMax.isNegative() && 1239 Min.sgt(SignedMax + OtherMax)) 1240 return OverflowResult::AlwaysOverflows; 1241 if (Max.isNegative() && OtherMin.isNonNegative() && 1242 Max.slt(SignedMin + OtherMin)) 1243 return OverflowResult::AlwaysOverflows; 1244 1245 if (Max.isNonNegative() && OtherMin.isNegative() && 1246 Max.sgt(SignedMax + OtherMin)) 1247 return OverflowResult::MayOverflow; 1248 if (Min.isNegative() && OtherMax.isNonNegative() && 1249 Min.slt(SignedMin + OtherMax)) 1250 return OverflowResult::MayOverflow; 1251 1252 return OverflowResult::NeverOverflows; 1253 } 1254 1255 void ConstantRange::print(raw_ostream &OS) const { 1256 if (isFullSet()) 1257 OS << "full-set"; 1258 else if (isEmptySet()) 1259 OS << "empty-set"; 1260 else 1261 OS << "[" << Lower << "," << Upper << ")"; 1262 } 1263 1264 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1265 LLVM_DUMP_METHOD void ConstantRange::dump() const { 1266 print(dbgs()); 1267 } 1268 #endif 1269 1270 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) { 1271 const unsigned NumRanges = Ranges.getNumOperands() / 2; 1272 assert(NumRanges >= 1 && "Must have at least one range!"); 1273 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs"); 1274 1275 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0)); 1276 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1)); 1277 1278 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue()); 1279 1280 for (unsigned i = 1; i < NumRanges; ++i) { 1281 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0)); 1282 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1)); 1283 1284 // Note: unionWith will potentially create a range that contains values not 1285 // contained in any of the original N ranges. 1286 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue())); 1287 } 1288 1289 return CR; 1290 } 1291