LLVM 22.0.0git
ConstantRange.cpp
Go to the documentation of this file.
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
24#include "llvm/ADT/APInt.h"
25#include "llvm/Config/llvm-config.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Operator.h"
34#include "llvm/Support/Debug.h"
38#include <algorithm>
39#include <cassert>
40#include <cstdint>
41#include <optional>
42
43using namespace llvm;
44
46 : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
47 Upper(Lower) {}
48
50 : Lower(std::move(V)), Upper(Lower + 1) {}
51
53 : Lower(std::move(L)), Upper(std::move(U)) {
54 assert(Lower.getBitWidth() == Upper.getBitWidth() &&
55 "ConstantRange with unequal bit widths");
56 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
57 "Lower == Upper, but they aren't min or max value!");
58}
59
61 bool IsSigned) {
62 if (Known.hasConflict())
63 return getEmpty(Known.getBitWidth());
64 if (Known.isUnknown())
65 return getFull(Known.getBitWidth());
66
67 // For unsigned ranges, or signed ranges with known sign bit, create a simple
68 // range between the smallest and largest possible value.
69 if (!IsSigned || Known.isNegative() || Known.isNonNegative())
70 return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);
71
72 // If we don't know the sign bit, pick the lower bound as a negative number
73 // and the upper bound as a non-negative one.
74 APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();
75 Lower.setSignBit();
76 Upper.clearSignBit();
77 return ConstantRange(Lower, Upper + 1);
78}
79
81 // TODO: We could return conflicting known bits here, but consumers are
82 // likely not prepared for that.
83 if (isEmptySet())
84 return KnownBits(getBitWidth());
85
86 // We can only retain the top bits that are the same between min and max.
87 APInt Min = getUnsignedMin();
88 APInt Max = getUnsignedMax();
90 if (std::optional<unsigned> DifferentBit =
92 Known.Zero.clearLowBits(*DifferentBit + 1);
93 Known.One.clearLowBits(*DifferentBit + 1);
94 }
95 return Known;
96}
97
98std::pair<ConstantRange, ConstantRange> ConstantRange::splitPosNeg() const {
99 uint32_t BW = getBitWidth();
100 APInt Zero = APInt::getZero(BW), One = APInt(BW, 1);
101 APInt SignedMin = APInt::getSignedMinValue(BW);
102 // There are no positive 1-bit values. The 1 would get interpreted as -1.
103 ConstantRange PosFilter =
104 BW == 1 ? getEmpty() : ConstantRange(One, SignedMin);
105 ConstantRange NegFilter(SignedMin, Zero);
106 return {intersectWith(PosFilter), intersectWith(NegFilter)};
107}
108
110 const ConstantRange &CR) {
111 if (CR.isEmptySet())
112 return CR;
113
114 uint32_t W = CR.getBitWidth();
115 switch (Pred) {
116 default:
117 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
118 case CmpInst::ICMP_EQ:
119 return CR;
120 case CmpInst::ICMP_NE:
121 if (CR.isSingleElement())
122 return ConstantRange(CR.getUpper(), CR.getLower());
123 return getFull(W);
124 case CmpInst::ICMP_ULT: {
126 if (UMax.isMinValue())
127 return getEmpty(W);
128 return ConstantRange(APInt::getMinValue(W), std::move(UMax));
129 }
130 case CmpInst::ICMP_SLT: {
131 APInt SMax(CR.getSignedMax());
132 if (SMax.isMinSignedValue())
133 return getEmpty(W);
134 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
135 }
137 return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
140 case CmpInst::ICMP_UGT: {
142 if (UMin.isMaxValue())
143 return getEmpty(W);
144 return ConstantRange(std::move(UMin) + 1, APInt::getZero(W));
145 }
146 case CmpInst::ICMP_SGT: {
147 APInt SMin(CR.getSignedMin());
148 if (SMin.isMaxSignedValue())
149 return getEmpty(W);
150 return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
151 }
156 }
157}
158
160 const ConstantRange &CR) {
161 // Follows from De-Morgan's laws:
162 //
163 // ~(~A union ~B) == A intersect B.
164 //
166 .inverse();
167}
168
170 const APInt &C) {
171 // Computes the exact range that is equal to both the constant ranges returned
172 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
173 // when RHS is a singleton such as an APInt. However for non-singleton RHS,
174 // for example ult [2,5) makeAllowedICmpRegion returns [0,4) but
175 // makeSatisfyICmpRegion returns [0,2).
176 //
177 return makeAllowedICmpRegion(Pred, C);
178}
179
181 const ConstantRange &CR1, const ConstantRange &CR2) {
182 if (CR1.isEmptySet() || CR2.isEmptySet())
183 return true;
184
185 return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) ||
186 (CR1.isAllNegative() && CR2.isAllNegative());
187}
188
190 const ConstantRange &CR1, const ConstantRange &CR2) {
191 if (CR1.isEmptySet() || CR2.isEmptySet())
192 return true;
193
194 return (CR1.isAllNonNegative() && CR2.isAllNegative()) ||
195 (CR1.isAllNegative() && CR2.isAllNonNegative());
196}
197
199 CmpInst::Predicate Pred, const ConstantRange &CR1,
200 const ConstantRange &CR2) {
202 "Only for relational integer predicates!");
203
204 CmpInst::Predicate FlippedSignednessPred =
206
208 return FlippedSignednessPred;
209
211 return CmpInst::getInversePredicate(FlippedSignednessPred);
212
214}
215
217 APInt &RHS, APInt &Offset) const {
218 Offset = APInt(getBitWidth(), 0);
219 if (isFullSet() || isEmptySet()) {
221 RHS = APInt(getBitWidth(), 0);
222 } else if (auto *OnlyElt = getSingleElement()) {
223 Pred = CmpInst::ICMP_EQ;
224 RHS = *OnlyElt;
225 } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
226 Pred = CmpInst::ICMP_NE;
227 RHS = *OnlyMissingElt;
228 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
229 Pred =
231 RHS = getUpper();
232 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
233 Pred =
235 RHS = getLower();
236 } else {
237 Pred = CmpInst::ICMP_ULT;
238 RHS = getUpper() - getLower();
239 Offset = -getLower();
240 }
241
243 "Bad result!");
244}
245
247 APInt &RHS) const {
250 return Offset.isZero();
251}
252
254 const ConstantRange &Other) const {
255 if (isEmptySet() || Other.isEmptySet())
256 return true;
257
258 switch (Pred) {
259 case CmpInst::ICMP_EQ:
260 if (const APInt *L = getSingleElement())
261 if (const APInt *R = Other.getSingleElement())
262 return *L == *R;
263 return false;
264 case CmpInst::ICMP_NE:
265 return inverse().contains(Other);
267 return getUnsignedMax().ult(Other.getUnsignedMin());
269 return getUnsignedMax().ule(Other.getUnsignedMin());
271 return getUnsignedMin().ugt(Other.getUnsignedMax());
273 return getUnsignedMin().uge(Other.getUnsignedMax());
275 return getSignedMax().slt(Other.getSignedMin());
277 return getSignedMax().sle(Other.getSignedMin());
279 return getSignedMin().sgt(Other.getSignedMax());
281 return getSignedMin().sge(Other.getSignedMax());
282 default:
283 llvm_unreachable("Invalid ICmp predicate");
284 }
285}
286
287/// Exact mul nuw region for single element RHS.
289 unsigned BitWidth = V.getBitWidth();
290 if (V == 0)
291 return ConstantRange::getFull(V.getBitWidth());
292
298}
299
300/// Exact mul nsw region for single element RHS.
302 // Handle 0 and -1 separately to avoid division by zero or overflow.
303 unsigned BitWidth = V.getBitWidth();
304 if (V == 0)
305 return ConstantRange::getFull(BitWidth);
306
309 // e.g. Returning [-127, 127], represented as [-127, -128).
310 if (V.isAllOnes())
311 return ConstantRange(-MaxValue, MinValue);
312
314 if (V.isNegative()) {
317 } else {
320 }
322}
323
326 const ConstantRange &Other,
327 unsigned NoWrapKind) {
328 using OBO = OverflowingBinaryOperator;
329
330 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
331
332 assert((NoWrapKind == OBO::NoSignedWrap ||
333 NoWrapKind == OBO::NoUnsignedWrap) &&
334 "NoWrapKind invalid!");
335
336 bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
337 unsigned BitWidth = Other.getBitWidth();
338
339 switch (BinOp) {
340 default:
341 llvm_unreachable("Unsupported binary op");
342
343 case Instruction::Add: {
344 if (Unsigned)
345 return getNonEmpty(APInt::getZero(BitWidth), -Other.getUnsignedMax());
346
348 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
349 return getNonEmpty(
350 SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
351 SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
352 }
353
354 case Instruction::Sub: {
355 if (Unsigned)
356 return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
357
359 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
360 return getNonEmpty(
361 SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
362 SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
363 }
364
365 case Instruction::Mul:
366 if (Unsigned)
367 return makeExactMulNUWRegion(Other.getUnsignedMax());
368
369 // Avoid one makeExactMulNSWRegion() call for the common case of constants.
370 if (const APInt *C = Other.getSingleElement())
371 return makeExactMulNSWRegion(*C);
372
373 return makeExactMulNSWRegion(Other.getSignedMin())
374 .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
375
376 case Instruction::Shl: {
377 // For given range of shift amounts, if we ignore all illegal shift amounts
378 // (that always produce poison), what shift amount range is left?
379 ConstantRange ShAmt = Other.intersectWith(
381 if (ShAmt.isEmptySet()) {
382 // If the entire range of shift amounts is already poison-producing,
383 // then we can freely add more poison-producing flags ontop of that.
384 return getFull(BitWidth);
385 }
386 // There are some legal shift amounts, we can compute conservatively-correct
387 // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax
388 // to be at most bitwidth-1, which results in most conservative range.
389 APInt ShAmtUMax = ShAmt.getUnsignedMax();
390 if (Unsigned)
392 APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);
394 APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);
395 }
396 }
397}
398
400 const APInt &Other,
401 unsigned NoWrapKind) {
402 // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
403 // "for all" and "for any" coincide in this case.
404 return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
405}
406
408 const APInt &C) {
409 unsigned BitWidth = Mask.getBitWidth();
410
411 if ((Mask & C) != C)
412 return getFull(BitWidth);
413
414 if (Mask.isZero())
415 return getEmpty(BitWidth);
416
417 // If (Val & Mask) != C, constrained to the non-equality being
418 // satisfiable, then the value must be larger than the lowest set bit of
419 // Mask, offset by constant C.
421 APInt::getOneBitSet(BitWidth, Mask.countr_zero()) + C, C);
422}
423
425 return Lower == Upper && Lower.isMaxValue();
426}
427
429 return Lower == Upper && Lower.isMinValue();
430}
431
433 return Lower.ugt(Upper) && !Upper.isZero();
434}
435
437 return Lower.ugt(Upper);
438}
439
441 return Lower.sgt(Upper) && !Upper.isMinSignedValue();
442}
443
445 return Lower.sgt(Upper);
446}
447
448bool
450 assert(getBitWidth() == Other.getBitWidth());
451 if (isFullSet())
452 return false;
453 if (Other.isFullSet())
454 return true;
455 return (Upper - Lower).ult(Other.Upper - Other.Lower);
456}
457
458bool
460 // If this a full set, we need special handling to avoid needing an extra bit
461 // to represent the size.
462 if (isFullSet())
463 return MaxSize == 0 || APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
464
465 return (Upper - Lower).ugt(MaxSize);
466}
467
469 // Empty set is all negative, full set is not.
470 if (isEmptySet())
471 return true;
472 if (isFullSet())
473 return false;
474
475 return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
476}
477
479 // Empty and full set are automatically treated correctly.
480 return !isSignWrappedSet() && Lower.isNonNegative();
481}
482
484 // Empty set is all positive, full set is not.
485 if (isEmptySet())
486 return true;
487 if (isFullSet())
488 return false;
489
490 return !isSignWrappedSet() && Lower.isStrictlyPositive();
491}
492
494 if (isFullSet() || isUpperWrapped())
496 return getUpper() - 1;
497}
498
500 if (isFullSet() || isWrappedSet())
502 return getLower();
503}
504
506 if (isFullSet() || isUpperSignWrapped())
508 return getUpper() - 1;
509}
510
512 if (isFullSet() || isSignWrappedSet())
514 return getLower();
515}
516
517bool ConstantRange::contains(const APInt &V) const {
518 if (Lower == Upper)
519 return isFullSet();
520
521 if (!isUpperWrapped())
522 return Lower.ule(V) && V.ult(Upper);
523 return Lower.ule(V) || V.ult(Upper);
524}
525
527 if (isFullSet() || Other.isEmptySet()) return true;
528 if (isEmptySet() || Other.isFullSet()) return false;
529
530 if (!isUpperWrapped()) {
531 if (Other.isUpperWrapped())
532 return false;
533
534 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
535 }
536
537 if (!Other.isUpperWrapped())
538 return Other.getUpper().ule(Upper) ||
539 Lower.ule(Other.getLower());
540
541 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
542}
543
545 if (isEmptySet())
546 return 0;
547
548 return getUnsignedMax().getActiveBits();
549}
550
552 if (isEmptySet())
553 return 0;
554
555 return std::max(getSignedMin().getSignificantBits(),
556 getSignedMax().getSignificantBits());
557}
558
560 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
561 // If the set is empty or full, don't modify the endpoints.
562 if (Lower == Upper)
563 return *this;
564 return ConstantRange(Lower - Val, Upper - Val);
565}
566
568 return intersectWith(CR.inverse());
569}
570
572 const ConstantRange &CR1, const ConstantRange &CR2,
575 if (!CR1.isWrappedSet() && CR2.isWrappedSet())
576 return CR1;
577 if (CR1.isWrappedSet() && !CR2.isWrappedSet())
578 return CR2;
579 } else if (Type == ConstantRange::Signed) {
580 if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
581 return CR1;
582 if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
583 return CR2;
584 }
585
586 if (CR1.isSizeStrictlySmallerThan(CR2))
587 return CR1;
588 return CR2;
589}
590
592 PreferredRangeType Type) const {
593 assert(getBitWidth() == CR.getBitWidth() &&
594 "ConstantRange types don't agree!");
595
596 // Handle common cases.
597 if ( isEmptySet() || CR.isFullSet()) return *this;
598 if (CR.isEmptySet() || isFullSet()) return CR;
599
600 if (!isUpperWrapped() && CR.isUpperWrapped())
601 return CR.intersectWith(*this, Type);
602
603 if (!isUpperWrapped() && !CR.isUpperWrapped()) {
604 if (Lower.ult(CR.Lower)) {
605 // L---U : this
606 // L---U : CR
607 if (Upper.ule(CR.Lower))
608 return getEmpty();
609
610 // L---U : this
611 // L---U : CR
612 if (Upper.ult(CR.Upper))
613 return ConstantRange(CR.Lower, Upper);
614
615 // L-------U : this
616 // L---U : CR
617 return CR;
618 }
619 // L---U : this
620 // L-------U : CR
621 if (Upper.ult(CR.Upper))
622 return *this;
623
624 // L-----U : this
625 // L-----U : CR
626 if (Lower.ult(CR.Upper))
627 return ConstantRange(Lower, CR.Upper);
628
629 // L---U : this
630 // L---U : CR
631 return getEmpty();
632 }
633
634 if (isUpperWrapped() && !CR.isUpperWrapped()) {
635 if (CR.Lower.ult(Upper)) {
636 // ------U L--- : this
637 // L--U : CR
638 if (CR.Upper.ult(Upper))
639 return CR;
640
641 // ------U L--- : this
642 // L------U : CR
643 if (CR.Upper.ule(Lower))
644 return ConstantRange(CR.Lower, Upper);
645
646 // ------U L--- : this
647 // L----------U : CR
648 return getPreferredRange(*this, CR, Type);
649 }
650 if (CR.Lower.ult(Lower)) {
651 // --U L---- : this
652 // L--U : CR
653 if (CR.Upper.ule(Lower))
654 return getEmpty();
655
656 // --U L---- : this
657 // L------U : CR
658 return ConstantRange(Lower, CR.Upper);
659 }
660
661 // --U L------ : this
662 // L--U : CR
663 return CR;
664 }
665
666 if (CR.Upper.ult(Upper)) {
667 // ------U L-- : this
668 // --U L------ : CR
669 if (CR.Lower.ult(Upper))
670 return getPreferredRange(*this, CR, Type);
671
672 // ----U L-- : this
673 // --U L---- : CR
674 if (CR.Lower.ult(Lower))
675 return ConstantRange(Lower, CR.Upper);
676
677 // ----U L---- : this
678 // --U L-- : CR
679 return CR;
680 }
681 if (CR.Upper.ule(Lower)) {
682 // --U L-- : this
683 // ----U L---- : CR
684 if (CR.Lower.ult(Lower))
685 return *this;
686
687 // --U L---- : this
688 // ----U L-- : CR
689 return ConstantRange(CR.Lower, Upper);
690 }
691
692 // --U L------ : this
693 // ------U L-- : CR
694 return getPreferredRange(*this, CR, Type);
695}
696
698 PreferredRangeType Type) const {
699 assert(getBitWidth() == CR.getBitWidth() &&
700 "ConstantRange types don't agree!");
701
702 if ( isFullSet() || CR.isEmptySet()) return *this;
703 if (CR.isFullSet() || isEmptySet()) return CR;
704
705 if (!isUpperWrapped() && CR.isUpperWrapped())
706 return CR.unionWith(*this, Type);
707
708 if (!isUpperWrapped() && !CR.isUpperWrapped()) {
709 // L---U and L---U : this
710 // L---U L---U : CR
711 // result in one of
712 // L---------U
713 // -----U L-----
714 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
715 return getPreferredRange(
716 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
717
718 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
719 APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
720
721 if (L.isZero() && U.isZero())
722 return getFull();
723
724 return ConstantRange(std::move(L), std::move(U));
725 }
726
727 if (!CR.isUpperWrapped()) {
728 // ------U L----- and ------U L----- : this
729 // L--U L--U : CR
730 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
731 return *this;
732
733 // ------U L----- : this
734 // L---------U : CR
735 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
736 return getFull();
737
738 // ----U L---- : this
739 // L---U : CR
740 // results in one of
741 // ----------U L----
742 // ----U L----------
743 if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
744 return getPreferredRange(
745 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
746
747 // ----U L----- : this
748 // L----U : CR
749 if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
750 return ConstantRange(CR.Lower, Upper);
751
752 // ------U L---- : this
753 // L-----U : CR
754 assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
755 "ConstantRange::unionWith missed a case with one range wrapped");
756 return ConstantRange(Lower, CR.Upper);
757 }
758
759 // ------U L---- and ------U L---- : this
760 // -U L----------- and ------------U L : CR
761 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
762 return getFull();
763
764 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
765 APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
766
767 return ConstantRange(std::move(L), std::move(U));
768}
769
770std::optional<ConstantRange>
772 // TODO: This can be implemented more efficiently.
773 ConstantRange Result = intersectWith(CR);
774 if (Result == inverse().unionWith(CR.inverse()).inverse())
775 return Result;
776 return std::nullopt;
777}
778
779std::optional<ConstantRange>
781 // TODO: This can be implemented more efficiently.
782 ConstantRange Result = unionWith(CR);
783 if (Result == inverse().intersectWith(CR.inverse()).inverse())
784 return Result;
785 return std::nullopt;
786}
787
789 uint32_t ResultBitWidth) const {
790 switch (CastOp) {
791 default:
792 llvm_unreachable("unsupported cast type");
793 case Instruction::Trunc:
794 return truncate(ResultBitWidth);
795 case Instruction::SExt:
796 return signExtend(ResultBitWidth);
797 case Instruction::ZExt:
798 return zeroExtend(ResultBitWidth);
799 case Instruction::BitCast:
800 return *this;
801 case Instruction::FPToUI:
802 case Instruction::FPToSI:
803 if (getBitWidth() == ResultBitWidth)
804 return *this;
805 else
806 return getFull(ResultBitWidth);
807 case Instruction::UIToFP: {
808 // TODO: use input range if available
809 auto BW = getBitWidth();
810 APInt Min = APInt::getMinValue(BW);
811 APInt Max = APInt::getMaxValue(BW);
812 if (ResultBitWidth > BW) {
813 Min = Min.zext(ResultBitWidth);
814 Max = Max.zext(ResultBitWidth);
815 }
816 return getNonEmpty(std::move(Min), std::move(Max) + 1);
817 }
818 case Instruction::SIToFP: {
819 // TODO: use input range if available
820 auto BW = getBitWidth();
823 if (ResultBitWidth > BW) {
824 SMin = SMin.sext(ResultBitWidth);
825 SMax = SMax.sext(ResultBitWidth);
826 }
827 return getNonEmpty(std::move(SMin), std::move(SMax) + 1);
828 }
829 case Instruction::FPTrunc:
830 case Instruction::FPExt:
831 case Instruction::IntToPtr:
832 case Instruction::PtrToAddr:
833 case Instruction::PtrToInt:
834 case Instruction::AddrSpaceCast:
835 // Conservatively return getFull set.
836 return getFull(ResultBitWidth);
837 };
838}
839
841 if (isEmptySet()) return getEmpty(DstTySize);
842
843 unsigned SrcTySize = getBitWidth();
844 assert(SrcTySize < DstTySize && "Not a value extension");
845 if (isFullSet() || isUpperWrapped()) {
846 // Change into [0, 1 << src bit width)
847 APInt LowerExt(DstTySize, 0);
848 if (!Upper) // special case: [X, 0) -- not really wrapping around
849 LowerExt = Lower.zext(DstTySize);
850 return ConstantRange(std::move(LowerExt),
851 APInt::getOneBitSet(DstTySize, SrcTySize));
852 }
853
854 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
855}
856
858 if (isEmptySet()) return getEmpty(DstTySize);
859
860 unsigned SrcTySize = getBitWidth();
861 assert(SrcTySize < DstTySize && "Not a value extension");
862
863 // special case: [X, INT_MIN) -- not really wrapping around
864 if (Upper.isMinSignedValue())
865 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
866
867 if (isFullSet() || isSignWrappedSet()) {
868 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
869 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
870 }
871
872 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
873}
874
876 unsigned NoWrapKind) const {
877 assert(getBitWidth() > DstTySize && "Not a value truncation");
878 if (isEmptySet())
879 return getEmpty(DstTySize);
880 if (isFullSet())
881 return getFull(DstTySize);
882
883 APInt LowerDiv(Lower), UpperDiv(Upper);
884 ConstantRange Union(DstTySize, /*isFullSet=*/false);
885
886 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
887 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
888 // then we do the union with [MaxValue, Upper)
889 if (isUpperWrapped()) {
890 // If Upper is greater than MaxValue(DstTy), it covers the whole truncated
891 // range.
892 if (Upper.getActiveBits() > DstTySize)
893 return getFull(DstTySize);
894
895 // For nuw the two parts are: [0, Upper) \/ [Lower, MaxValue(DstTy)]
896 if (NoWrapKind & TruncInst::NoUnsignedWrap) {
897 Union = ConstantRange(APInt::getZero(DstTySize), Upper.trunc(DstTySize));
898 UpperDiv = APInt::getOneBitSet(getBitWidth(), DstTySize);
899 } else {
900 // If Upper is equal to MaxValue(DstTy), it covers the whole truncated
901 // range.
902 if (Upper.countr_one() == DstTySize)
903 return getFull(DstTySize);
904 Union =
905 ConstantRange(APInt::getMaxValue(DstTySize), Upper.trunc(DstTySize));
906 UpperDiv.setAllBits();
907 // Union covers the MaxValue case, so return if the remaining range is
908 // just MaxValue(DstTy).
909 if (LowerDiv == UpperDiv)
910 return Union;
911 }
912 }
913
914 // Chop off the most significant bits that are past the destination bitwidth.
915 if (LowerDiv.getActiveBits() > DstTySize) {
916 // For trunc nuw if LowerDiv is greater than MaxValue(DstTy), the range is
917 // outside the whole truncated range.
918 if (NoWrapKind & TruncInst::NoUnsignedWrap)
919 return Union;
920 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
921 APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
922 LowerDiv -= Adjust;
923 UpperDiv -= Adjust;
924 }
925
926 unsigned UpperDivWidth = UpperDiv.getActiveBits();
927 if (UpperDivWidth <= DstTySize)
928 return ConstantRange(LowerDiv.trunc(DstTySize),
929 UpperDiv.trunc(DstTySize)).unionWith(Union);
930
931 if (!LowerDiv.isZero() && NoWrapKind & TruncInst::NoUnsignedWrap)
932 return ConstantRange(LowerDiv.trunc(DstTySize), APInt::getZero(DstTySize))
933 .unionWith(Union);
934
935 // The truncated value wraps around. Check if we can do better than fullset.
936 if (UpperDivWidth == DstTySize + 1) {
937 // Clear the MSB so that UpperDiv wraps around.
938 UpperDiv.clearBit(DstTySize);
939 if (UpperDiv.ult(LowerDiv))
940 return ConstantRange(LowerDiv.trunc(DstTySize),
941 UpperDiv.trunc(DstTySize)).unionWith(Union);
942 }
943
944 return getFull(DstTySize);
945}
946
948 unsigned SrcTySize = getBitWidth();
949 if (SrcTySize > DstTySize)
950 return truncate(DstTySize);
951 if (SrcTySize < DstTySize)
952 return zeroExtend(DstTySize);
953 return *this;
954}
955
957 unsigned SrcTySize = getBitWidth();
958 if (SrcTySize > DstTySize)
959 return truncate(DstTySize);
960 if (SrcTySize < DstTySize)
961 return signExtend(DstTySize);
962 return *this;
963}
964
966 const ConstantRange &Other) const {
967 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
968
969 switch (BinOp) {
970 case Instruction::Add:
971 return add(Other);
972 case Instruction::Sub:
973 return sub(Other);
974 case Instruction::Mul:
975 return multiply(Other);
976 case Instruction::UDiv:
977 return udiv(Other);
978 case Instruction::SDiv:
979 return sdiv(Other);
980 case Instruction::URem:
981 return urem(Other);
982 case Instruction::SRem:
983 return srem(Other);
984 case Instruction::Shl:
985 return shl(Other);
986 case Instruction::LShr:
987 return lshr(Other);
988 case Instruction::AShr:
989 return ashr(Other);
990 case Instruction::And:
991 return binaryAnd(Other);
992 case Instruction::Or:
993 return binaryOr(Other);
994 case Instruction::Xor:
995 return binaryXor(Other);
996 // Note: floating point operations applied to abstract ranges are just
997 // ideal integer operations with a lossy representation
998 case Instruction::FAdd:
999 return add(Other);
1000 case Instruction::FSub:
1001 return sub(Other);
1002 case Instruction::FMul:
1003 return multiply(Other);
1004 default:
1005 // Conservatively return getFull set.
1006 return getFull();
1007 }
1008}
1009
1011 const ConstantRange &Other,
1012 unsigned NoWrapKind) const {
1013 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
1014
1015 switch (BinOp) {
1016 case Instruction::Add:
1017 return addWithNoWrap(Other, NoWrapKind);
1018 case Instruction::Sub:
1019 return subWithNoWrap(Other, NoWrapKind);
1020 case Instruction::Mul:
1021 return multiplyWithNoWrap(Other, NoWrapKind);
1022 case Instruction::Shl:
1023 return shlWithNoWrap(Other, NoWrapKind);
1024 default:
1025 // Don't know about this Overflowing Binary Operation.
1026 // Conservatively fallback to plain binop handling.
1027 return binaryOp(BinOp, Other);
1028 }
1029}
1030
1032 switch (IntrinsicID) {
1033 case Intrinsic::uadd_sat:
1034 case Intrinsic::usub_sat:
1035 case Intrinsic::sadd_sat:
1036 case Intrinsic::ssub_sat:
1037 case Intrinsic::umin:
1038 case Intrinsic::umax:
1039 case Intrinsic::smin:
1040 case Intrinsic::smax:
1041 case Intrinsic::abs:
1042 case Intrinsic::ctlz:
1043 case Intrinsic::cttz:
1044 case Intrinsic::ctpop:
1045 return true;
1046 default:
1047 return false;
1048 }
1049}
1050
1053 switch (IntrinsicID) {
1054 case Intrinsic::uadd_sat:
1055 return Ops[0].uadd_sat(Ops[1]);
1056 case Intrinsic::usub_sat:
1057 return Ops[0].usub_sat(Ops[1]);
1058 case Intrinsic::sadd_sat:
1059 return Ops[0].sadd_sat(Ops[1]);
1060 case Intrinsic::ssub_sat:
1061 return Ops[0].ssub_sat(Ops[1]);
1062 case Intrinsic::umin:
1063 return Ops[0].umin(Ops[1]);
1064 case Intrinsic::umax:
1065 return Ops[0].umax(Ops[1]);
1066 case Intrinsic::smin:
1067 return Ops[0].smin(Ops[1]);
1068 case Intrinsic::smax:
1069 return Ops[0].smax(Ops[1]);
1070 case Intrinsic::abs: {
1071 const APInt *IntMinIsPoison = Ops[1].getSingleElement();
1072 assert(IntMinIsPoison && "Must be known (immarg)");
1073 assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
1074 return Ops[0].abs(IntMinIsPoison->getBoolValue());
1075 }
1076 case Intrinsic::ctlz: {
1077 const APInt *ZeroIsPoison = Ops[1].getSingleElement();
1078 assert(ZeroIsPoison && "Must be known (immarg)");
1079 assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");
1080 return Ops[0].ctlz(ZeroIsPoison->getBoolValue());
1081 }
1082 case Intrinsic::cttz: {
1083 const APInt *ZeroIsPoison = Ops[1].getSingleElement();
1084 assert(ZeroIsPoison && "Must be known (immarg)");
1085 assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");
1086 return Ops[0].cttz(ZeroIsPoison->getBoolValue());
1087 }
1088 case Intrinsic::ctpop:
1089 return Ops[0].ctpop();
1090 default:
1091 assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
1092 llvm_unreachable("Unsupported intrinsic");
1093 }
1094}
1095
1098 if (isEmptySet() || Other.isEmptySet())
1099 return getEmpty();
1100 if (isFullSet() || Other.isFullSet())
1101 return getFull();
1102
1103 APInt NewLower = getLower() + Other.getLower();
1104 APInt NewUpper = getUpper() + Other.getUpper() - 1;
1105 if (NewLower == NewUpper)
1106 return getFull();
1107
1108 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1109 if (X.isSizeStrictlySmallerThan(*this) ||
1110 X.isSizeStrictlySmallerThan(Other))
1111 // We've wrapped, therefore, full set.
1112 return getFull();
1113 return X;
1114}
1115
1117 unsigned NoWrapKind,
1118 PreferredRangeType RangeType) const {
1119 // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
1120 // (X is from this, and Y is from Other)
1121 if (isEmptySet() || Other.isEmptySet())
1122 return getEmpty();
1123 if (isFullSet() && Other.isFullSet())
1124 return getFull();
1125
1126 using OBO = OverflowingBinaryOperator;
1127 ConstantRange Result = add(Other);
1128
1129 // If an overflow happens for every value pair in these two constant ranges,
1130 // we must return Empty set. In this case, we get that for free, because we
1131 // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
1132 // in an empty set.
1133
1134 if (NoWrapKind & OBO::NoSignedWrap)
1135 Result = Result.intersectWith(sadd_sat(Other), RangeType);
1136
1137 if (NoWrapKind & OBO::NoUnsignedWrap)
1138 Result = Result.intersectWith(uadd_sat(Other), RangeType);
1139
1140 return Result;
1141}
1142
1145 if (isEmptySet() || Other.isEmptySet())
1146 return getEmpty();
1147 if (isFullSet() || Other.isFullSet())
1148 return getFull();
1149
1150 APInt NewLower = getLower() - Other.getUpper() + 1;
1151 APInt NewUpper = getUpper() - Other.getLower();
1152 if (NewLower == NewUpper)
1153 return getFull();
1154
1155 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1156 if (X.isSizeStrictlySmallerThan(*this) ||
1157 X.isSizeStrictlySmallerThan(Other))
1158 // We've wrapped, therefore, full set.
1159 return getFull();
1160 return X;
1161}
1162
1164 unsigned NoWrapKind,
1165 PreferredRangeType RangeType) const {
1166 // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
1167 // (X is from this, and Y is from Other)
1168 if (isEmptySet() || Other.isEmptySet())
1169 return getEmpty();
1170 if (isFullSet() && Other.isFullSet())
1171 return getFull();
1172
1173 using OBO = OverflowingBinaryOperator;
1174 ConstantRange Result = sub(Other);
1175
1176 // If an overflow happens for every value pair in these two constant ranges,
1177 // we must return Empty set. In signed case, we get that for free, because we
1178 // get lucky that intersection of sub() with ssub_sat() results in an
1179 // empty set. But for unsigned we must perform the overflow check manually.
1180
1181 if (NoWrapKind & OBO::NoSignedWrap)
1182 Result = Result.intersectWith(ssub_sat(Other), RangeType);
1183
1184 if (NoWrapKind & OBO::NoUnsignedWrap) {
1185 if (getUnsignedMax().ult(Other.getUnsignedMin()))
1186 return getEmpty(); // Always overflows.
1187 Result = Result.intersectWith(usub_sat(Other), RangeType);
1188 }
1189
1190 return Result;
1191}
1192
1195 // TODO: If either operand is a single element and the multiply is known to
1196 // be non-wrapping, round the result min and max value to the appropriate
1197 // multiple of that element. If wrapping is possible, at least adjust the
1198 // range according to the greatest power-of-two factor of the single element.
1199
1200 if (isEmptySet() || Other.isEmptySet())
1201 return getEmpty();
1202
1203 if (const APInt *C = getSingleElement()) {
1204 if (C->isOne())
1205 return Other;
1206 if (C->isAllOnes())
1208 }
1209
1210 if (const APInt *C = Other.getSingleElement()) {
1211 if (C->isOne())
1212 return *this;
1213 if (C->isAllOnes())
1214 return ConstantRange(APInt::getZero(getBitWidth())).sub(*this);
1215 }
1216
1217 // Multiplication is signedness-independent. However different ranges can be
1218 // obtained depending on how the input ranges are treated. These different
1219 // ranges are all conservatively correct, but one might be better than the
1220 // other. We calculate two ranges; one treating the inputs as unsigned
1221 // and the other signed, then return the smallest of these ranges.
1222
1223 // Unsigned range first.
1224 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
1225 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
1226 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
1227 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
1228
1229 ConstantRange Result_zext = ConstantRange(this_min * Other_min,
1230 this_max * Other_max + 1);
1231 ConstantRange UR = Result_zext.truncate(getBitWidth());
1232
1233 // If the unsigned range doesn't wrap, and isn't negative then it's a range
1234 // from one positive number to another which is as good as we can generate.
1235 // In this case, skip the extra work of generating signed ranges which aren't
1236 // going to be better than this range.
1237 if (!UR.isUpperWrapped() &&
1239 return UR;
1240
1241 // Now the signed range. Because we could be dealing with negative numbers
1242 // here, the lower bound is the smallest of the cartesian product of the
1243 // lower and upper ranges; for example:
1244 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1245 // Similarly for the upper bound, swapping min for max.
1246
1247 this_min = getSignedMin().sext(getBitWidth() * 2);
1248 this_max = getSignedMax().sext(getBitWidth() * 2);
1249 Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
1250 Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
1251
1252 auto L = {this_min * Other_min, this_min * Other_max,
1253 this_max * Other_min, this_max * Other_max};
1254 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1255 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
1256 ConstantRange SR = Result_sext.truncate(getBitWidth());
1257
1258 return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
1259}
1260
1263 unsigned NoWrapKind,
1264 PreferredRangeType RangeType) const {
1265 if (isEmptySet() || Other.isEmptySet())
1266 return getEmpty();
1267 if (isFullSet() && Other.isFullSet())
1268 return getFull();
1269
1270 ConstantRange Result = multiply(Other);
1271
1273 Result = Result.intersectWith(smul_sat(Other), RangeType);
1274
1276 Result = Result.intersectWith(umul_sat(Other), RangeType);
1277
1278 // mul nsw nuw X, Y s>= 0 if X s> 1 or Y s> 1
1279 if ((NoWrapKind == (OverflowingBinaryOperator::NoSignedWrap |
1281 !Result.isAllNonNegative()) {
1282 if (getSignedMin().sgt(1) || Other.getSignedMin().sgt(1))
1283 Result = Result.intersectWith(
1286 RangeType);
1287 }
1288
1289 return Result;
1290}
1291
1293 if (isEmptySet() || Other.isEmptySet())
1294 return getEmpty();
1295
1296 APInt Min = getSignedMin();
1297 APInt Max = getSignedMax();
1298 APInt OtherMin = Other.getSignedMin();
1299 APInt OtherMax = Other.getSignedMax();
1300
1301 bool O1, O2, O3, O4;
1302 auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2),
1303 Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)};
1304 if (O1 || O2 || O3 || O4)
1305 return getFull();
1306
1307 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1308 return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1);
1309}
1310
1313 // X smax Y is: range(smax(X_smin, Y_smin),
1314 // smax(X_smax, Y_smax))
1315 if (isEmptySet() || Other.isEmptySet())
1316 return getEmpty();
1317 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
1318 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
1319 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1320 if (isSignWrappedSet() || Other.isSignWrappedSet())
1321 return Res.intersectWith(unionWith(Other, Signed), Signed);
1322 return Res;
1323}
1324
1327 // X umax Y is: range(umax(X_umin, Y_umin),
1328 // umax(X_umax, Y_umax))
1329 if (isEmptySet() || Other.isEmptySet())
1330 return getEmpty();
1331 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1332 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1333 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1334 if (isWrappedSet() || Other.isWrappedSet())
1336 return Res;
1337}
1338
1341 // X smin Y is: range(smin(X_smin, Y_smin),
1342 // smin(X_smax, Y_smax))
1343 if (isEmptySet() || Other.isEmptySet())
1344 return getEmpty();
1345 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
1346 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
1347 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1348 if (isSignWrappedSet() || Other.isSignWrappedSet())
1349 return Res.intersectWith(unionWith(Other, Signed), Signed);
1350 return Res;
1351}
1352
1355 // X umin Y is: range(umin(X_umin, Y_umin),
1356 // umin(X_umax, Y_umax))
1357 if (isEmptySet() || Other.isEmptySet())
1358 return getEmpty();
1359 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
1360 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1361 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1362 if (isWrappedSet() || Other.isWrappedSet())
1364 return Res;
1365}
1366
1369 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1370 return getEmpty();
1371
1372 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
1373
1374 APInt RHS_umin = RHS.getUnsignedMin();
1375 if (RHS_umin.isZero()) {
1376 // We want the lowest value in RHS excluding zero. Usually that would be 1
1377 // except for a range in the form of [X, 1) in which case it would be X.
1378 if (RHS.getUpper() == 1)
1379 RHS_umin = RHS.getLower();
1380 else
1381 RHS_umin = 1;
1382 }
1383
1384 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
1385 return getNonEmpty(std::move(Lower), std::move(Upper));
1386}
1387
1391
1392 // We split up the LHS and RHS into positive and negative components
1393 // and then also compute the positive and negative components of the result
1394 // separately by combining division results with the appropriate signs.
1395 auto [PosL, NegL] = splitPosNeg();
1396 auto [PosR, NegR] = RHS.splitPosNeg();
1397
1398 ConstantRange PosRes = getEmpty();
1399 if (!PosL.isEmptySet() && !PosR.isEmptySet())
1400 // pos / pos = pos.
1401 PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
1402 (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
1403
1404 if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
1405 // neg / neg = pos.
1406 //
1407 // We need to deal with one tricky case here: SignedMin / -1 is UB on the
1408 // IR level, so we'll want to exclude this case when calculating bounds.
1409 // (For APInts the operation is well-defined and yields SignedMin.) We
1410 // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
1411 APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
1412 if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {
1413 // Remove -1 from the LHS. Skip if it's the only element, as this would
1414 // leave us with an empty set.
1415 if (!NegR.Lower.isAllOnes()) {
1416 APInt AdjNegRUpper;
1417 if (RHS.Lower.isAllOnes())
1418 // Negative part of [-1, X] without -1 is [SignedMin, X].
1419 AdjNegRUpper = RHS.Upper;
1420 else
1421 // [X, -1] without -1 is [X, -2].
1422 AdjNegRUpper = NegR.Upper - 1;
1423
1424 PosRes = PosRes.unionWith(
1425 ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
1426 }
1427
1428 // Remove SignedMin from the RHS. Skip if it's the only element, as this
1429 // would leave us with an empty set.
1430 if (NegL.Upper != SignedMin + 1) {
1431 APInt AdjNegLLower;
1432 if (Upper == SignedMin + 1)
1433 // Negative part of [X, SignedMin] without SignedMin is [X, -1].
1434 AdjNegLLower = Lower;
1435 else
1436 // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
1437 AdjNegLLower = NegL.Lower + 1;
1438
1439 PosRes = PosRes.unionWith(
1440 ConstantRange(std::move(Lo),
1441 AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
1442 }
1443 } else {
1444 PosRes = PosRes.unionWith(
1445 ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
1446 }
1447 }
1448
1449 ConstantRange NegRes = getEmpty();
1450 if (!PosL.isEmptySet() && !NegR.isEmptySet())
1451 // pos / neg = neg.
1452 NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
1453 PosL.Lower.sdiv(NegR.Lower) + 1);
1454
1455 if (!NegL.isEmptySet() && !PosR.isEmptySet())
1456 // neg / pos = neg.
1457 NegRes = NegRes.unionWith(
1458 ConstantRange(NegL.Lower.sdiv(PosR.Lower),
1459 (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
1460
1461 // Prefer a non-wrapping signed range here.
1463
1464 // Preserve the zero that we dropped when splitting the LHS by sign.
1465 if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
1466 Res = Res.unionWith(ConstantRange(Zero));
1467 return Res;
1468}
1469
1471 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1472 return getEmpty();
1473
1474 if (const APInt *RHSInt = RHS.getSingleElement()) {
1475 // UREM by null is UB.
1476 if (RHSInt->isZero())
1477 return getEmpty();
1478 // Use APInt's implementation of UREM for single element ranges.
1479 if (const APInt *LHSInt = getSingleElement())
1480 return {LHSInt->urem(*RHSInt)};
1481 }
1482
1483 // L % R for L < R is L.
1484 if (getUnsignedMax().ult(RHS.getUnsignedMin()))
1485 return *this;
1486
1487 // L % R is <= L and < R.
1488 APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
1489 return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper));
1490}
1491
1493 if (isEmptySet() || RHS.isEmptySet())
1494 return getEmpty();
1495
1496 if (const APInt *RHSInt = RHS.getSingleElement()) {
1497 // SREM by null is UB.
1498 if (RHSInt->isZero())
1499 return getEmpty();
1500 // Use APInt's implementation of SREM for single element ranges.
1501 if (const APInt *LHSInt = getSingleElement())
1502 return {LHSInt->srem(*RHSInt)};
1503 }
1504
1505 ConstantRange AbsRHS = RHS.abs();
1506 APInt MinAbsRHS = AbsRHS.getUnsignedMin();
1507 APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
1508
1509 // Modulus by zero is UB.
1510 if (MaxAbsRHS.isZero())
1511 return getEmpty();
1512
1513 if (MinAbsRHS.isZero())
1514 ++MinAbsRHS;
1515
1516 APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
1517
1518 if (MinLHS.isNonNegative()) {
1519 // L % R for L < R is L.
1520 if (MaxLHS.ult(MinAbsRHS))
1521 return *this;
1522
1523 // L % R is <= L and < R.
1524 APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1525 return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper));
1526 }
1527
1528 // Same basic logic as above, but the result is negative.
1529 if (MaxLHS.isNegative()) {
1530 if (MinLHS.ugt(-MinAbsRHS))
1531 return *this;
1532
1533 APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1534 return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
1535 }
1536
1537 // LHS range crosses zero.
1538 APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1539 APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1540 return ConstantRange(std::move(Lower), std::move(Upper));
1541}
1542
1545}
1546
1547/// Estimate the 'bit-masked AND' operation's lower bound.
1548///
1549/// E.g., given two ranges as follows (single quotes are separators and
1550/// have no meaning here),
1551///
1552/// LHS = [10'00101'1, ; LLo
1553/// 10'10000'0] ; LHi
1554/// RHS = [10'11111'0, ; RLo
1555/// 10'11111'1] ; RHi
1556///
1557/// we know that the higher 2 bits of the result is always 10; and we also
1558/// notice that RHS[1:6] are always 1, so the result[1:6] cannot be less than
1559/// LHS[1:6] (i.e., 00101). Thus, the lower bound is 10'00101'0.
1560///
1561/// The algorithm is as follows,
1562/// 1. we first calculate a mask to find the higher common bits by
1563/// Mask = ~((LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo));
1564/// Mask = clear all non-leading-ones bits in Mask;
1565/// in the example, the Mask is set to 11'00000'0;
1566/// 2. calculate a new mask by setting all common leading bits to 1 in RHS, and
1567/// keeping the longest leading ones (i.e., 11'11111'0 in the example);
1568/// 3. return (LLo & new mask) as the lower bound;
1569/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
1570/// bound with the larger one.
1572 const ConstantRange &RHS) {
1573 auto BitWidth = LHS.getBitWidth();
1574 // If either is full set or unsigned wrapped, then the range must contain '0'
1575 // which leads the lower bound to 0.
1576 if ((LHS.isFullSet() || RHS.isFullSet()) ||
1577 (LHS.isWrappedSet() || RHS.isWrappedSet()))
1578 return APInt::getZero(BitWidth);
1579
1580 auto LLo = LHS.getLower();
1581 auto LHi = LHS.getUpper() - 1;
1582 auto RLo = RHS.getLower();
1583 auto RHi = RHS.getUpper() - 1;
1584
1585 // Calculate the mask for the higher common bits.
1586 auto Mask = ~((LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo));
1587 unsigned LeadingOnes = Mask.countLeadingOnes();
1588 Mask.clearLowBits(BitWidth - LeadingOnes);
1589
1590 auto estimateBound = [BitWidth, &Mask](APInt ALo, const APInt &BLo,
1591 const APInt &BHi) {
1592 unsigned LeadingOnes = ((BLo & BHi) | Mask).countLeadingOnes();
1593 unsigned StartBit = BitWidth - LeadingOnes;
1594 ALo.clearLowBits(StartBit);
1595 return ALo;
1596 };
1597
1598 auto LowerBoundByLHS = estimateBound(LLo, RLo, RHi);
1599 auto LowerBoundByRHS = estimateBound(RLo, LLo, LHi);
1600
1601 return APIntOps::umax(LowerBoundByLHS, LowerBoundByRHS);
1602}
1603
1605 if (isEmptySet() || Other.isEmptySet())
1606 return getEmpty();
1607
1608 ConstantRange KnownBitsRange =
1609 fromKnownBits(toKnownBits() & Other.toKnownBits(), false);
1610 auto LowerBound = estimateBitMaskedAndLowerBound(*this, Other);
1611 ConstantRange UMinUMaxRange = getNonEmpty(
1612 LowerBound, APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax()) + 1);
1613 return KnownBitsRange.intersectWith(UMinUMaxRange);
1614}
1615
1617 if (isEmptySet() || Other.isEmptySet())
1618 return getEmpty();
1619
1620 ConstantRange KnownBitsRange =
1621 fromKnownBits(toKnownBits() | Other.toKnownBits(), false);
1622
1623 // ~a & ~b >= x
1624 // <=> ~(~a & ~b) <= ~x
1625 // <=> a | b <= ~x
1626 // <=> a | b < ~x + 1 = -x
1627 // thus, UpperBound(a | b) == -LowerBound(~a & ~b)
1628 auto UpperBound =
1630 // Upper wrapped range.
1631 ConstantRange UMaxUMinRange = getNonEmpty(
1632 APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()), UpperBound);
1633 return KnownBitsRange.intersectWith(UMaxUMinRange);
1634}
1635
1637 if (isEmptySet() || Other.isEmptySet())
1638 return getEmpty();
1639
1640 // Use APInt's implementation of XOR for single element ranges.
1641 if (isSingleElement() && Other.isSingleElement())
1642 return {*getSingleElement() ^ *Other.getSingleElement()};
1643
1644 // Special-case binary complement, since we can give a precise answer.
1645 if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())
1646 return binaryNot();
1647 if (isSingleElement() && getSingleElement()->isAllOnes())
1648 return Other.binaryNot();
1649
1650 KnownBits LHSKnown = toKnownBits();
1651 KnownBits RHSKnown = Other.toKnownBits();
1652 KnownBits Known = LHSKnown ^ RHSKnown;
1653 ConstantRange CR = fromKnownBits(Known, /*IsSigned*/ false);
1654 // Typically the following code doesn't improve the result if BW = 1.
1655 if (getBitWidth() == 1)
1656 return CR;
1657
1658 // If LHS is known to be the subset of RHS, treat LHS ^ RHS as RHS -nuw/nsw
1659 // LHS. If RHS is known to be the subset of LHS, treat LHS ^ RHS as LHS
1660 // -nuw/nsw RHS.
1661 if ((~LHSKnown.Zero).isSubsetOf(RHSKnown.One))
1663 else if ((~RHSKnown.Zero).isSubsetOf(LHSKnown.One))
1664 CR = CR.intersectWith(this->sub(Other), PreferredRangeType::Unsigned);
1665 return CR;
1666}
1667
1670 if (isEmptySet() || Other.isEmptySet())
1671 return getEmpty();
1672
1673 APInt Min = getUnsignedMin();
1674 APInt Max = getUnsignedMax();
1675 if (const APInt *RHS = Other.getSingleElement()) {
1676 unsigned BW = getBitWidth();
1677 if (RHS->uge(BW))
1678 return getEmpty();
1679
1680 unsigned EqualLeadingBits = (Min ^ Max).countl_zero();
1681 if (RHS->ule(EqualLeadingBits))
1682 return getNonEmpty(Min << *RHS, (Max << *RHS) + 1);
1683
1684 return getNonEmpty(APInt::getZero(BW),
1685 APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1);
1686 }
1687
1688 APInt OtherMax = Other.getUnsignedMax();
1689 if (isAllNegative() && OtherMax.ule(Min.countl_one())) {
1690 // For negative numbers, if the shift does not overflow in a signed sense,
1691 // a larger shift will make the number smaller.
1692 Max <<= Other.getUnsignedMin();
1693 Min <<= OtherMax;
1694 return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
1695 }
1696
1697 // There's overflow!
1698 if (OtherMax.ugt(Max.countl_zero()))
1699 return getFull();
1700
1701 // FIXME: implement the other tricky cases
1702
1703 Min <<= Other.getUnsignedMin();
1704 Max <<= OtherMax;
1705
1706 return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
1707}
1708
1710 const ConstantRange &RHS) {
1711 unsigned BitWidth = LHS.getBitWidth();
1712 bool Overflow;
1713 APInt LHSMin = LHS.getUnsignedMin();
1714 unsigned RHSMin = RHS.getUnsignedMin().getLimitedValue(BitWidth);
1715 APInt MinShl = LHSMin.ushl_ov(RHSMin, Overflow);
1716 if (Overflow)
1717 return ConstantRange::getEmpty(BitWidth);
1718 APInt LHSMax = LHS.getUnsignedMax();
1719 unsigned RHSMax = RHS.getUnsignedMax().getLimitedValue(BitWidth);
1720 APInt MaxShl = MinShl;
1721 unsigned MaxShAmt = LHSMax.countLeadingZeros();
1722 if (RHSMin <= MaxShAmt)
1723 MaxShl = LHSMax << std::min(RHSMax, MaxShAmt);
1724 RHSMin = std::max(RHSMin, MaxShAmt + 1);
1725 RHSMax = std::min(RHSMax, LHSMin.countLeadingZeros());
1726 if (RHSMin <= RHSMax)
1727 MaxShl = APIntOps::umax(MaxShl,
1729 return ConstantRange::getNonEmpty(MinShl, MaxShl + 1);
1730}
1731
1733 const APInt &LHSMax,
1734 unsigned RHSMin,
1735 unsigned RHSMax) {
1736 unsigned BitWidth = LHSMin.getBitWidth();
1737 bool Overflow;
1738 APInt MinShl = LHSMin.sshl_ov(RHSMin, Overflow);
1739 if (Overflow)
1740 return ConstantRange::getEmpty(BitWidth);
1741 APInt MaxShl = MinShl;
1742 unsigned MaxShAmt = LHSMax.countLeadingZeros() - 1;
1743 if (RHSMin <= MaxShAmt)
1744 MaxShl = LHSMax << std::min(RHSMax, MaxShAmt);
1745 RHSMin = std::max(RHSMin, MaxShAmt + 1);
1746 RHSMax = std::min(RHSMax, LHSMin.countLeadingZeros() - 1);
1747 if (RHSMin <= RHSMax)
1748 MaxShl = APIntOps::umax(MaxShl,
1749 APInt::getBitsSet(BitWidth, RHSMin, BitWidth - 1));
1750 return ConstantRange::getNonEmpty(MinShl, MaxShl + 1);
1751}
1752
1754 const APInt &LHSMax,
1755 unsigned RHSMin, unsigned RHSMax) {
1756 unsigned BitWidth = LHSMin.getBitWidth();
1757 bool Overflow;
1758 APInt MaxShl = LHSMax.sshl_ov(RHSMin, Overflow);
1759 if (Overflow)
1760 return ConstantRange::getEmpty(BitWidth);
1761 APInt MinShl = MaxShl;
1762 unsigned MaxShAmt = LHSMin.countLeadingOnes() - 1;
1763 if (RHSMin <= MaxShAmt)
1764 MinShl = LHSMin.shl(std::min(RHSMax, MaxShAmt));
1765 RHSMin = std::max(RHSMin, MaxShAmt + 1);
1766 RHSMax = std::min(RHSMax, LHSMax.countLeadingOnes() - 1);
1767 if (RHSMin <= RHSMax)
1768 MinShl = APInt::getSignMask(BitWidth);
1769 return ConstantRange::getNonEmpty(MinShl, MaxShl + 1);
1770}
1771
1773 const ConstantRange &RHS) {
1774 unsigned BitWidth = LHS.getBitWidth();
1775 unsigned RHSMin = RHS.getUnsignedMin().getLimitedValue(BitWidth);
1776 unsigned RHSMax = RHS.getUnsignedMax().getLimitedValue(BitWidth);
1777 APInt LHSMin = LHS.getSignedMin();
1778 APInt LHSMax = LHS.getSignedMax();
1779 if (LHSMin.isNonNegative())
1780 return computeShlNSWWithNNegLHS(LHSMin, LHSMax, RHSMin, RHSMax);
1781 else if (LHSMax.isNegative())
1782 return computeShlNSWWithNegLHS(LHSMin, LHSMax, RHSMin, RHSMax);
1783 return computeShlNSWWithNNegLHS(APInt::getZero(BitWidth), LHSMax, RHSMin,
1784 RHSMax)
1786 RHSMin, RHSMax),
1788}
1789
1791 unsigned NoWrapKind,
1792 PreferredRangeType RangeType) const {
1793 if (isEmptySet() || Other.isEmptySet())
1794 return getEmpty();
1795
1796 switch (NoWrapKind) {
1797 case 0:
1798 return shl(Other);
1800 return computeShlNSW(*this, Other);
1802 return computeShlNUW(*this, Other);
1805 return computeShlNSW(*this, Other)
1806 .intersectWith(computeShlNUW(*this, Other), RangeType);
1807 default:
1808 llvm_unreachable("Invalid NoWrapKind");
1809 }
1810}
1811
1814 if (isEmptySet() || Other.isEmptySet())
1815 return getEmpty();
1816
1817 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1818 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1819 return getNonEmpty(std::move(min), std::move(max));
1820}
1821
1824 if (isEmptySet() || Other.isEmptySet())
1825 return getEmpty();
1826
1827 // May straddle zero, so handle both positive and negative cases.
1828 // 'PosMax' is the upper bound of the result of the ashr
1829 // operation, when Upper of the LHS of ashr is a non-negative.
1830 // number. Since ashr of a non-negative number will result in a
1831 // smaller number, the Upper value of LHS is shifted right with
1832 // the minimum value of 'Other' instead of the maximum value.
1833 APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1834
1835 // 'PosMin' is the lower bound of the result of the ashr
1836 // operation, when Lower of the LHS is a non-negative number.
1837 // Since ashr of a non-negative number will result in a smaller
1838 // number, the Lower value of LHS is shifted right with the
1839 // maximum value of 'Other'.
1840 APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1841
1842 // 'NegMax' is the upper bound of the result of the ashr
1843 // operation, when Upper of the LHS of ashr is a negative number.
1844 // Since 'ashr' of a negative number will result in a bigger
1845 // number, the Upper value of LHS is shifted right with the
1846 // maximum value of 'Other'.
1847 APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1848
1849 // 'NegMin' is the lower bound of the result of the ashr
1850 // operation, when Lower of the LHS of ashr is a negative number.
1851 // Since 'ashr' of a negative number will result in a bigger
1852 // number, the Lower value of LHS is shifted right with the
1853 // minimum value of 'Other'.
1854 APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1855
1856 APInt max, min;
1857 if (getSignedMin().isNonNegative()) {
1858 // Upper and Lower of LHS are non-negative.
1859 min = PosMin;
1860 max = PosMax;
1861 } else if (getSignedMax().isNegative()) {
1862 // Upper and Lower of LHS are negative.
1863 min = NegMin;
1864 max = NegMax;
1865 } else {
1866 // Upper is non-negative and Lower is negative.
1867 min = NegMin;
1868 max = PosMax;
1869 }
1870 return getNonEmpty(std::move(min), std::move(max));
1871}
1872
1874 if (isEmptySet() || Other.isEmptySet())
1875 return getEmpty();
1876
1877 APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1878 APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1879 return getNonEmpty(std::move(NewL), std::move(NewU));
1880}
1881
1883 if (isEmptySet() || Other.isEmptySet())
1884 return getEmpty();
1885
1886 APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1887 APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1888 return getNonEmpty(std::move(NewL), std::move(NewU));
1889}
1890
1892 if (isEmptySet() || Other.isEmptySet())
1893 return getEmpty();
1894
1895 APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1896 APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1897 return getNonEmpty(std::move(NewL), std::move(NewU));
1898}
1899
1901 if (isEmptySet() || Other.isEmptySet())
1902 return getEmpty();
1903
1904 APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1905 APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1906 return getNonEmpty(std::move(NewL), std::move(NewU));
1907}
1908
1910 if (isEmptySet() || Other.isEmptySet())
1911 return getEmpty();
1912
1913 APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());
1914 APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;
1915 return getNonEmpty(std::move(NewL), std::move(NewU));
1916}
1917
1919 if (isEmptySet() || Other.isEmptySet())
1920 return getEmpty();
1921
1922 // Because we could be dealing with negative numbers here, the lower bound is
1923 // the smallest of the cartesian product of the lower and upper ranges;
1924 // for example:
1925 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1926 // Similarly for the upper bound, swapping min for max.
1927
1928 APInt Min = getSignedMin();
1929 APInt Max = getSignedMax();
1930 APInt OtherMin = Other.getSignedMin();
1931 APInt OtherMax = Other.getSignedMax();
1932
1933 auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax),
1934 Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)};
1935 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1936 return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1);
1937}
1938
1940 if (isEmptySet() || Other.isEmptySet())
1941 return getEmpty();
1942
1943 APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());
1944 APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;
1945 return getNonEmpty(std::move(NewL), std::move(NewU));
1946}
1947
1949 if (isEmptySet() || Other.isEmptySet())
1950 return getEmpty();
1951
1952 APInt Min = getSignedMin(), Max = getSignedMax();
1953 APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
1954 APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);
1955 APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
1956 return getNonEmpty(std::move(NewL), std::move(NewU));
1957}
1958
1960 if (isFullSet())
1961 return getEmpty();
1962 if (isEmptySet())
1963 return getFull();
1964 return ConstantRange(Upper, Lower);
1965}
1966
1967ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
1968 if (isEmptySet())
1969 return getEmpty();
1970
1971 if (isSignWrappedSet()) {
1972 APInt Lo;
1973 // Check whether the range crosses zero.
1974 if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
1976 else
1977 Lo = APIntOps::umin(Lower, -Upper + 1);
1978
1979 // If SignedMin is not poison, then it is included in the result range.
1980 if (IntMinIsPoison)
1982 else
1984 }
1985
1987
1988 // Skip SignedMin if it is poison.
1989 if (IntMinIsPoison && SMin.isMinSignedValue()) {
1990 // The range may become empty if it *only* contains SignedMin.
1991 if (SMax.isMinSignedValue())
1992 return getEmpty();
1993 ++SMin;
1994 }
1995
1996 // All non-negative.
1997 if (SMin.isNonNegative())
1998 return ConstantRange(SMin, SMax + 1);
1999
2000 // All negative.
2001 if (SMax.isNegative())
2002 return ConstantRange(-SMax, -SMin + 1);
2003
2004 // Range crosses zero.
2006 APIntOps::umax(-SMin, SMax) + 1);
2007}
2008
2009ConstantRange ConstantRange::ctlz(bool ZeroIsPoison) const {
2010 if (isEmptySet())
2011 return getEmpty();
2012
2014 if (ZeroIsPoison && contains(Zero)) {
2015 // ZeroIsPoison is set, and zero is contained. We discern three cases, in
2016 // which a zero can appear:
2017 // 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.
2018 // 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.
2019 // 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.
2020
2021 if (getLower().isZero()) {
2022 if ((getUpper() - 1).isZero()) {
2023 // We have in input interval of kind [0, 1). In this case we cannot
2024 // really help but return empty-set.
2025 return getEmpty();
2026 }
2027
2028 // Compute the resulting range by excluding zero from Lower.
2029 return ConstantRange(
2030 APInt(getBitWidth(), (getUpper() - 1).countl_zero()),
2031 APInt(getBitWidth(), (getLower() + 1).countl_zero() + 1));
2032 } else if ((getUpper() - 1).isZero()) {
2033 // Compute the resulting range by excluding zero from Upper.
2034 return ConstantRange(Zero,
2036 } else {
2037 return ConstantRange(Zero, APInt(getBitWidth(), getBitWidth()));
2038 }
2039 }
2040
2041 // Zero is either safe or not in the range. The output range is composed by
2042 // the result of countLeadingZero of the two extremes.
2045}
2046
2048 const APInt &Upper) {
2049 assert(!ConstantRange(Lower, Upper).isWrappedSet() &&
2050 "Unexpected wrapped set.");
2051 assert(Lower != Upper && "Unexpected empty set.");
2052 unsigned BitWidth = Lower.getBitWidth();
2053 if (Lower + 1 == Upper)
2054 return ConstantRange(APInt(BitWidth, Lower.countr_zero()));
2055 if (Lower.isZero())
2057 APInt(BitWidth, BitWidth + 1));
2058
2059 // Calculate longest common prefix.
2060 unsigned LCPLength = (Lower ^ (Upper - 1)).countl_zero();
2061 // If Lower is {LCP, 000...}, the maximum is Lower.countr_zero().
2062 // Otherwise, the maximum is BitWidth - LCPLength - 1 ({LCP, 100...}).
2063 return ConstantRange(
2066 std::max(BitWidth - LCPLength - 1, Lower.countr_zero()) + 1));
2067}
2068
2069ConstantRange ConstantRange::cttz(bool ZeroIsPoison) const {
2070 if (isEmptySet())
2071 return getEmpty();
2072
2073 unsigned BitWidth = getBitWidth();
2075 if (ZeroIsPoison && contains(Zero)) {
2076 // ZeroIsPoison is set, and zero is contained. We discern three cases, in
2077 // which a zero can appear:
2078 // 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.
2079 // 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.
2080 // 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.
2081
2082 if (Lower.isZero()) {
2083 if (Upper == 1) {
2084 // We have in input interval of kind [0, 1). In this case we cannot
2085 // really help but return empty-set.
2086 return getEmpty();
2087 }
2088
2089 // Compute the resulting range by excluding zero from Lower.
2091 } else if (Upper == 1) {
2092 // Compute the resulting range by excluding zero from Upper.
2093 return getUnsignedCountTrailingZerosRange(Lower, Zero);
2094 } else {
2096 ConstantRange CR2 =
2098 return CR1.unionWith(CR2);
2099 }
2100 }
2101
2102 if (isFullSet())
2103 return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
2104 if (!isWrappedSet())
2105 return getUnsignedCountTrailingZerosRange(Lower, Upper);
2106 // The range is wrapped. We decompose it into two ranges, [0, Upper) and
2107 // [Lower, 0).
2108 // Handle [Lower, 0)
2110 // Handle [0, Upper)
2112 return CR1.unionWith(CR2);
2113}
2114
2116 const APInt &Upper) {
2117 assert(!ConstantRange(Lower, Upper).isWrappedSet() &&
2118 "Unexpected wrapped set.");
2119 assert(Lower != Upper && "Unexpected empty set.");
2120 unsigned BitWidth = Lower.getBitWidth();
2121 if (Lower + 1 == Upper)
2122 return ConstantRange(APInt(BitWidth, Lower.popcount()));
2123
2124 APInt Max = Upper - 1;
2125 // Calculate longest common prefix.
2126 unsigned LCPLength = (Lower ^ Max).countl_zero();
2127 unsigned LCPPopCount = Lower.getHiBits(LCPLength).popcount();
2128 // If Lower is {LCP, 000...}, the minimum is the popcount of LCP.
2129 // Otherwise, the minimum is the popcount of LCP + 1.
2130 unsigned MinBits =
2131 LCPPopCount + (Lower.countr_zero() < BitWidth - LCPLength ? 1 : 0);
2132 // If Max is {LCP, 111...}, the maximum is the popcount of LCP + (BitWidth -
2133 // length of LCP).
2134 // Otherwise, the minimum is the popcount of LCP + (BitWidth -
2135 // length of LCP - 1).
2136 unsigned MaxBits = LCPPopCount + (BitWidth - LCPLength) -
2137 (Max.countr_one() < BitWidth - LCPLength ? 1 : 0);
2138 return ConstantRange(APInt(BitWidth, MinBits), APInt(BitWidth, MaxBits + 1));
2139}
2140
2142 if (isEmptySet())
2143 return getEmpty();
2144
2145 unsigned BitWidth = getBitWidth();
2147 if (isFullSet())
2148 return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
2149 if (!isWrappedSet())
2150 return getUnsignedPopCountRange(Lower, Upper);
2151 // The range is wrapped. We decompose it into two ranges, [0, Upper) and
2152 // [Lower, 0).
2153 // Handle [Lower, 0) == [Lower, Max]
2155 APInt(BitWidth, BitWidth + 1));
2156 // Handle [0, Upper)
2157 ConstantRange CR2 = getUnsignedPopCountRange(Zero, Upper);
2158 return CR1.unionWith(CR2);
2159}
2160
2162 const ConstantRange &Other) const {
2163 if (isEmptySet() || Other.isEmptySet())
2165
2166 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2167 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2168
2169 // a u+ b overflows high iff a u> ~b.
2170 if (Min.ugt(~OtherMin))
2172 if (Max.ugt(~OtherMax))
2175}
2176
2178 const ConstantRange &Other) const {
2179 if (isEmptySet() || Other.isEmptySet())
2181
2182 APInt Min = getSignedMin(), Max = getSignedMax();
2183 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2184
2187
2188 // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
2189 // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
2190 if (Min.isNonNegative() && OtherMin.isNonNegative() &&
2191 Min.sgt(SignedMax - OtherMin))
2193 if (Max.isNegative() && OtherMax.isNegative() &&
2194 Max.slt(SignedMin - OtherMax))
2196
2197 if (Max.isNonNegative() && OtherMax.isNonNegative() &&
2198 Max.sgt(SignedMax - OtherMax))
2200 if (Min.isNegative() && OtherMin.isNegative() &&
2201 Min.slt(SignedMin - OtherMin))
2203
2205}
2206
2208 const ConstantRange &Other) const {
2209 if (isEmptySet() || Other.isEmptySet())
2211
2212 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2213 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2214
2215 // a u- b overflows low iff a u< b.
2216 if (Max.ult(OtherMin))
2218 if (Min.ult(OtherMax))
2221}
2222
2224 const ConstantRange &Other) const {
2225 if (isEmptySet() || Other.isEmptySet())
2227
2228 APInt Min = getSignedMin(), Max = getSignedMax();
2229 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2230
2233
2234 // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
2235 // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
2236 if (Min.isNonNegative() && OtherMax.isNegative() &&
2237 Min.sgt(SignedMax + OtherMax))
2239 if (Max.isNegative() && OtherMin.isNonNegative() &&
2240 Max.slt(SignedMin + OtherMin))
2242
2243 if (Max.isNonNegative() && OtherMin.isNegative() &&
2244 Max.sgt(SignedMax + OtherMin))
2246 if (Min.isNegative() && OtherMax.isNonNegative() &&
2247 Min.slt(SignedMin + OtherMax))
2249
2251}
2252
2254 const ConstantRange &Other) const {
2255 if (isEmptySet() || Other.isEmptySet())
2257
2258 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2259 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2260 bool Overflow;
2261
2262 (void) Min.umul_ov(OtherMin, Overflow);
2263 if (Overflow)
2265
2266 (void) Max.umul_ov(OtherMax, Overflow);
2267 if (Overflow)
2269
2271}
2272
2274 if (isFullSet())
2275 OS << "full-set";
2276 else if (isEmptySet())
2277 OS << "empty-set";
2278 else
2279 OS << "[" << Lower << "," << Upper << ")";
2280}
2281
2282#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2284 print(dbgs());
2285}
2286#endif
2287
2289 const unsigned NumRanges = Ranges.getNumOperands() / 2;
2290 assert(NumRanges >= 1 && "Must have at least one range!");
2291 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
2292
2293 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
2294 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
2295
2296 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
2297
2298 for (unsigned i = 1; i < NumRanges; ++i) {
2299 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
2300 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
2301
2302 // Note: unionWith will potentially create a range that contains values not
2303 // contained in any of the original N ranges.
2304 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
2305 }
2306
2307 return CR;
2308}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:638
static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS, const ConstantRange &RHS)
Estimate the 'bit-masked AND' operation's lower bound.
static ConstantRange computeShlNUW(const ConstantRange &LHS, const ConstantRange &RHS)
static ConstantRange getUnsignedPopCountRange(const APInt &Lower, const APInt &Upper)
static ConstantRange computeShlNSW(const ConstantRange &LHS, const ConstantRange &RHS)
static ConstantRange makeExactMulNUWRegion(const APInt &V)
Exact mul nuw region for single element RHS.
static ConstantRange computeShlNSWWithNNegLHS(const APInt &LHSMin, const APInt &LHSMax, unsigned RHSMin, unsigned RHSMax)
static ConstantRange makeExactMulNSWRegion(const APInt &V)
Exact mul nsw region for single element RHS.
static ConstantRange getPreferredRange(const ConstantRange &CR1, const ConstantRange &CR2, ConstantRange::PreferredRangeType Type)
static ConstantRange getUnsignedCountTrailingZerosRange(const APInt &Lower, const APInt &Upper)
static ConstantRange computeShlNSWWithNegLHS(const APInt &LHSMin, const APInt &LHSMax, unsigned RHSMin, unsigned RHSMax)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:546
This file contains the declarations for metadata subclasses.
uint64_t High
raw_pwrite_stream & OS
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1971
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition: APInt.cpp:2055
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1573
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:234
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition: APInt.h:1406
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:1012
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:229
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:423
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1512
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:936
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition: APInt.h:206
LLVM_ABI APInt sshl_ov(const APInt &Amt, bool &Overflow) const
Definition: APInt.cpp:1988
LLVM_ABI APInt smul_sat(const APInt &RHS) const
Definition: APInt.cpp:2064
unsigned countLeadingOnes() const
Definition: APInt.h:1624
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition: APInt.cpp:2026
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition: APInt.h:1201
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1182
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition: APInt.h:258
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:380
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1488
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1111
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:209
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition: APInt.h:417
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition: APInt.h:216
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:329
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition: APInt.cpp:1644
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition: APInt.h:1166
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:219
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition: APInt.cpp:2086
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition: APInt.cpp:2100
LLVM_ABI APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition: APInt.cpp:2005
unsigned countLeadingZeros() const
Definition: APInt.h:1606
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition: APInt.h:356
unsigned countl_one() const
Count the number of leading one bits.
Definition: APInt.h:1615
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition: APInt.h:1435
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition: APInt.cpp:2036
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:827
void setAllBits()
Set every bit to 1.
Definition: APInt.h:1319
bool getBoolValue() const
Convert APInt to a boolean value.
Definition: APInt.h:471
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1960
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:334
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1150
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition: APInt.cpp:985
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:873
LLVM_ABI APInt umul_sat(const APInt &RHS) const
Definition: APInt.cpp:2077
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:306
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1130
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:296
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:200
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1237
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition: APInt.h:286
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:239
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:851
unsigned countr_one() const
Count the number of trailing one bits.
Definition: APInt.h:1656
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1221
void clearSignBit()
Set the sign bit to 0.
Definition: APInt.h:1449
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition: APInt.cpp:2045
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition: APInt.h:399
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:678
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:707
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:708
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:702
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:701
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:705
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:703
@ ICMP_EQ
equal
Definition: InstrTypes.h:699
@ ICMP_NE
not equal
Definition: InstrTypes.h:700
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:706
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:704
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:791
bool isIntPredicate() const
Definition: InstrTypes.h:785
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition: InstrTypes.h:928
This class represents a range of values.
Definition: ConstantRange.h:47
LLVM_ABI ConstantRange multiply(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI unsigned getActiveBits() const
Compute the maximal number of active bits needed to represent every value in this range.
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI std::optional< ConstantRange > exactUnionWith(const ConstantRange &CR) const
Union the two ranges and return the result if it can be represented exactly, otherwise return std::nu...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange umul_sat(const ConstantRange &Other) const
Perform an unsigned saturating multiplication of two constant ranges.
static LLVM_ABI CmpInst::Predicate getEquivalentPredWithFlippedSignedness(CmpInst::Predicate Pred, const ConstantRange &CR1, const ConstantRange &CR2)
If the comparison between constant ranges this and Other is insensitive to the signedness of the comp...
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange binaryXor(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-xor of a value in this ra...
const APInt * getSingleMissingElement() const
If this set contains all but a single element, return it, otherwise return null.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI ConstantRange sshl_sat(const ConstantRange &Other) const
Perform a signed saturating left shift of this constant range by a value in Other.
LLVM_ABI ConstantRange smul_fast(const ConstantRange &Other) const
Return range of possible values for a signed multiplication of this and Other.
LLVM_ABI ConstantRange lshr(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a logical right shift of a value i...
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
LLVM_ABI ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI ConstantRange srem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed remainder operation of a ...
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
LLVM_ABI ConstantRange sadd_sat(const ConstantRange &Other) const
Perform a signed saturating addition of two constant ranges.
LLVM_ABI ConstantRange ushl_sat(const ConstantRange &Other) const
Perform an unsigned saturating left shift of this constant range by a value in Other.
static LLVM_ABI ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
LLVM_ABI void dump() const
Allow printing from a debugger easily.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange smul_sat(const ConstantRange &Other) const
Perform a signed saturating multiplication of two constant ranges.
LLVM_ABI bool isAllPositive() const
Return true if all values in this range are positive.
LLVM_ABI ConstantRange shl(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a left shift of a value in this ra...
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
static LLVM_ABI bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
static LLVM_ABI ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the largest range such that all values in the returned range satisfy the given predicate with...
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI ConstantRange usub_sat(const ConstantRange &Other) const
Perform an unsigned saturating subtraction of two constant ranges.
LLVM_ABI ConstantRange uadd_sat(const ConstantRange &Other) const
Perform an unsigned saturating addition of two constant ranges.
LLVM_ABI ConstantRange overflowingBinaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind) const
Return a new range representing the possible values resulting from an application of the specified ov...
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
LLVM_ABI ConstantRange(uint32_t BitWidth, bool isFullSet)
Initialize a full or empty set for the specified bit width.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI std::pair< ConstantRange, ConstantRange > splitPosNeg() const
Split the ConstantRange into positive and negative components, ignoring zero values.
LLVM_ABI ConstantRange subWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from an subtraction with wrap type NoWr...
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange ssub_sat(const ConstantRange &Other) const
Perform a signed saturating subtraction of two constant ranges.
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
LLVM_ABI ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange sdiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed division of a value in th...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool isUpperWrapped() const
Return true if the exclusive upper bound wraps around the unsigned domain.
LLVM_ABI ConstantRange shlWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from a left shift with wrap type NoWrap...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI std::optional< ConstantRange > exactIntersectWith(const ConstantRange &CR) const
Intersect the two ranges and return the result if it can be represented exactly, otherwise return std...
LLVM_ABI ConstantRange ashr(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a arithmetic right shift of a valu...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static LLVM_ABI bool areInsensitiveToSignednessOfInvertedICmpPredicate(const ConstantRange &CR1, const ConstantRange &CR2)
Return true iff CR1 ult CR2 is equivalent to CR1 sge CR2.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange addWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from an addition with wrap type NoWrapK...
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static LLVM_ABI ConstantRange makeMaskNotEqualRange(const APInt &Mask, const APInt &C)
Initialize a range containing all values X that satisfy (X & Mask) != C.
static LLVM_ABI bool areInsensitiveToSignednessOfICmpPredicate(const ConstantRange &CR1, const ConstantRange &CR2)
Return true iff CR1 ult CR2 is equivalent to CR1 slt CR2.
LLVM_ABI ConstantRange cttz(bool ZeroIsPoison=false) const
Calculate cttz range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
Definition: ConstantRange.h:84
LLVM_ABI ConstantRange ctpop() const
Calculate ctpop range.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
LLVM_ABI ConstantRange udiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned division of a value in...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange binaryNot() const
Return a new range representing the possible values resulting from a binary-xor of a value in this ra...
LLVM_ABI ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
LLVM_ABI ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
LLVM_ABI ConstantRange binaryOr(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-or of a value in this ran...
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange ctlz(bool ZeroIsPoison=false) const
Calculate ctlz range.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
LLVM_ABI bool isSizeStrictlySmallerThan(const ConstantRange &CR) const
Compare set size of this range with the range CR.
LLVM_ABI ConstantRange multiplyWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from a multiplication with wrap type No...
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
bool isBinaryOp() const
Definition: Instruction.h:317
Metadata node.
Definition: Metadata.h:1077
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition: Operator.h:78
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI std::optional< unsigned > GetMostSignificantDifferentBit(const APInt &A, const APInt &B)
Compare two values, and if they are different, return the position of the most significant bit that i...
Definition: APInt.cpp:3002
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition: APInt.cpp:2763
LLVM_ABI APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
Definition: APInt.cpp:2781
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition: APInt.h:2248
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition: APInt.h:2253
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition: APInt.h:2258
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition: APInt.h:2263
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:477
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition: bit.h:203
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
@ Other
Any other memory.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:223
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition: KnownBits.h:294
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:101
bool isUnknown() const
Returns true if we don't know any bits.
Definition: KnownBits.h:66
bool hasConflict() const
Returns true if there is conflicting information.
Definition: KnownBits.h:51
unsigned getBitWidth() const
Get the bit width of this value.
Definition: KnownBits.h:44
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition: KnownBits.h:138
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition: KnownBits.h:122
bool isNegative() const
Returns true if this value is known to be negative.
Definition: KnownBits.h:98