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