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