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