1 //===- ConstantRangeTest.cpp - ConstantRange tests ------------------------===//
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 #include "llvm/IR/ConstantRange.h"
10 #include "llvm/ADT/BitVector.h"
11 #include "llvm/ADT/Sequence.h"
12 #include "llvm/ADT/SmallBitVector.h"
13 #include "llvm/IR/Instructions.h"
14 #include "llvm/IR/Operator.h"
15 #include "llvm/Support/KnownBits.h"
16 #include "gtest/gtest.h"
17 
18 using namespace llvm;
19 
20 namespace {
21 
22 class ConstantRangeTest : public ::testing::Test {
23 protected:
24   static ConstantRange Full;
25   static ConstantRange Empty;
26   static ConstantRange One;
27   static ConstantRange Some;
28   static ConstantRange Wrap;
29 };
30 
31 template<typename Fn>
32 static void EnumerateConstantRanges(unsigned Bits, Fn TestFn) {
33   unsigned Max = 1 << Bits;
34   for (unsigned Lo = 0; Lo < Max; Lo++) {
35     for (unsigned Hi = 0; Hi < Max; Hi++) {
36       // Enforce ConstantRange invariant.
37       if (Lo == Hi && Lo != 0 && Lo != Max - 1)
38         continue;
39 
40       ConstantRange CR(APInt(Bits, Lo), APInt(Bits, Hi));
41       TestFn(CR);
42     }
43   }
44 }
45 
46 template<typename Fn>
47 static void EnumerateTwoConstantRanges(unsigned Bits, Fn TestFn) {
48   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR1) {
49     EnumerateConstantRanges(Bits, [&](const ConstantRange &CR2) {
50       TestFn(CR1, CR2);
51     });
52   });
53 }
54 
55 template<typename Fn>
56 static void ForeachNumInConstantRange(const ConstantRange &CR, Fn TestFn) {
57   if (!CR.isEmptySet()) {
58     APInt N = CR.getLower();
59     do TestFn(N);
60     while (++N != CR.getUpper());
61   }
62 }
63 
64 using PreferFn = llvm::function_ref<bool(const ConstantRange &,
65                                          const ConstantRange &)>;
66 
67 bool PreferSmallest(const ConstantRange &CR1, const ConstantRange &CR2) {
68   return CR1.isSizeStrictlySmallerThan(CR2);
69 }
70 
71 bool PreferSmallestUnsigned(const ConstantRange &CR1,
72                             const ConstantRange &CR2) {
73   if (CR1.isWrappedSet() != CR2.isWrappedSet())
74     return CR1.isWrappedSet() < CR2.isWrappedSet();
75   return PreferSmallest(CR1, CR2);
76 }
77 
78 bool PreferSmallestSigned(const ConstantRange &CR1, const ConstantRange &CR2) {
79   if (CR1.isSignWrappedSet() != CR2.isSignWrappedSet())
80     return CR1.isSignWrappedSet() < CR2.isSignWrappedSet();
81   return PreferSmallest(CR1, CR2);
82 }
83 
84 bool PreferSmallestNonFullUnsigned(const ConstantRange &CR1,
85                                    const ConstantRange &CR2) {
86   if (CR1.isFullSet() != CR2.isFullSet())
87     return CR1.isFullSet() < CR2.isFullSet();
88   return PreferSmallestUnsigned(CR1, CR2);
89 }
90 
91 bool PreferSmallestNonFullSigned(const ConstantRange &CR1,
92                                  const ConstantRange &CR2) {
93   if (CR1.isFullSet() != CR2.isFullSet())
94     return CR1.isFullSet() < CR2.isFullSet();
95   return PreferSmallestSigned(CR1, CR2);
96 }
97 
98 testing::AssertionResult rangeContains(const ConstantRange &CR, const APInt &N,
99                                        ArrayRef<ConstantRange> Inputs) {
100   if (CR.contains(N))
101     return testing::AssertionSuccess();
102 
103   testing::AssertionResult Result = testing::AssertionFailure();
104   Result << CR << " does not contain " << N << " for inputs: ";
105   for (const ConstantRange &Input : Inputs)
106     Result << Input << ", ";
107   return Result;
108 }
109 
110 // Check whether constant range CR is an optimal approximation of the set
111 // Elems under the given PreferenceFn. The preference function should return
112 // true if the first range argument is strictly preferred to the second one.
113 static void TestRange(const ConstantRange &CR, const SmallBitVector &Elems,
114                       PreferFn PreferenceFn, ArrayRef<ConstantRange> Inputs,
115                       bool CheckOptimality = true) {
116   unsigned BitWidth = CR.getBitWidth();
117 
118   // Check conservative correctness.
119   for (unsigned Elem : Elems.set_bits()) {
120     EXPECT_TRUE(rangeContains(CR, APInt(BitWidth, Elem), Inputs));
121   }
122 
123   if (!CheckOptimality)
124     return;
125 
126   // Make sure we have at least one element for the code below.
127   if (Elems.none()) {
128     EXPECT_TRUE(CR.isEmptySet());
129     return;
130   }
131 
132   auto NotPreferred = [&](const ConstantRange &PossibleCR) {
133     if (!PreferenceFn(PossibleCR, CR))
134       return testing::AssertionSuccess();
135 
136     testing::AssertionResult Result = testing::AssertionFailure();
137     Result << "Inputs = ";
138     for (const ConstantRange &Input : Inputs)
139       Result << Input << ", ";
140     Result << "CR = " << CR << ", BetterCR = " << PossibleCR;
141     return Result;
142   };
143 
144   // Look at all pairs of adjacent elements and the slack-free ranges
145   // [Elem, PrevElem] they imply. Check that none of the ranges are strictly
146   // preferred over the computed range (they may have equal preference).
147   int FirstElem = Elems.find_first();
148   int PrevElem = FirstElem, Elem;
149   do {
150     Elem = Elems.find_next(PrevElem);
151     if (Elem < 0)
152       Elem = FirstElem; // Wrap around to first element.
153 
154     ConstantRange PossibleCR =
155         ConstantRange::getNonEmpty(APInt(BitWidth, Elem),
156                                    APInt(BitWidth, PrevElem) + 1);
157     // We get a full range any time PrevElem and Elem are adjacent. Avoid
158     // repeated checks by skipping here, and explicitly checking below instead.
159     if (!PossibleCR.isFullSet()) {
160       EXPECT_TRUE(NotPreferred(PossibleCR));
161     }
162 
163     PrevElem = Elem;
164   } while (Elem != FirstElem);
165 
166   EXPECT_TRUE(NotPreferred(ConstantRange::getFull(BitWidth)));
167 }
168 
169 using UnaryRangeFn = llvm::function_ref<ConstantRange(const ConstantRange &)>;
170 using UnaryIntFn = llvm::function_ref<Optional<APInt>(const APInt &)>;
171 
172 static void TestUnaryOpExhaustive(UnaryRangeFn RangeFn, UnaryIntFn IntFn,
173                                   PreferFn PreferenceFn = PreferSmallest) {
174   unsigned Bits = 4;
175   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
176     SmallBitVector Elems(1 << Bits);
177     ForeachNumInConstantRange(CR, [&](const APInt &N) {
178       if (Optional<APInt> ResultN = IntFn(N))
179         Elems.set(ResultN->getZExtValue());
180     });
181     TestRange(RangeFn(CR), Elems, PreferenceFn, {CR});
182   });
183 }
184 
185 using BinaryRangeFn = llvm::function_ref<ConstantRange(const ConstantRange &,
186                                                        const ConstantRange &)>;
187 using BinaryIntFn = llvm::function_ref<Optional<APInt>(const APInt &,
188                                                        const APInt &)>;
189 using BinaryCheckFn = llvm::function_ref<bool(const ConstantRange &,
190                                               const ConstantRange &)>;
191 
192 static bool CheckAll(const ConstantRange &, const ConstantRange &) {
193   return true;
194 }
195 
196 static bool CheckSingleElementsOnly(const ConstantRange &CR1,
197                                     const ConstantRange &CR2) {
198   return CR1.isSingleElement() && CR2.isSingleElement();
199 }
200 
201 // CheckFn determines whether optimality is checked for a given range pair.
202 // Correctness is always checked.
203 static void TestBinaryOpExhaustive(BinaryRangeFn RangeFn, BinaryIntFn IntFn,
204                                    PreferFn PreferenceFn = PreferSmallest,
205                                    BinaryCheckFn CheckFn = CheckAll) {
206   unsigned Bits = 4;
207   EnumerateTwoConstantRanges(
208       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
209         SmallBitVector Elems(1 << Bits);
210         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
211           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
212             if (Optional<APInt> ResultN = IntFn(N1, N2))
213               Elems.set(ResultN->getZExtValue());
214           });
215         });
216         TestRange(RangeFn(CR1, CR2), Elems, PreferenceFn, {CR1, CR2},
217                   CheckFn(CR1, CR2));
218       });
219 }
220 
221 struct OpRangeGathererBase {
222   void account(const APInt &N);
223   ConstantRange getRange();
224 };
225 
226 struct UnsignedOpRangeGatherer : public OpRangeGathererBase {
227   APInt Min;
228   APInt Max;
229 
230   UnsignedOpRangeGatherer(unsigned Bits)
231       : Min(APInt::getMaxValue(Bits)), Max(APInt::getMinValue(Bits)) {}
232 
233   void account(const APInt &N) {
234     if (N.ult(Min))
235       Min = N;
236     if (N.ugt(Max))
237       Max = N;
238   }
239 
240   ConstantRange getRange() {
241     if (Min.ugt(Max))
242       return ConstantRange::getEmpty(Min.getBitWidth());
243     return ConstantRange::getNonEmpty(Min, Max + 1);
244   }
245 };
246 
247 struct SignedOpRangeGatherer : public OpRangeGathererBase {
248   APInt Min;
249   APInt Max;
250 
251   SignedOpRangeGatherer(unsigned Bits)
252       : Min(APInt::getSignedMaxValue(Bits)),
253         Max(APInt::getSignedMinValue(Bits)) {}
254 
255   void account(const APInt &N) {
256     if (N.slt(Min))
257       Min = N;
258     if (N.sgt(Max))
259       Max = N;
260   }
261 
262   ConstantRange getRange() {
263     if (Min.sgt(Max))
264       return ConstantRange::getEmpty(Min.getBitWidth());
265     return ConstantRange::getNonEmpty(Min, Max + 1);
266   }
267 };
268 
269 ConstantRange ConstantRangeTest::Full(16, true);
270 ConstantRange ConstantRangeTest::Empty(16, false);
271 ConstantRange ConstantRangeTest::One(APInt(16, 0xa));
272 ConstantRange ConstantRangeTest::Some(APInt(16, 0xa), APInt(16, 0xaaa));
273 ConstantRange ConstantRangeTest::Wrap(APInt(16, 0xaaa), APInt(16, 0xa));
274 
275 TEST_F(ConstantRangeTest, Basics) {
276   EXPECT_TRUE(Full.isFullSet());
277   EXPECT_FALSE(Full.isEmptySet());
278   EXPECT_TRUE(Full.inverse().isEmptySet());
279   EXPECT_FALSE(Full.isWrappedSet());
280   EXPECT_TRUE(Full.contains(APInt(16, 0x0)));
281   EXPECT_TRUE(Full.contains(APInt(16, 0x9)));
282   EXPECT_TRUE(Full.contains(APInt(16, 0xa)));
283   EXPECT_TRUE(Full.contains(APInt(16, 0xaa9)));
284   EXPECT_TRUE(Full.contains(APInt(16, 0xaaa)));
285 
286   EXPECT_FALSE(Empty.isFullSet());
287   EXPECT_TRUE(Empty.isEmptySet());
288   EXPECT_TRUE(Empty.inverse().isFullSet());
289   EXPECT_FALSE(Empty.isWrappedSet());
290   EXPECT_FALSE(Empty.contains(APInt(16, 0x0)));
291   EXPECT_FALSE(Empty.contains(APInt(16, 0x9)));
292   EXPECT_FALSE(Empty.contains(APInt(16, 0xa)));
293   EXPECT_FALSE(Empty.contains(APInt(16, 0xaa9)));
294   EXPECT_FALSE(Empty.contains(APInt(16, 0xaaa)));
295 
296   EXPECT_FALSE(One.isFullSet());
297   EXPECT_FALSE(One.isEmptySet());
298   EXPECT_FALSE(One.isWrappedSet());
299   EXPECT_FALSE(One.contains(APInt(16, 0x0)));
300   EXPECT_FALSE(One.contains(APInt(16, 0x9)));
301   EXPECT_TRUE(One.contains(APInt(16, 0xa)));
302   EXPECT_FALSE(One.contains(APInt(16, 0xaa9)));
303   EXPECT_FALSE(One.contains(APInt(16, 0xaaa)));
304   EXPECT_FALSE(One.inverse().contains(APInt(16, 0xa)));
305 
306   EXPECT_FALSE(Some.isFullSet());
307   EXPECT_FALSE(Some.isEmptySet());
308   EXPECT_FALSE(Some.isWrappedSet());
309   EXPECT_FALSE(Some.contains(APInt(16, 0x0)));
310   EXPECT_FALSE(Some.contains(APInt(16, 0x9)));
311   EXPECT_TRUE(Some.contains(APInt(16, 0xa)));
312   EXPECT_TRUE(Some.contains(APInt(16, 0xaa9)));
313   EXPECT_FALSE(Some.contains(APInt(16, 0xaaa)));
314 
315   EXPECT_FALSE(Wrap.isFullSet());
316   EXPECT_FALSE(Wrap.isEmptySet());
317   EXPECT_TRUE(Wrap.isWrappedSet());
318   EXPECT_TRUE(Wrap.contains(APInt(16, 0x0)));
319   EXPECT_TRUE(Wrap.contains(APInt(16, 0x9)));
320   EXPECT_FALSE(Wrap.contains(APInt(16, 0xa)));
321   EXPECT_FALSE(Wrap.contains(APInt(16, 0xaa9)));
322   EXPECT_TRUE(Wrap.contains(APInt(16, 0xaaa)));
323 }
324 
325 TEST_F(ConstantRangeTest, Equality) {
326   EXPECT_EQ(Full, Full);
327   EXPECT_EQ(Empty, Empty);
328   EXPECT_EQ(One, One);
329   EXPECT_EQ(Some, Some);
330   EXPECT_EQ(Wrap, Wrap);
331   EXPECT_NE(Full, Empty);
332   EXPECT_NE(Full, One);
333   EXPECT_NE(Full, Some);
334   EXPECT_NE(Full, Wrap);
335   EXPECT_NE(Empty, One);
336   EXPECT_NE(Empty, Some);
337   EXPECT_NE(Empty, Wrap);
338   EXPECT_NE(One, Some);
339   EXPECT_NE(One, Wrap);
340   EXPECT_NE(Some, Wrap);
341 }
342 
343 TEST_F(ConstantRangeTest, SingleElement) {
344   EXPECT_EQ(Full.getSingleElement(), static_cast<APInt *>(nullptr));
345   EXPECT_EQ(Empty.getSingleElement(), static_cast<APInt *>(nullptr));
346   EXPECT_EQ(Full.getSingleMissingElement(), static_cast<APInt *>(nullptr));
347   EXPECT_EQ(Empty.getSingleMissingElement(), static_cast<APInt *>(nullptr));
348 
349   EXPECT_EQ(*One.getSingleElement(), APInt(16, 0xa));
350   EXPECT_EQ(Some.getSingleElement(), static_cast<APInt *>(nullptr));
351   EXPECT_EQ(Wrap.getSingleElement(), static_cast<APInt *>(nullptr));
352 
353   EXPECT_EQ(One.getSingleMissingElement(), static_cast<APInt *>(nullptr));
354   EXPECT_EQ(Some.getSingleMissingElement(), static_cast<APInt *>(nullptr));
355 
356   ConstantRange OneInverse = One.inverse();
357   EXPECT_EQ(*OneInverse.getSingleMissingElement(), *One.getSingleElement());
358 
359   EXPECT_FALSE(Full.isSingleElement());
360   EXPECT_FALSE(Empty.isSingleElement());
361   EXPECT_TRUE(One.isSingleElement());
362   EXPECT_FALSE(Some.isSingleElement());
363   EXPECT_FALSE(Wrap.isSingleElement());
364 }
365 
366 TEST_F(ConstantRangeTest, GetMinsAndMaxes) {
367   EXPECT_EQ(Full.getUnsignedMax(), APInt(16, UINT16_MAX));
368   EXPECT_EQ(One.getUnsignedMax(), APInt(16, 0xa));
369   EXPECT_EQ(Some.getUnsignedMax(), APInt(16, 0xaa9));
370   EXPECT_EQ(Wrap.getUnsignedMax(), APInt(16, UINT16_MAX));
371 
372   EXPECT_EQ(Full.getUnsignedMin(), APInt(16, 0));
373   EXPECT_EQ(One.getUnsignedMin(), APInt(16, 0xa));
374   EXPECT_EQ(Some.getUnsignedMin(), APInt(16, 0xa));
375   EXPECT_EQ(Wrap.getUnsignedMin(), APInt(16, 0));
376 
377   EXPECT_EQ(Full.getSignedMax(), APInt(16, INT16_MAX));
378   EXPECT_EQ(One.getSignedMax(), APInt(16, 0xa));
379   EXPECT_EQ(Some.getSignedMax(), APInt(16, 0xaa9));
380   EXPECT_EQ(Wrap.getSignedMax(), APInt(16, INT16_MAX));
381 
382   EXPECT_EQ(Full.getSignedMin(), APInt(16, (uint64_t)INT16_MIN));
383   EXPECT_EQ(One.getSignedMin(), APInt(16, 0xa));
384   EXPECT_EQ(Some.getSignedMin(), APInt(16, 0xa));
385   EXPECT_EQ(Wrap.getSignedMin(), APInt(16, (uint64_t)INT16_MIN));
386 
387   // Found by Klee
388   EXPECT_EQ(ConstantRange(APInt(4, 7), APInt(4, 0)).getSignedMax(),
389             APInt(4, 7));
390 }
391 
392 TEST_F(ConstantRangeTest, SignWrapped) {
393   EXPECT_FALSE(Full.isSignWrappedSet());
394   EXPECT_FALSE(Empty.isSignWrappedSet());
395   EXPECT_FALSE(One.isSignWrappedSet());
396   EXPECT_FALSE(Some.isSignWrappedSet());
397   EXPECT_TRUE(Wrap.isSignWrappedSet());
398 
399   EXPECT_FALSE(ConstantRange(APInt(8, 127), APInt(8, 128)).isSignWrappedSet());
400   EXPECT_TRUE(ConstantRange(APInt(8, 127), APInt(8, 129)).isSignWrappedSet());
401   EXPECT_FALSE(ConstantRange(APInt(8, 128), APInt(8, 129)).isSignWrappedSet());
402   EXPECT_TRUE(ConstantRange(APInt(8, 10), APInt(8, 9)).isSignWrappedSet());
403   EXPECT_TRUE(ConstantRange(APInt(8, 10), APInt(8, 250)).isSignWrappedSet());
404   EXPECT_FALSE(ConstantRange(APInt(8, 250), APInt(8, 10)).isSignWrappedSet());
405   EXPECT_FALSE(ConstantRange(APInt(8, 250), APInt(8, 251)).isSignWrappedSet());
406 }
407 
408 TEST_F(ConstantRangeTest, UpperWrapped) {
409   // The behavior here is the same as for isWrappedSet() / isSignWrappedSet().
410   EXPECT_FALSE(Full.isUpperWrapped());
411   EXPECT_FALSE(Empty.isUpperWrapped());
412   EXPECT_FALSE(One.isUpperWrapped());
413   EXPECT_FALSE(Some.isUpperWrapped());
414   EXPECT_TRUE(Wrap.isUpperWrapped());
415   EXPECT_FALSE(Full.isUpperSignWrapped());
416   EXPECT_FALSE(Empty.isUpperSignWrapped());
417   EXPECT_FALSE(One.isUpperSignWrapped());
418   EXPECT_FALSE(Some.isUpperSignWrapped());
419   EXPECT_TRUE(Wrap.isUpperSignWrapped());
420 
421   // The behavior differs if Upper is the Min/SignedMin value.
422   ConstantRange CR1(APInt(8, 42), APInt::getMinValue(8));
423   EXPECT_FALSE(CR1.isWrappedSet());
424   EXPECT_TRUE(CR1.isUpperWrapped());
425 
426   ConstantRange CR2(APInt(8, 42), APInt::getSignedMinValue(8));
427   EXPECT_FALSE(CR2.isSignWrappedSet());
428   EXPECT_TRUE(CR2.isUpperSignWrapped());
429 }
430 
431 TEST_F(ConstantRangeTest, Trunc) {
432   ConstantRange TFull = Full.truncate(10);
433   ConstantRange TEmpty = Empty.truncate(10);
434   ConstantRange TOne = One.truncate(10);
435   ConstantRange TSome = Some.truncate(10);
436   ConstantRange TWrap = Wrap.truncate(10);
437   EXPECT_TRUE(TFull.isFullSet());
438   EXPECT_TRUE(TEmpty.isEmptySet());
439   EXPECT_EQ(TOne, ConstantRange(One.getLower().trunc(10),
440                                 One.getUpper().trunc(10)));
441   EXPECT_TRUE(TSome.isFullSet());
442   EXPECT_TRUE(TWrap.isFullSet());
443 
444   // trunc([2, 5), 3->2) = [2, 1)
445   ConstantRange TwoFive(APInt(3, 2), APInt(3, 5));
446   EXPECT_EQ(TwoFive.truncate(2), ConstantRange(APInt(2, 2), APInt(2, 1)));
447 
448   // trunc([2, 6), 3->2) = full
449   ConstantRange TwoSix(APInt(3, 2), APInt(3, 6));
450   EXPECT_TRUE(TwoSix.truncate(2).isFullSet());
451 
452   // trunc([5, 7), 3->2) = [1, 3)
453   ConstantRange FiveSeven(APInt(3, 5), APInt(3, 7));
454   EXPECT_EQ(FiveSeven.truncate(2), ConstantRange(APInt(2, 1), APInt(2, 3)));
455 
456   // trunc([7, 1), 3->2) = [3, 1)
457   ConstantRange SevenOne(APInt(3, 7), APInt(3, 1));
458   EXPECT_EQ(SevenOne.truncate(2), ConstantRange(APInt(2, 3), APInt(2, 1)));
459 }
460 
461 TEST_F(ConstantRangeTest, ZExt) {
462   ConstantRange ZFull = Full.zeroExtend(20);
463   ConstantRange ZEmpty = Empty.zeroExtend(20);
464   ConstantRange ZOne = One.zeroExtend(20);
465   ConstantRange ZSome = Some.zeroExtend(20);
466   ConstantRange ZWrap = Wrap.zeroExtend(20);
467   EXPECT_EQ(ZFull, ConstantRange(APInt(20, 0), APInt(20, 0x10000)));
468   EXPECT_TRUE(ZEmpty.isEmptySet());
469   EXPECT_EQ(ZOne, ConstantRange(One.getLower().zext(20),
470                                 One.getUpper().zext(20)));
471   EXPECT_EQ(ZSome, ConstantRange(Some.getLower().zext(20),
472                                  Some.getUpper().zext(20)));
473   EXPECT_EQ(ZWrap, ConstantRange(APInt(20, 0), APInt(20, 0x10000)));
474 
475   // zext([5, 0), 3->7) = [5, 8)
476   ConstantRange FiveZero(APInt(3, 5), APInt(3, 0));
477   EXPECT_EQ(FiveZero.zeroExtend(7), ConstantRange(APInt(7, 5), APInt(7, 8)));
478 }
479 
480 TEST_F(ConstantRangeTest, SExt) {
481   ConstantRange SFull = Full.signExtend(20);
482   ConstantRange SEmpty = Empty.signExtend(20);
483   ConstantRange SOne = One.signExtend(20);
484   ConstantRange SSome = Some.signExtend(20);
485   ConstantRange SWrap = Wrap.signExtend(20);
486   EXPECT_EQ(SFull, ConstantRange(APInt(20, (uint64_t)INT16_MIN, true),
487                                  APInt(20, INT16_MAX + 1, true)));
488   EXPECT_TRUE(SEmpty.isEmptySet());
489   EXPECT_EQ(SOne, ConstantRange(One.getLower().sext(20),
490                                 One.getUpper().sext(20)));
491   EXPECT_EQ(SSome, ConstantRange(Some.getLower().sext(20),
492                                  Some.getUpper().sext(20)));
493   EXPECT_EQ(SWrap, ConstantRange(APInt(20, (uint64_t)INT16_MIN, true),
494                                  APInt(20, INT16_MAX + 1, true)));
495 
496   EXPECT_EQ(ConstantRange(APInt(8, 120), APInt(8, 140)).signExtend(16),
497             ConstantRange(APInt(16, -128), APInt(16, 128)));
498 
499   EXPECT_EQ(ConstantRange(APInt(16, 0x0200), APInt(16, 0x8000)).signExtend(19),
500             ConstantRange(APInt(19, 0x0200), APInt(19, 0x8000)));
501 }
502 
503 TEST_F(ConstantRangeTest, IntersectWith) {
504   EXPECT_EQ(Empty.intersectWith(Full), Empty);
505   EXPECT_EQ(Empty.intersectWith(Empty), Empty);
506   EXPECT_EQ(Empty.intersectWith(One), Empty);
507   EXPECT_EQ(Empty.intersectWith(Some), Empty);
508   EXPECT_EQ(Empty.intersectWith(Wrap), Empty);
509   EXPECT_EQ(Full.intersectWith(Full), Full);
510   EXPECT_EQ(Some.intersectWith(Some), Some);
511   EXPECT_EQ(Some.intersectWith(One), One);
512   EXPECT_EQ(Full.intersectWith(One), One);
513   EXPECT_EQ(Full.intersectWith(Some), Some);
514   EXPECT_EQ(Some.intersectWith(Wrap), Empty);
515   EXPECT_EQ(One.intersectWith(Wrap), Empty);
516   EXPECT_EQ(One.intersectWith(Wrap), Wrap.intersectWith(One));
517 
518   // Klee generated testcase from PR4545.
519   // The intersection of i16 [4, 2) and [6, 5) is disjoint, looking like
520   // 01..4.6789ABCDEF where the dots represent values not in the intersection.
521   ConstantRange LHS(APInt(16, 4), APInt(16, 2));
522   ConstantRange RHS(APInt(16, 6), APInt(16, 5));
523   EXPECT_TRUE(LHS.intersectWith(RHS) == LHS);
524 
525   // previous bug: intersection of [min, 3) and [2, max) should be 2
526   LHS = ConstantRange(APInt(32, -2147483646), APInt(32, 3));
527   RHS = ConstantRange(APInt(32, 2), APInt(32, 2147483646));
528   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 2)));
529 
530   // [2, 0) /\ [4, 3) = [2, 0)
531   LHS = ConstantRange(APInt(32, 2), APInt(32, 0));
532   RHS = ConstantRange(APInt(32, 4), APInt(32, 3));
533   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 2), APInt(32, 0)));
534 
535   // [2, 0) /\ [4, 2) = [4, 0)
536   LHS = ConstantRange(APInt(32, 2), APInt(32, 0));
537   RHS = ConstantRange(APInt(32, 4), APInt(32, 2));
538   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 4), APInt(32, 0)));
539 
540   // [4, 2) /\ [5, 1) = [5, 1)
541   LHS = ConstantRange(APInt(32, 4), APInt(32, 2));
542   RHS = ConstantRange(APInt(32, 5), APInt(32, 1));
543   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 5), APInt(32, 1)));
544 
545   // [2, 0) /\ [7, 4) = [7, 4)
546   LHS = ConstantRange(APInt(32, 2), APInt(32, 0));
547   RHS = ConstantRange(APInt(32, 7), APInt(32, 4));
548   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 7), APInt(32, 4)));
549 
550   // [4, 2) /\ [1, 0) = [1, 0)
551   LHS = ConstantRange(APInt(32, 4), APInt(32, 2));
552   RHS = ConstantRange(APInt(32, 1), APInt(32, 0));
553   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 4), APInt(32, 2)));
554 
555   // [15, 0) /\ [7, 6) = [15, 0)
556   LHS = ConstantRange(APInt(32, 15), APInt(32, 0));
557   RHS = ConstantRange(APInt(32, 7), APInt(32, 6));
558   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 15), APInt(32, 0)));
559 }
560 
561 template<typename Fn1, typename Fn2>
562 void testBinarySetOperationExhaustive(Fn1 OpFn, Fn2 InResultFn) {
563   unsigned Bits = 4;
564   EnumerateTwoConstantRanges(Bits,
565       [=](const ConstantRange &CR1, const ConstantRange &CR2) {
566         SmallBitVector Elems(1 << Bits);
567         APInt Num(Bits, 0);
568         for (unsigned I = 0, Limit = 1 << Bits; I < Limit; ++I, ++Num)
569           if (InResultFn(CR1, CR2, Num))
570             Elems.set(Num.getZExtValue());
571 
572         ConstantRange SmallestCR = OpFn(CR1, CR2, ConstantRange::Smallest);
573         TestRange(SmallestCR, Elems, PreferSmallest, {CR1, CR2});
574 
575         ConstantRange UnsignedCR = OpFn(CR1, CR2, ConstantRange::Unsigned);
576         TestRange(UnsignedCR, Elems, PreferSmallestNonFullUnsigned, {CR1, CR2});
577 
578         ConstantRange SignedCR = OpFn(CR1, CR2, ConstantRange::Signed);
579         TestRange(SignedCR, Elems, PreferSmallestNonFullSigned, {CR1, CR2});
580       });
581 }
582 
583 TEST_F(ConstantRangeTest, IntersectWithExhaustive) {
584   testBinarySetOperationExhaustive(
585       [](const ConstantRange &CR1, const ConstantRange &CR2,
586          ConstantRange::PreferredRangeType Type) {
587         return CR1.intersectWith(CR2, Type);
588       },
589       [](const ConstantRange &CR1, const ConstantRange &CR2, const APInt &N) {
590         return CR1.contains(N) && CR2.contains(N);
591       });
592 }
593 
594 TEST_F(ConstantRangeTest, UnionWithExhaustive) {
595   testBinarySetOperationExhaustive(
596       [](const ConstantRange &CR1, const ConstantRange &CR2,
597          ConstantRange::PreferredRangeType Type) {
598         return CR1.unionWith(CR2, Type);
599       },
600       [](const ConstantRange &CR1, const ConstantRange &CR2, const APInt &N) {
601         return CR1.contains(N) || CR2.contains(N);
602       });
603 }
604 
605 TEST_F(ConstantRangeTest, UnionWith) {
606   EXPECT_EQ(Wrap.unionWith(One),
607             ConstantRange(APInt(16, 0xaaa), APInt(16, 0xb)));
608   EXPECT_EQ(One.unionWith(Wrap), Wrap.unionWith(One));
609   EXPECT_EQ(Empty.unionWith(Empty), Empty);
610   EXPECT_EQ(Full.unionWith(Full), Full);
611   EXPECT_EQ(Some.unionWith(Wrap), Full);
612 
613   // PR4545
614   EXPECT_EQ(ConstantRange(APInt(16, 14), APInt(16, 1)).unionWith(
615                                     ConstantRange(APInt(16, 0), APInt(16, 8))),
616             ConstantRange(APInt(16, 14), APInt(16, 8)));
617   EXPECT_EQ(ConstantRange(APInt(16, 6), APInt(16, 4)).unionWith(
618                                     ConstantRange(APInt(16, 4), APInt(16, 0))),
619             ConstantRange::getFull(16));
620   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 0)).unionWith(
621                                     ConstantRange(APInt(16, 2), APInt(16, 1))),
622             ConstantRange::getFull(16));
623 }
624 
625 TEST_F(ConstantRangeTest, SetDifference) {
626   EXPECT_EQ(Full.difference(Empty), Full);
627   EXPECT_EQ(Full.difference(Full), Empty);
628   EXPECT_EQ(Empty.difference(Empty), Empty);
629   EXPECT_EQ(Empty.difference(Full), Empty);
630 
631   ConstantRange A(APInt(16, 3), APInt(16, 7));
632   ConstantRange B(APInt(16, 5), APInt(16, 9));
633   ConstantRange C(APInt(16, 3), APInt(16, 5));
634   ConstantRange D(APInt(16, 7), APInt(16, 9));
635   ConstantRange E(APInt(16, 5), APInt(16, 4));
636   ConstantRange F(APInt(16, 7), APInt(16, 3));
637   EXPECT_EQ(A.difference(B), C);
638   EXPECT_EQ(B.difference(A), D);
639   EXPECT_EQ(E.difference(A), F);
640 }
641 
642 TEST_F(ConstantRangeTest, getActiveBits) {
643   unsigned Bits = 4;
644   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
645     unsigned Exact = 0;
646     ForeachNumInConstantRange(CR, [&](const APInt &N) {
647       Exact = std::max(Exact, N.getActiveBits());
648     });
649 
650     unsigned ResultCR = CR.getActiveBits();
651     EXPECT_EQ(Exact, ResultCR);
652   });
653 }
654 TEST_F(ConstantRangeTest, losslessUnsignedTruncationZeroext) {
655   unsigned Bits = 4;
656   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
657     unsigned MinBitWidth = CR.getActiveBits();
658     if (MinBitWidth == 0) {
659       EXPECT_TRUE(CR.isEmptySet() ||
660                   (CR.isSingleElement() && CR.getSingleElement()->isZero()));
661       return;
662     }
663     if (MinBitWidth == Bits)
664       return;
665     EXPECT_EQ(CR, CR.truncate(MinBitWidth).zeroExtend(Bits));
666   });
667 }
668 
669 TEST_F(ConstantRangeTest, getMinSignedBits) {
670   unsigned Bits = 4;
671   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
672     unsigned Exact = 0;
673     ForeachNumInConstantRange(CR, [&](const APInt &N) {
674       Exact = std::max(Exact, N.getMinSignedBits());
675     });
676 
677     unsigned ResultCR = CR.getMinSignedBits();
678     EXPECT_EQ(Exact, ResultCR);
679   });
680 }
681 TEST_F(ConstantRangeTest, losslessSignedTruncationSignext) {
682   unsigned Bits = 4;
683   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
684     unsigned MinBitWidth = CR.getMinSignedBits();
685     if (MinBitWidth == 0) {
686       EXPECT_TRUE(CR.isEmptySet());
687       return;
688     }
689     if (MinBitWidth == Bits)
690       return;
691     EXPECT_EQ(CR, CR.truncate(MinBitWidth).signExtend(Bits));
692   });
693 }
694 
695 TEST_F(ConstantRangeTest, SubtractAPInt) {
696   EXPECT_EQ(Full.subtract(APInt(16, 4)), Full);
697   EXPECT_EQ(Empty.subtract(APInt(16, 4)), Empty);
698   EXPECT_EQ(Some.subtract(APInt(16, 4)),
699             ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6)));
700   EXPECT_EQ(Wrap.subtract(APInt(16, 4)),
701             ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6)));
702   EXPECT_EQ(One.subtract(APInt(16, 4)),
703             ConstantRange(APInt(16, 0x6)));
704 }
705 
706 TEST_F(ConstantRangeTest, Add) {
707   EXPECT_EQ(Full.add(APInt(16, 4)), Full);
708   EXPECT_EQ(Full.add(Full), Full);
709   EXPECT_EQ(Full.add(Empty), Empty);
710   EXPECT_EQ(Full.add(One), Full);
711   EXPECT_EQ(Full.add(Some), Full);
712   EXPECT_EQ(Full.add(Wrap), Full);
713   EXPECT_EQ(Empty.add(Empty), Empty);
714   EXPECT_EQ(Empty.add(One), Empty);
715   EXPECT_EQ(Empty.add(Some), Empty);
716   EXPECT_EQ(Empty.add(Wrap), Empty);
717   EXPECT_EQ(Empty.add(APInt(16, 4)), Empty);
718   EXPECT_EQ(Some.add(APInt(16, 4)),
719             ConstantRange(APInt(16, 0xe), APInt(16, 0xaae)));
720   EXPECT_EQ(Wrap.add(APInt(16, 4)),
721             ConstantRange(APInt(16, 0xaae), APInt(16, 0xe)));
722   EXPECT_EQ(One.add(APInt(16, 4)),
723             ConstantRange(APInt(16, 0xe)));
724 
725   TestBinaryOpExhaustive(
726       [](const ConstantRange &CR1, const ConstantRange &CR2) {
727         return CR1.add(CR2);
728       },
729       [](const APInt &N1, const APInt &N2) {
730         return N1 + N2;
731       });
732 }
733 
734 template <typename Fn1, typename Fn2>
735 static void TestAddWithNoSignedWrapExhaustive(Fn1 RangeFn, Fn2 IntFn) {
736   unsigned Bits = 4;
737   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
738                                        const ConstantRange &CR2) {
739     ConstantRange CR = RangeFn(CR1, CR2);
740     SignedOpRangeGatherer R(CR.getBitWidth());
741     bool AllOverflow = true;
742     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
743       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
744         bool IsOverflow = false;
745         APInt N = IntFn(IsOverflow, N1, N2);
746         if (!IsOverflow) {
747           AllOverflow = false;
748           R.account(N);
749           EXPECT_TRUE(CR.contains(N));
750         }
751       });
752     });
753 
754     EXPECT_EQ(CR.isEmptySet(), AllOverflow);
755 
756     if (CR1.isSignWrappedSet() || CR2.isSignWrappedSet())
757       return;
758 
759     ConstantRange Exact = R.getRange();
760     EXPECT_EQ(Exact, CR);
761   });
762 }
763 
764 template <typename Fn1, typename Fn2>
765 static void TestAddWithNoUnsignedWrapExhaustive(Fn1 RangeFn, Fn2 IntFn) {
766   unsigned Bits = 4;
767   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
768                                        const ConstantRange &CR2) {
769     ConstantRange CR = RangeFn(CR1, CR2);
770     UnsignedOpRangeGatherer R(CR.getBitWidth());
771     bool AllOverflow = true;
772     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
773       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
774         bool IsOverflow = false;
775         APInt N = IntFn(IsOverflow, N1, N2);
776         if (!IsOverflow) {
777           AllOverflow = false;
778           R.account(N);
779           EXPECT_TRUE(CR.contains(N));
780         }
781       });
782     });
783 
784     EXPECT_EQ(CR.isEmptySet(), AllOverflow);
785 
786     if (CR1.isWrappedSet() || CR2.isWrappedSet())
787       return;
788 
789     ConstantRange Exact = R.getRange();
790     EXPECT_EQ(Exact, CR);
791   });
792 }
793 
794 template <typename Fn1, typename Fn2, typename Fn3>
795 static void TestAddWithNoSignedUnsignedWrapExhaustive(Fn1 RangeFn,
796                                                       Fn2 IntFnSigned,
797                                                       Fn3 IntFnUnsigned) {
798   unsigned Bits = 4;
799   EnumerateTwoConstantRanges(
800       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
801         ConstantRange CR = RangeFn(CR1, CR2);
802         UnsignedOpRangeGatherer UR(CR.getBitWidth());
803         SignedOpRangeGatherer SR(CR.getBitWidth());
804         bool AllOverflow = true;
805         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
806           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
807             bool IsOverflow = false, IsSignedOverflow = false;
808             APInt N = IntFnSigned(IsSignedOverflow, N1, N2);
809             (void) IntFnUnsigned(IsOverflow, N1, N2);
810             if (!IsSignedOverflow && !IsOverflow) {
811               AllOverflow = false;
812               UR.account(N);
813               SR.account(N);
814               EXPECT_TRUE(CR.contains(N));
815             }
816           });
817         });
818 
819         EXPECT_EQ(CR.isEmptySet(), AllOverflow);
820 
821         if (CR1.isWrappedSet() || CR2.isWrappedSet() ||
822             CR1.isSignWrappedSet() || CR2.isSignWrappedSet())
823           return;
824 
825         ConstantRange ExactUnsignedCR = UR.getRange();
826         ConstantRange ExactSignedCR = SR.getRange();
827 
828         if (ExactUnsignedCR.isEmptySet() || ExactSignedCR.isEmptySet()) {
829           EXPECT_TRUE(CR.isEmptySet());
830           return;
831         }
832 
833         ConstantRange Exact = ExactSignedCR.intersectWith(ExactUnsignedCR);
834         EXPECT_EQ(Exact, CR);
835       });
836 }
837 
838 TEST_F(ConstantRangeTest, AddWithNoWrap) {
839   typedef OverflowingBinaryOperator OBO;
840   EXPECT_EQ(Empty.addWithNoWrap(Some, OBO::NoSignedWrap), Empty);
841   EXPECT_EQ(Some.addWithNoWrap(Empty, OBO::NoSignedWrap), Empty);
842   EXPECT_EQ(Full.addWithNoWrap(Full, OBO::NoSignedWrap), Full);
843   EXPECT_NE(Full.addWithNoWrap(Some, OBO::NoSignedWrap), Full);
844   EXPECT_NE(Some.addWithNoWrap(Full, OBO::NoSignedWrap), Full);
845   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, 1), APInt(16, 2)),
846                                OBO::NoSignedWrap),
847             ConstantRange(APInt(16, INT16_MIN + 1), APInt(16, INT16_MIN)));
848   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 2))
849                 .addWithNoWrap(Full, OBO::NoSignedWrap),
850             ConstantRange(APInt(16, INT16_MIN + 1), APInt(16, INT16_MIN)));
851   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, -1), APInt(16, 0)),
852                                OBO::NoSignedWrap),
853             ConstantRange(APInt(16, INT16_MIN), APInt(16, INT16_MAX)));
854   EXPECT_EQ(ConstantRange(APInt(8, 100), APInt(8, 120))
855                 .addWithNoWrap(ConstantRange(APInt(8, 120), APInt(8, 123)),
856                                OBO::NoSignedWrap),
857             ConstantRange(8, false));
858   EXPECT_EQ(ConstantRange(APInt(8, -120), APInt(8, -100))
859                 .addWithNoWrap(ConstantRange(APInt(8, -110), APInt(8, -100)),
860                                OBO::NoSignedWrap),
861             ConstantRange(8, false));
862   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
863                 .addWithNoWrap(ConstantRange(APInt(8, -128), APInt(8, 28)),
864                                OBO::NoSignedWrap),
865             ConstantRange(8, true));
866   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
867                 .addWithNoWrap(ConstantRange(APInt(8, -120), APInt(8, 29)),
868                                OBO::NoSignedWrap),
869             ConstantRange(APInt(8, -120), APInt(8, -128)));
870   EXPECT_EQ(ConstantRange(APInt(8, -50), APInt(8, 50))
871                 .addWithNoWrap(ConstantRange(APInt(8, 10), APInt(8, 20)),
872                                OBO::NoSignedWrap),
873             ConstantRange(APInt(8, -40), APInt(8, 69)));
874   EXPECT_EQ(ConstantRange(APInt(8, 10), APInt(8, 20))
875                 .addWithNoWrap(ConstantRange(APInt(8, -50), APInt(8, 50)),
876                                OBO::NoSignedWrap),
877             ConstantRange(APInt(8, -40), APInt(8, 69)));
878   EXPECT_EQ(ConstantRange(APInt(8, 120), APInt(8, -10))
879                 .addWithNoWrap(ConstantRange(APInt(8, 5), APInt(8, 20)),
880                                OBO::NoSignedWrap),
881             ConstantRange(APInt(8, 125), APInt(8, 9)));
882   EXPECT_EQ(ConstantRange(APInt(8, 5), APInt(8, 20))
883                 .addWithNoWrap(ConstantRange(APInt(8, 120), APInt(8, -10)),
884                                OBO::NoSignedWrap),
885             ConstantRange(APInt(8, 125), APInt(8, 9)));
886 
887   TestAddWithNoSignedWrapExhaustive(
888       [](const ConstantRange &CR1, const ConstantRange &CR2) {
889         return CR1.addWithNoWrap(CR2, OBO::NoSignedWrap);
890       },
891       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
892         return N1.sadd_ov(N2, IsOverflow);
893       });
894 
895   EXPECT_EQ(Empty.addWithNoWrap(Some, OBO::NoUnsignedWrap), Empty);
896   EXPECT_EQ(Some.addWithNoWrap(Empty, OBO::NoUnsignedWrap), Empty);
897   EXPECT_EQ(Full.addWithNoWrap(Full, OBO::NoUnsignedWrap), Full);
898   EXPECT_NE(Full.addWithNoWrap(Some, OBO::NoUnsignedWrap), Full);
899   EXPECT_NE(Some.addWithNoWrap(Full, OBO::NoUnsignedWrap), Full);
900   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, 1), APInt(16, 2)),
901                                OBO::NoUnsignedWrap),
902             ConstantRange(APInt(16, 1), APInt(16, 0)));
903   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 2))
904                 .addWithNoWrap(Full, OBO::NoUnsignedWrap),
905             ConstantRange(APInt(16, 1), APInt(16, 0)));
906   EXPECT_EQ(ConstantRange(APInt(8, 200), APInt(8, 220))
907                 .addWithNoWrap(ConstantRange(APInt(8, 100), APInt(8, 123)),
908                                OBO::NoUnsignedWrap),
909             ConstantRange(8, false));
910   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
911                 .addWithNoWrap(ConstantRange(APInt(8, 0), APInt(8, 156)),
912                                OBO::NoUnsignedWrap),
913             ConstantRange(8, true));
914   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
915                 .addWithNoWrap(ConstantRange(APInt(8, 10), APInt(8, 29)),
916                                OBO::NoUnsignedWrap),
917             ConstantRange(APInt(8, 10), APInt(8, 129)));
918   EXPECT_EQ(ConstantRange(APInt(8, 20), APInt(8, 10))
919                 .addWithNoWrap(ConstantRange(APInt(8, 50), APInt(8, 200)),
920                                OBO::NoUnsignedWrap),
921             ConstantRange(APInt(8, 50), APInt(8, 0)));
922   EXPECT_EQ(ConstantRange(APInt(8, 10), APInt(8, 20))
923                 .addWithNoWrap(ConstantRange(APInt(8, 50), APInt(8, 200)),
924                                OBO::NoUnsignedWrap),
925             ConstantRange(APInt(8, 60), APInt(8, -37)));
926   EXPECT_EQ(ConstantRange(APInt(8, 20), APInt(8, -30))
927                 .addWithNoWrap(ConstantRange(APInt(8, 5), APInt(8, 20)),
928                                OBO::NoUnsignedWrap),
929             ConstantRange(APInt(8, 25), APInt(8, -11)));
930   EXPECT_EQ(ConstantRange(APInt(8, 5), APInt(8, 20))
931                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, -30)),
932                                OBO::NoUnsignedWrap),
933             ConstantRange(APInt(8, 25), APInt(8, -11)));
934 
935   TestAddWithNoUnsignedWrapExhaustive(
936       [](const ConstantRange &CR1, const ConstantRange &CR2) {
937         return CR1.addWithNoWrap(CR2, OBO::NoUnsignedWrap);
938       },
939       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
940         return N1.uadd_ov(N2, IsOverflow);
941       });
942 
943   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
944                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
945                                OBO::NoSignedWrap),
946             ConstantRange(APInt(8, 70), APInt(8, -128)));
947   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
948                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
949                                OBO::NoUnsignedWrap),
950             ConstantRange(APInt(8, 70), APInt(8, 169)));
951   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
952                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
953                                OBO::NoUnsignedWrap | OBO::NoSignedWrap),
954             ConstantRange(APInt(8, 70), APInt(8, -128)));
955 
956   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
957                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
958                                OBO::NoSignedWrap),
959             ConstantRange(APInt(8, -80), APInt(8, -21)));
960   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
961                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
962                                OBO::NoUnsignedWrap),
963             ConstantRange(APInt(8, 176), APInt(8, 235)));
964   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
965                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
966                                OBO::NoUnsignedWrap | OBO::NoSignedWrap),
967             ConstantRange(APInt(8, 176), APInt(8, 235)));
968 
969   TestAddWithNoSignedUnsignedWrapExhaustive(
970       [](const ConstantRange &CR1, const ConstantRange &CR2) {
971         return CR1.addWithNoWrap(CR2, OBO::NoUnsignedWrap | OBO::NoSignedWrap);
972       },
973       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
974         return N1.sadd_ov(N2, IsOverflow);
975       },
976       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
977         return N1.uadd_ov(N2, IsOverflow);
978       });
979 }
980 
981 TEST_F(ConstantRangeTest, Sub) {
982   EXPECT_EQ(Full.sub(APInt(16, 4)), Full);
983   EXPECT_EQ(Full.sub(Full), Full);
984   EXPECT_EQ(Full.sub(Empty), Empty);
985   EXPECT_EQ(Full.sub(One), Full);
986   EXPECT_EQ(Full.sub(Some), Full);
987   EXPECT_EQ(Full.sub(Wrap), Full);
988   EXPECT_EQ(Empty.sub(Empty), Empty);
989   EXPECT_EQ(Empty.sub(One), Empty);
990   EXPECT_EQ(Empty.sub(Some), Empty);
991   EXPECT_EQ(Empty.sub(Wrap), Empty);
992   EXPECT_EQ(Empty.sub(APInt(16, 4)), Empty);
993   EXPECT_EQ(Some.sub(APInt(16, 4)),
994             ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6)));
995   EXPECT_EQ(Some.sub(Some),
996             ConstantRange(APInt(16, 0xf561), APInt(16, 0xaa0)));
997   EXPECT_EQ(Wrap.sub(APInt(16, 4)),
998             ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6)));
999   EXPECT_EQ(One.sub(APInt(16, 4)),
1000             ConstantRange(APInt(16, 0x6)));
1001 
1002   TestBinaryOpExhaustive(
1003       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1004         return CR1.sub(CR2);
1005       },
1006       [](const APInt &N1, const APInt &N2) {
1007         return N1 - N2;
1008       });
1009 }
1010 
1011 TEST_F(ConstantRangeTest, SubWithNoWrap) {
1012   typedef OverflowingBinaryOperator OBO;
1013   TestAddWithNoSignedWrapExhaustive(
1014       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1015         return CR1.subWithNoWrap(CR2, OBO::NoSignedWrap);
1016       },
1017       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1018         return N1.ssub_ov(N2, IsOverflow);
1019       });
1020   TestAddWithNoUnsignedWrapExhaustive(
1021       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1022         return CR1.subWithNoWrap(CR2, OBO::NoUnsignedWrap);
1023       },
1024       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1025         return N1.usub_ov(N2, IsOverflow);
1026       });
1027   TestAddWithNoSignedUnsignedWrapExhaustive(
1028       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1029         return CR1.subWithNoWrap(CR2, OBO::NoUnsignedWrap | OBO::NoSignedWrap);
1030       },
1031       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1032         return N1.ssub_ov(N2, IsOverflow);
1033       },
1034       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1035         return N1.usub_ov(N2, IsOverflow);
1036       });
1037 }
1038 
1039 TEST_F(ConstantRangeTest, Multiply) {
1040   EXPECT_EQ(Full.multiply(Full), Full);
1041   EXPECT_EQ(Full.multiply(Empty), Empty);
1042   EXPECT_EQ(Full.multiply(One), Full);
1043   EXPECT_EQ(Full.multiply(Some), Full);
1044   EXPECT_EQ(Full.multiply(Wrap), Full);
1045   EXPECT_EQ(Empty.multiply(Empty), Empty);
1046   EXPECT_EQ(Empty.multiply(One), Empty);
1047   EXPECT_EQ(Empty.multiply(Some), Empty);
1048   EXPECT_EQ(Empty.multiply(Wrap), Empty);
1049   EXPECT_EQ(One.multiply(One), ConstantRange(APInt(16, 0xa*0xa),
1050                                              APInt(16, 0xa*0xa + 1)));
1051   EXPECT_EQ(One.multiply(Some), ConstantRange(APInt(16, 0xa*0xa),
1052                                               APInt(16, 0xa*0xaa9 + 1)));
1053   EXPECT_EQ(One.multiply(Wrap), Full);
1054   EXPECT_EQ(Some.multiply(Some), Full);
1055   EXPECT_EQ(Some.multiply(Wrap), Full);
1056   EXPECT_EQ(Wrap.multiply(Wrap), Full);
1057 
1058   ConstantRange Zero(APInt(16, 0));
1059   EXPECT_EQ(Zero.multiply(Full), Zero);
1060   EXPECT_EQ(Zero.multiply(Some), Zero);
1061   EXPECT_EQ(Zero.multiply(Wrap), Zero);
1062   EXPECT_EQ(Full.multiply(Zero), Zero);
1063   EXPECT_EQ(Some.multiply(Zero), Zero);
1064   EXPECT_EQ(Wrap.multiply(Zero), Zero);
1065 
1066   // http://llvm.org/PR4545
1067   EXPECT_EQ(ConstantRange(APInt(4, 1), APInt(4, 6)).multiply(
1068                 ConstantRange(APInt(4, 6), APInt(4, 2))),
1069             ConstantRange(4, /*isFullSet=*/true));
1070 
1071   EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 0)).multiply(
1072               ConstantRange(APInt(8, 252), APInt(8, 4))),
1073             ConstantRange(APInt(8, 250), APInt(8, 9)));
1074   EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 255)).multiply(
1075               ConstantRange(APInt(8, 2), APInt(8, 4))),
1076             ConstantRange(APInt(8, 250), APInt(8, 253)));
1077 
1078   // TODO: This should be return [-2, 0]
1079   EXPECT_EQ(ConstantRange(APInt(8, -2)).multiply(
1080               ConstantRange(APInt(8, 0), APInt(8, 2))),
1081             ConstantRange(APInt(8, -2), APInt(8, 1)));
1082 }
1083 
1084 TEST_F(ConstantRangeTest, smul_fast) {
1085   TestBinaryOpExhaustive(
1086       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1087         return CR1.smul_fast(CR2);
1088       },
1089       [](const APInt &N1, const APInt &N2) {
1090         return N1 * N2;
1091       },
1092       PreferSmallest,
1093       [](const ConstantRange &, const ConstantRange &) {
1094         return false; // Check correctness only.
1095       });
1096 }
1097 
1098 TEST_F(ConstantRangeTest, UMax) {
1099   EXPECT_EQ(Full.umax(Full), Full);
1100   EXPECT_EQ(Full.umax(Empty), Empty);
1101   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1102   EXPECT_EQ(Full.umax(Wrap), Full);
1103   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1104   EXPECT_EQ(Empty.umax(Empty), Empty);
1105   EXPECT_EQ(Empty.umax(Some), Empty);
1106   EXPECT_EQ(Empty.umax(Wrap), Empty);
1107   EXPECT_EQ(Empty.umax(One), Empty);
1108   EXPECT_EQ(Some.umax(Some), Some);
1109   EXPECT_EQ(Some.umax(Wrap), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1110   EXPECT_EQ(Some.umax(One), Some);
1111   EXPECT_EQ(Wrap.umax(Wrap), Wrap);
1112   EXPECT_EQ(Wrap.umax(One), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1113   EXPECT_EQ(One.umax(One), One);
1114 
1115   TestBinaryOpExhaustive(
1116       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1117         return CR1.umax(CR2);
1118       },
1119       [](const APInt &N1, const APInt &N2) {
1120         return APIntOps::umax(N1, N2);
1121       },
1122       PreferSmallestNonFullUnsigned);
1123 }
1124 
1125 TEST_F(ConstantRangeTest, SMax) {
1126   EXPECT_EQ(Full.smax(Full), Full);
1127   EXPECT_EQ(Full.smax(Empty), Empty);
1128   EXPECT_EQ(Full.smax(Some), ConstantRange(APInt(16, 0xa),
1129                                            APInt::getSignedMinValue(16)));
1130   EXPECT_EQ(Full.smax(Wrap), Full);
1131   EXPECT_EQ(Full.smax(One), ConstantRange(APInt(16, 0xa),
1132                                           APInt::getSignedMinValue(16)));
1133   EXPECT_EQ(Empty.smax(Empty), Empty);
1134   EXPECT_EQ(Empty.smax(Some), Empty);
1135   EXPECT_EQ(Empty.smax(Wrap), Empty);
1136   EXPECT_EQ(Empty.smax(One), Empty);
1137   EXPECT_EQ(Some.smax(Some), Some);
1138   EXPECT_EQ(Some.smax(Wrap), ConstantRange(APInt(16, 0xa),
1139                                            APInt(16, (uint64_t)INT16_MIN)));
1140   EXPECT_EQ(Some.smax(One), Some);
1141   EXPECT_EQ(Wrap.smax(One), ConstantRange(APInt(16, 0xa),
1142                                           APInt(16, (uint64_t)INT16_MIN)));
1143   EXPECT_EQ(One.smax(One), One);
1144 
1145   TestBinaryOpExhaustive(
1146       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1147         return CR1.smax(CR2);
1148       },
1149       [](const APInt &N1, const APInt &N2) {
1150         return APIntOps::smax(N1, N2);
1151       },
1152       PreferSmallestNonFullSigned);
1153 }
1154 
1155 TEST_F(ConstantRangeTest, UMin) {
1156   EXPECT_EQ(Full.umin(Full), Full);
1157   EXPECT_EQ(Full.umin(Empty), Empty);
1158   EXPECT_EQ(Full.umin(Some), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1159   EXPECT_EQ(Full.umin(Wrap), Full);
1160   EXPECT_EQ(Empty.umin(Empty), Empty);
1161   EXPECT_EQ(Empty.umin(Some), Empty);
1162   EXPECT_EQ(Empty.umin(Wrap), Empty);
1163   EXPECT_EQ(Empty.umin(One), Empty);
1164   EXPECT_EQ(Some.umin(Some), Some);
1165   EXPECT_EQ(Some.umin(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1166   EXPECT_EQ(Some.umin(One), One);
1167   EXPECT_EQ(Wrap.umin(Wrap), Wrap);
1168   EXPECT_EQ(Wrap.umin(One), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1169   EXPECT_EQ(One.umin(One), One);
1170 
1171   TestBinaryOpExhaustive(
1172       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1173         return CR1.umin(CR2);
1174       },
1175       [](const APInt &N1, const APInt &N2) {
1176         return APIntOps::umin(N1, N2);
1177       },
1178       PreferSmallestNonFullUnsigned);
1179 }
1180 
1181 TEST_F(ConstantRangeTest, SMin) {
1182   EXPECT_EQ(Full.smin(Full), Full);
1183   EXPECT_EQ(Full.smin(Empty), Empty);
1184   EXPECT_EQ(Full.smin(Some), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1185                                            APInt(16, 0xaaa)));
1186   EXPECT_EQ(Full.smin(Wrap), Full);
1187   EXPECT_EQ(Empty.smin(Empty), Empty);
1188   EXPECT_EQ(Empty.smin(Some), Empty);
1189   EXPECT_EQ(Empty.smin(Wrap), Empty);
1190   EXPECT_EQ(Empty.smin(One), Empty);
1191   EXPECT_EQ(Some.smin(Some), Some);
1192   EXPECT_EQ(Some.smin(Wrap), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1193                                            APInt(16, 0xaaa)));
1194   EXPECT_EQ(Some.smin(One), One);
1195   EXPECT_EQ(Wrap.smin(Wrap), Wrap);
1196   EXPECT_EQ(Wrap.smin(One), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1197                                           APInt(16, 0xb)));
1198   EXPECT_EQ(One.smin(One), One);
1199 
1200   TestBinaryOpExhaustive(
1201       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1202         return CR1.smin(CR2);
1203       },
1204       [](const APInt &N1, const APInt &N2) {
1205         return APIntOps::smin(N1, N2);
1206       },
1207       PreferSmallestNonFullSigned);
1208 }
1209 
1210 TEST_F(ConstantRangeTest, UDiv) {
1211   EXPECT_EQ(Full.udiv(Full), Full);
1212   EXPECT_EQ(Full.udiv(Empty), Empty);
1213   EXPECT_EQ(Full.udiv(One), ConstantRange(APInt(16, 0),
1214                                           APInt(16, 0xffff / 0xa + 1)));
1215   EXPECT_EQ(Full.udiv(Some), ConstantRange(APInt(16, 0),
1216                                            APInt(16, 0xffff / 0xa + 1)));
1217   EXPECT_EQ(Full.udiv(Wrap), Full);
1218   EXPECT_EQ(Empty.udiv(Empty), Empty);
1219   EXPECT_EQ(Empty.udiv(One), Empty);
1220   EXPECT_EQ(Empty.udiv(Some), Empty);
1221   EXPECT_EQ(Empty.udiv(Wrap), Empty);
1222   EXPECT_EQ(One.udiv(One), ConstantRange(APInt(16, 1)));
1223   EXPECT_EQ(One.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 2)));
1224   EXPECT_EQ(One.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1225   EXPECT_EQ(Some.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 0x111)));
1226   EXPECT_EQ(Some.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1227   EXPECT_EQ(Wrap.udiv(Wrap), Full);
1228 
1229 
1230   ConstantRange Zero(APInt(16, 0));
1231   EXPECT_EQ(Zero.udiv(One), Zero);
1232   EXPECT_EQ(Zero.udiv(Full), Zero);
1233 
1234   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 99)).udiv(Full),
1235             ConstantRange(APInt(16, 0), APInt(16, 99)));
1236   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 99)).udiv(Full),
1237             ConstantRange(APInt(16, 0), APInt(16, 99)));
1238 }
1239 
1240 TEST_F(ConstantRangeTest, SDiv) {
1241   unsigned Bits = 4;
1242   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
1243                                        const ConstantRange &CR2) {
1244     // Collect possible results in a bit vector. We store the signed value plus
1245     // a bias to make it unsigned.
1246     int Bias = 1 << (Bits - 1);
1247     BitVector Results(1 << Bits);
1248     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1249       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
1250         // Division by zero is UB.
1251         if (N2 == 0)
1252           return;
1253 
1254         // SignedMin / -1 is UB.
1255         if (N1.isMinSignedValue() && N2.isAllOnes())
1256           return;
1257 
1258         APInt N = N1.sdiv(N2);
1259         Results.set(N.getSExtValue() + Bias);
1260       });
1261     });
1262 
1263     ConstantRange CR = CR1.sdiv(CR2);
1264     if (Results.none()) {
1265       EXPECT_TRUE(CR.isEmptySet());
1266       return;
1267     }
1268 
1269     // If there is a non-full signed envelope, that should be the result.
1270     APInt SMin(Bits, Results.find_first() - Bias);
1271     APInt SMax(Bits, Results.find_last() - Bias);
1272     ConstantRange Envelope = ConstantRange::getNonEmpty(SMin, SMax + 1);
1273     if (!Envelope.isFullSet()) {
1274       EXPECT_EQ(Envelope, CR);
1275       return;
1276     }
1277 
1278     // If the signed envelope is a full set, try to find a smaller sign wrapped
1279     // set that is separated in negative and positive components (or one which
1280     // can also additionally contain zero).
1281     int LastNeg = Results.find_last_in(0, Bias) - Bias;
1282     int LastPos = Results.find_next(Bias) - Bias;
1283     if (Results[Bias]) {
1284       if (LastNeg == -1)
1285         ++LastNeg;
1286       else if (LastPos == 1)
1287         --LastPos;
1288     }
1289 
1290     APInt WMax(Bits, LastNeg);
1291     APInt WMin(Bits, LastPos);
1292     ConstantRange Wrapped = ConstantRange::getNonEmpty(WMin, WMax + 1);
1293     EXPECT_EQ(Wrapped, CR);
1294   });
1295 }
1296 
1297 TEST_F(ConstantRangeTest, URem) {
1298   EXPECT_EQ(Full.urem(Empty), Empty);
1299   EXPECT_EQ(Empty.urem(Full), Empty);
1300   // urem by zero is poison.
1301   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0))), Empty);
1302   // urem by full range doesn't contain MaxValue.
1303   EXPECT_EQ(Full.urem(Full), ConstantRange(APInt(16, 0), APInt(16, 0xffff)));
1304   // urem is upper bounded by maximum RHS minus one.
1305   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0), APInt(16, 123))),
1306             ConstantRange(APInt(16, 0), APInt(16, 122)));
1307   // urem is upper bounded by maximum LHS.
1308   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 123)).urem(Full),
1309             ConstantRange(APInt(16, 0), APInt(16, 123)));
1310   // If the LHS is always lower than the RHS, the result is the LHS.
1311   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1312                 .urem(ConstantRange(APInt(16, 20), APInt(16, 30))),
1313             ConstantRange(APInt(16, 10), APInt(16, 20)));
1314   // It has to be strictly lower, otherwise the top value may wrap to zero.
1315   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1316                 .urem(ConstantRange(APInt(16, 19), APInt(16, 30))),
1317             ConstantRange(APInt(16, 0), APInt(16, 20)));
1318   // [12, 14] % 10 is [2, 4], but we conservatively compute [0, 9].
1319   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1320                 .urem(ConstantRange(APInt(16, 10))),
1321             ConstantRange(APInt(16, 0), APInt(16, 10)));
1322 
1323   TestBinaryOpExhaustive(
1324       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1325         return CR1.urem(CR2);
1326       },
1327       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1328         if (N2.isZero())
1329           return None;
1330         return N1.urem(N2);
1331       },
1332       PreferSmallest,
1333       CheckSingleElementsOnly);
1334 }
1335 
1336 TEST_F(ConstantRangeTest, SRem) {
1337   EXPECT_EQ(Full.srem(Empty), Empty);
1338   EXPECT_EQ(Empty.srem(Full), Empty);
1339   // srem by zero is UB.
1340   EXPECT_EQ(Full.srem(ConstantRange(APInt(16, 0))), Empty);
1341   // srem by full range doesn't contain SignedMinValue.
1342   EXPECT_EQ(Full.srem(Full), ConstantRange(APInt::getSignedMinValue(16) + 1,
1343                                            APInt::getSignedMinValue(16)));
1344 
1345   ConstantRange PosMod(APInt(16, 10), APInt(16, 21));  // [10, 20]
1346   ConstantRange NegMod(APInt(16, -20), APInt(16, -9)); // [-20, -10]
1347   ConstantRange IntMinMod(APInt::getSignedMinValue(16));
1348 
1349   ConstantRange Expected(16, true);
1350 
1351   // srem is bounded by abs(RHS) minus one.
1352   ConstantRange PosLargeLHS(APInt(16, 0), APInt(16, 41));
1353   Expected = ConstantRange(APInt(16, 0), APInt(16, 20));
1354   EXPECT_EQ(PosLargeLHS.srem(PosMod), Expected);
1355   EXPECT_EQ(PosLargeLHS.srem(NegMod), Expected);
1356   ConstantRange NegLargeLHS(APInt(16, -40), APInt(16, 1));
1357   Expected = ConstantRange(APInt(16, -19), APInt(16, 1));
1358   EXPECT_EQ(NegLargeLHS.srem(PosMod), Expected);
1359   EXPECT_EQ(NegLargeLHS.srem(NegMod), Expected);
1360   ConstantRange PosNegLargeLHS(APInt(16, -32), APInt(16, 38));
1361   Expected = ConstantRange(APInt(16, -19), APInt(16, 20));
1362   EXPECT_EQ(PosNegLargeLHS.srem(PosMod), Expected);
1363   EXPECT_EQ(PosNegLargeLHS.srem(NegMod), Expected);
1364 
1365   // srem is bounded by LHS.
1366   ConstantRange PosLHS(APInt(16, 0), APInt(16, 16));
1367   EXPECT_EQ(PosLHS.srem(PosMod), PosLHS);
1368   EXPECT_EQ(PosLHS.srem(NegMod), PosLHS);
1369   EXPECT_EQ(PosLHS.srem(IntMinMod), PosLHS);
1370   ConstantRange NegLHS(APInt(16, -15), APInt(16, 1));
1371   EXPECT_EQ(NegLHS.srem(PosMod), NegLHS);
1372   EXPECT_EQ(NegLHS.srem(NegMod), NegLHS);
1373   EXPECT_EQ(NegLHS.srem(IntMinMod), NegLHS);
1374   ConstantRange PosNegLHS(APInt(16, -12), APInt(16, 18));
1375   EXPECT_EQ(PosNegLHS.srem(PosMod), PosNegLHS);
1376   EXPECT_EQ(PosNegLHS.srem(NegMod), PosNegLHS);
1377   EXPECT_EQ(PosNegLHS.srem(IntMinMod), PosNegLHS);
1378 
1379   // srem is LHS if it is smaller than RHS.
1380   ConstantRange PosSmallLHS(APInt(16, 3), APInt(16, 8));
1381   EXPECT_EQ(PosSmallLHS.srem(PosMod), PosSmallLHS);
1382   EXPECT_EQ(PosSmallLHS.srem(NegMod), PosSmallLHS);
1383   EXPECT_EQ(PosSmallLHS.srem(IntMinMod), PosSmallLHS);
1384   ConstantRange NegSmallLHS(APInt(16, -7), APInt(16, -2));
1385   EXPECT_EQ(NegSmallLHS.srem(PosMod), NegSmallLHS);
1386   EXPECT_EQ(NegSmallLHS.srem(NegMod), NegSmallLHS);
1387   EXPECT_EQ(NegSmallLHS.srem(IntMinMod), NegSmallLHS);
1388   ConstantRange PosNegSmallLHS(APInt(16, -3), APInt(16, 8));
1389   EXPECT_EQ(PosNegSmallLHS.srem(PosMod), PosNegSmallLHS);
1390   EXPECT_EQ(PosNegSmallLHS.srem(NegMod), PosNegSmallLHS);
1391   EXPECT_EQ(PosNegSmallLHS.srem(IntMinMod), PosNegSmallLHS);
1392 
1393   // Example of a suboptimal result:
1394   // [12, 14] srem 10 is [2, 4], but we conservatively compute [0, 9].
1395   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1396                 .srem(ConstantRange(APInt(16, 10))),
1397             ConstantRange(APInt(16, 0), APInt(16, 10)));
1398 
1399   TestBinaryOpExhaustive(
1400       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1401         return CR1.srem(CR2);
1402       },
1403       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1404         if (N2.isZero())
1405           return None;
1406         return N1.srem(N2);
1407       },
1408       PreferSmallest,
1409       CheckSingleElementsOnly);
1410 }
1411 
1412 TEST_F(ConstantRangeTest, Shl) {
1413   ConstantRange Some2(APInt(16, 0xfff), APInt(16, 0x8000));
1414   ConstantRange WrapNullMax(APInt(16, 0x1), APInt(16, 0x0));
1415   EXPECT_EQ(Full.shl(Full), Full);
1416   EXPECT_EQ(Full.shl(Empty), Empty);
1417   EXPECT_EQ(Full.shl(One), ConstantRange(APInt(16, 0),
1418                                          APInt(16, 0xfc00) + 1));
1419   EXPECT_EQ(Full.shl(Some), Full);   // TODO: [0, (-1 << 0xa) + 1)
1420   EXPECT_EQ(Full.shl(Wrap), Full);
1421   EXPECT_EQ(Empty.shl(Empty), Empty);
1422   EXPECT_EQ(Empty.shl(One), Empty);
1423   EXPECT_EQ(Empty.shl(Some), Empty);
1424   EXPECT_EQ(Empty.shl(Wrap), Empty);
1425   EXPECT_EQ(One.shl(One), ConstantRange(APInt(16, 0xa << 0xa),
1426                                         APInt(16, (0xa << 0xa) + 1)));
1427   EXPECT_EQ(One.shl(Some), Full);    // TODO: [0xa << 0xa, 0)
1428   EXPECT_EQ(One.shl(Wrap), Full);    // TODO: [0xa, 0xa << 14 + 1)
1429   EXPECT_EQ(Some.shl(Some), Full);   // TODO: [0xa << 0xa, 0xfc01)
1430   EXPECT_EQ(Some.shl(Wrap), Full);   // TODO: [0xa, 0x7ff << 0x5 + 1)
1431   EXPECT_EQ(Wrap.shl(Wrap), Full);
1432   EXPECT_EQ(
1433       Some2.shl(ConstantRange(APInt(16, 0x1))),
1434       ConstantRange(APInt(16, 0xfff << 0x1), APInt(16, 0x7fff << 0x1) + 1));
1435   EXPECT_EQ(One.shl(WrapNullMax), Full);
1436 
1437   TestBinaryOpExhaustive(
1438       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1439         return CR1.shl(CR2);
1440       },
1441       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1442         if (N2.uge(N2.getBitWidth()))
1443           return None;
1444         return N1.shl(N2);
1445       },
1446       PreferSmallestUnsigned,
1447       [](const ConstantRange &, const ConstantRange &CR2) {
1448         // We currently only produce precise results for single element RHS.
1449         return CR2.isSingleElement();
1450       });
1451 }
1452 
1453 TEST_F(ConstantRangeTest, Lshr) {
1454   EXPECT_EQ(Full.lshr(Full), Full);
1455   EXPECT_EQ(Full.lshr(Empty), Empty);
1456   EXPECT_EQ(Full.lshr(One), ConstantRange(APInt(16, 0),
1457                                           APInt(16, (0xffff >> 0xa) + 1)));
1458   EXPECT_EQ(Full.lshr(Some), ConstantRange(APInt(16, 0),
1459                                            APInt(16, (0xffff >> 0xa) + 1)));
1460   EXPECT_EQ(Full.lshr(Wrap), Full);
1461   EXPECT_EQ(Empty.lshr(Empty), Empty);
1462   EXPECT_EQ(Empty.lshr(One), Empty);
1463   EXPECT_EQ(Empty.lshr(Some), Empty);
1464   EXPECT_EQ(Empty.lshr(Wrap), Empty);
1465   EXPECT_EQ(One.lshr(One), ConstantRange(APInt(16, 0)));
1466   EXPECT_EQ(One.lshr(Some), ConstantRange(APInt(16, 0)));
1467   EXPECT_EQ(One.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1468   EXPECT_EQ(Some.lshr(Some), ConstantRange(APInt(16, 0),
1469                                            APInt(16, (0xaaa >> 0xa) + 1)));
1470   EXPECT_EQ(Some.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1471   EXPECT_EQ(Wrap.lshr(Wrap), Full);
1472 }
1473 
1474 TEST_F(ConstantRangeTest, Ashr) {
1475   EXPECT_EQ(Full.ashr(Full), Full);
1476   EXPECT_EQ(Full.ashr(Empty), Empty);
1477   EXPECT_EQ(Full.ashr(One), ConstantRange(APInt(16, 0xffe0),
1478                                           APInt(16, (0x7fff >> 0xa) + 1 )));
1479   ConstantRange Small(APInt(16, 0xa), APInt(16, 0xb));
1480   EXPECT_EQ(Full.ashr(Small), ConstantRange(APInt(16, 0xffe0),
1481                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1482   EXPECT_EQ(Full.ashr(Some), ConstantRange(APInt(16, 0xffe0),
1483                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1484   EXPECT_EQ(Full.ashr(Wrap), Full);
1485   EXPECT_EQ(Empty.ashr(Empty), Empty);
1486   EXPECT_EQ(Empty.ashr(One), Empty);
1487   EXPECT_EQ(Empty.ashr(Some), Empty);
1488   EXPECT_EQ(Empty.ashr(Wrap), Empty);
1489   EXPECT_EQ(One.ashr(One), ConstantRange(APInt(16, 0)));
1490   EXPECT_EQ(One.ashr(Some), ConstantRange(APInt(16, 0)));
1491   EXPECT_EQ(One.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1492   EXPECT_EQ(Some.ashr(Some), ConstantRange(APInt(16, 0),
1493                                            APInt(16, (0xaaa >> 0xa) + 1)));
1494   EXPECT_EQ(Some.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1495   EXPECT_EQ(Wrap.ashr(Wrap), Full);
1496   ConstantRange Neg(APInt(16, 0xf3f0, true), APInt(16, 0xf7f8, true));
1497   EXPECT_EQ(Neg.ashr(Small), ConstantRange(APInt(16, 0xfffc, true),
1498                                            APInt(16, 0xfffe, true)));
1499 }
1500 
1501 TEST(ConstantRange, MakeAllowedICmpRegion) {
1502   // PR8250
1503   ConstantRange SMax = ConstantRange(APInt::getSignedMaxValue(32));
1504   EXPECT_TRUE(ConstantRange::makeAllowedICmpRegion(ICmpInst::ICMP_SGT, SMax)
1505                   .isEmptySet());
1506 }
1507 
1508 TEST(ConstantRange, MakeSatisfyingICmpRegion) {
1509   ConstantRange LowHalf(APInt(8, 0), APInt(8, 128));
1510   ConstantRange HighHalf(APInt(8, 128), APInt(8, 0));
1511   ConstantRange EmptySet(8, /* isFullSet = */ false);
1512 
1513   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, LowHalf),
1514             HighHalf);
1515 
1516   EXPECT_EQ(
1517       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, HighHalf),
1518       LowHalf);
1519 
1520   EXPECT_TRUE(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_EQ,
1521                                                       HighHalf).isEmptySet());
1522 
1523   ConstantRange UnsignedSample(APInt(8, 5), APInt(8, 200));
1524 
1525   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULT,
1526                                                     UnsignedSample),
1527             ConstantRange(APInt(8, 0), APInt(8, 5)));
1528 
1529   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULE,
1530                                                     UnsignedSample),
1531             ConstantRange(APInt(8, 0), APInt(8, 6)));
1532 
1533   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGT,
1534                                                     UnsignedSample),
1535             ConstantRange(APInt(8, 200), APInt(8, 0)));
1536 
1537   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGE,
1538                                                     UnsignedSample),
1539             ConstantRange(APInt(8, 199), APInt(8, 0)));
1540 
1541   ConstantRange SignedSample(APInt(8, -5), APInt(8, 5));
1542 
1543   EXPECT_EQ(
1544       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLT, SignedSample),
1545       ConstantRange(APInt(8, -128), APInt(8, -5)));
1546 
1547   EXPECT_EQ(
1548       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLE, SignedSample),
1549       ConstantRange(APInt(8, -128), APInt(8, -4)));
1550 
1551   EXPECT_EQ(
1552       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGT, SignedSample),
1553       ConstantRange(APInt(8, 5), APInt(8, -128)));
1554 
1555   EXPECT_EQ(
1556       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGE, SignedSample),
1557       ConstantRange(APInt(8, 4), APInt(8, -128)));
1558 }
1559 
1560 void ICmpTestImpl(CmpInst::Predicate Pred) {
1561   unsigned Bits = 4;
1562   EnumerateTwoConstantRanges(
1563       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
1564         bool Exhaustive = true;
1565         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1566           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
1567             Exhaustive &= ICmpInst::compare(N1, N2, Pred);
1568           });
1569         });
1570         EXPECT_EQ(CR1.icmp(Pred, CR2), Exhaustive);
1571       });
1572 }
1573 
1574 TEST(ConstantRange, ICmp) {
1575   for (auto Pred : ICmpInst::predicates())
1576     ICmpTestImpl(Pred);
1577 }
1578 
1579 TEST(ConstantRange, MakeGuaranteedNoWrapRegion) {
1580   const int IntMin4Bits = 8;
1581   const int IntMax4Bits = 7;
1582   typedef OverflowingBinaryOperator OBO;
1583 
1584   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1585     APInt C(4, Const, true /* = isSigned */);
1586 
1587     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1588         Instruction::Add, C, OBO::NoUnsignedWrap);
1589 
1590     EXPECT_FALSE(NUWRegion.isEmptySet());
1591 
1592     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1593         Instruction::Add, C, OBO::NoSignedWrap);
1594 
1595     EXPECT_FALSE(NSWRegion.isEmptySet());
1596 
1597     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1598          ++I) {
1599       bool Overflow = false;
1600       (void)I.uadd_ov(C, Overflow);
1601       EXPECT_FALSE(Overflow);
1602     }
1603 
1604     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1605          ++I) {
1606       bool Overflow = false;
1607       (void)I.sadd_ov(C, Overflow);
1608       EXPECT_FALSE(Overflow);
1609     }
1610   }
1611 
1612   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1613     APInt C(4, Const, true /* = isSigned */);
1614 
1615     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1616         Instruction::Sub, C, OBO::NoUnsignedWrap);
1617 
1618     EXPECT_FALSE(NUWRegion.isEmptySet());
1619 
1620     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1621         Instruction::Sub, C, OBO::NoSignedWrap);
1622 
1623     EXPECT_FALSE(NSWRegion.isEmptySet());
1624 
1625     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1626          ++I) {
1627       bool Overflow = false;
1628       (void)I.usub_ov(C, Overflow);
1629       EXPECT_FALSE(Overflow);
1630     }
1631 
1632     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1633          ++I) {
1634       bool Overflow = false;
1635       (void)I.ssub_ov(C, Overflow);
1636       EXPECT_FALSE(Overflow);
1637     }
1638   }
1639 
1640   auto NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1641       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1642       OBO::NoSignedWrap);
1643   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1644               NSWForAllValues.getSingleElement()->isMinValue());
1645 
1646   NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1647       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1648       OBO::NoSignedWrap);
1649   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1650               NSWForAllValues.getSingleElement()->isMaxValue());
1651 
1652   auto NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1653       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1654       OBO::NoUnsignedWrap);
1655   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1656               NUWForAllValues.getSingleElement()->isMinValue());
1657 
1658   NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1659       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1660       OBO::NoUnsignedWrap);
1661   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1662               NUWForAllValues.getSingleElement()->isMaxValue());
1663 
1664   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1665       Instruction::Add, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1666   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1667       Instruction::Add, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1668   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1669       Instruction::Sub, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1670   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1671       Instruction::Sub, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1672 
1673   ConstantRange OneToFive(APInt(32, 1), APInt(32, 6));
1674   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1675                 Instruction::Add, OneToFive, OBO::NoSignedWrap),
1676             ConstantRange(APInt::getSignedMinValue(32),
1677                           APInt::getSignedMaxValue(32) - 4));
1678   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1679                 Instruction::Add, OneToFive, OBO::NoUnsignedWrap),
1680             ConstantRange(APInt::getMinValue(32), APInt::getMinValue(32) - 5));
1681   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1682                 Instruction::Sub, OneToFive, OBO::NoSignedWrap),
1683             ConstantRange(APInt::getSignedMinValue(32) + 5,
1684                           APInt::getSignedMinValue(32)));
1685   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1686                 Instruction::Sub, OneToFive, OBO::NoUnsignedWrap),
1687             ConstantRange(APInt::getMinValue(32) + 5, APInt::getMinValue(32)));
1688 
1689   ConstantRange MinusFiveToMinusTwo(APInt(32, -5), APInt(32, -1));
1690   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1691                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1692             ConstantRange(APInt::getSignedMinValue(32) + 5,
1693                           APInt::getSignedMinValue(32)));
1694   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1695                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1696             ConstantRange(APInt(32, 0), APInt(32, 2)));
1697   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1698                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1699             ConstantRange(APInt::getSignedMinValue(32),
1700                           APInt::getSignedMaxValue(32) - 4));
1701   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1702                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1703             ConstantRange(APInt::getMaxValue(32) - 1,
1704                           APInt::getMinValue(32)));
1705 
1706   ConstantRange MinusOneToOne(APInt(32, -1), APInt(32, 2));
1707   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1708                 Instruction::Add, MinusOneToOne, OBO::NoSignedWrap),
1709             ConstantRange(APInt::getSignedMinValue(32) + 1,
1710                           APInt::getSignedMinValue(32) - 1));
1711   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1712                 Instruction::Add, MinusOneToOne, OBO::NoUnsignedWrap),
1713             ConstantRange(APInt(32, 0), APInt(32, 1)));
1714   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1715                 Instruction::Sub, MinusOneToOne, OBO::NoSignedWrap),
1716             ConstantRange(APInt::getSignedMinValue(32) + 1,
1717                           APInt::getSignedMinValue(32) - 1));
1718   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1719                 Instruction::Sub, MinusOneToOne, OBO::NoUnsignedWrap),
1720             ConstantRange(APInt::getMaxValue(32),
1721                           APInt::getMinValue(32)));
1722 
1723   ConstantRange One(APInt(32, 1), APInt(32, 2));
1724   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1725                 Instruction::Add, One, OBO::NoSignedWrap),
1726             ConstantRange(APInt::getSignedMinValue(32),
1727                           APInt::getSignedMaxValue(32)));
1728   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1729                 Instruction::Add, One, OBO::NoUnsignedWrap),
1730             ConstantRange(APInt::getMinValue(32), APInt::getMaxValue(32)));
1731   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1732                 Instruction::Sub, One, OBO::NoSignedWrap),
1733             ConstantRange(APInt::getSignedMinValue(32) + 1,
1734                           APInt::getSignedMinValue(32)));
1735   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1736                 Instruction::Sub, One, OBO::NoUnsignedWrap),
1737             ConstantRange(APInt::getMinValue(32) + 1, APInt::getMinValue(32)));
1738 
1739   ConstantRange OneLessThanBitWidth(APInt(32, 0), APInt(32, 31) + 1);
1740   ConstantRange UpToBitWidth(APInt(32, 0), APInt(32, 32) + 1);
1741   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1742                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1743             ConstantRange::makeGuaranteedNoWrapRegion(
1744                 Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1745   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1746                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1747             ConstantRange::makeGuaranteedNoWrapRegion(
1748                 Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1749   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1750                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1751             ConstantRange(APInt(32, 0), APInt(32, 1) + 1));
1752   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1753                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1754             ConstantRange(APInt(32, -1), APInt(32, 0) + 1));
1755 
1756   EXPECT_EQ(
1757       ConstantRange::makeGuaranteedNoWrapRegion(
1758           Instruction::Shl, ConstantRange::getFull(32), OBO::NoUnsignedWrap),
1759       ConstantRange::makeGuaranteedNoWrapRegion(
1760           Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1761   EXPECT_EQ(
1762       ConstantRange::makeGuaranteedNoWrapRegion(
1763           Instruction::Shl, ConstantRange::getFull(32), OBO::NoSignedWrap),
1764       ConstantRange::makeGuaranteedNoWrapRegion(
1765           Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1766 
1767   ConstantRange IllegalShAmt(APInt(32, 32), APInt(32, 0) + 1);
1768   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1769                 Instruction::Shl, IllegalShAmt, OBO::NoUnsignedWrap),
1770             ConstantRange::getFull(32));
1771   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1772                 Instruction::Shl, IllegalShAmt, OBO::NoSignedWrap),
1773             ConstantRange::getFull(32));
1774 
1775   EXPECT_EQ(
1776       ConstantRange::makeGuaranteedNoWrapRegion(
1777           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1778           OBO::NoUnsignedWrap),
1779       ConstantRange::makeGuaranteedNoWrapRegion(
1780           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1781           OBO::NoUnsignedWrap));
1782   EXPECT_EQ(
1783       ConstantRange::makeGuaranteedNoWrapRegion(
1784           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1785           OBO::NoSignedWrap),
1786       ConstantRange::makeGuaranteedNoWrapRegion(
1787           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1788           OBO::NoSignedWrap));
1789 
1790   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1791                 Instruction::Shl,
1792                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1793                 OBO::NoUnsignedWrap),
1794             ConstantRange(APInt(32, 0), APInt(32, 65535) + 1));
1795   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1796                 Instruction::Shl,
1797                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1798                 OBO::NoSignedWrap),
1799             ConstantRange(APInt(32, -32768), APInt(32, 32767) + 1));
1800 }
1801 
1802 template<typename Fn>
1803 void TestNoWrapRegionExhaustive(Instruction::BinaryOps BinOp,
1804                                 unsigned NoWrapKind, Fn OverflowFn) {
1805   unsigned Bits = 5;
1806   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
1807     if (CR.isEmptySet())
1808       return;
1809     if (Instruction::isShift(BinOp) && CR.getUnsignedMax().uge(Bits))
1810       return;
1811 
1812     ConstantRange NoWrap =
1813         ConstantRange::makeGuaranteedNoWrapRegion(BinOp, CR, NoWrapKind);
1814     ConstantRange Full = ConstantRange::getFull(Bits);
1815     ForeachNumInConstantRange(Full, [&](const APInt &N1) {
1816       bool NoOverflow = true;
1817       bool Overflow = true;
1818       ForeachNumInConstantRange(CR, [&](const APInt &N2) {
1819         if (OverflowFn(N1, N2))
1820           NoOverflow = false;
1821         else
1822           Overflow = false;
1823       });
1824       EXPECT_EQ(NoOverflow, NoWrap.contains(N1));
1825 
1826       // The no-wrap range is exact for single-element ranges.
1827       if (CR.isSingleElement()) {
1828         EXPECT_EQ(Overflow, !NoWrap.contains(N1));
1829       }
1830     });
1831   });
1832 }
1833 
1834 // Show that makeGuaranteedNoWrapRegion() is maximal, and for single-element
1835 // ranges also exact.
1836 TEST(ConstantRange, NoWrapRegionExhaustive) {
1837   TestNoWrapRegionExhaustive(
1838       Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap,
1839       [](const APInt &N1, const APInt &N2) {
1840         bool Overflow;
1841         (void) N1.uadd_ov(N2, Overflow);
1842         return Overflow;
1843       });
1844   TestNoWrapRegionExhaustive(
1845       Instruction::Add, OverflowingBinaryOperator::NoSignedWrap,
1846       [](const APInt &N1, const APInt &N2) {
1847         bool Overflow;
1848         (void) N1.sadd_ov(N2, Overflow);
1849         return Overflow;
1850       });
1851   TestNoWrapRegionExhaustive(
1852       Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap,
1853       [](const APInt &N1, const APInt &N2) {
1854         bool Overflow;
1855         (void) N1.usub_ov(N2, Overflow);
1856         return Overflow;
1857       });
1858   TestNoWrapRegionExhaustive(
1859       Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap,
1860       [](const APInt &N1, const APInt &N2) {
1861         bool Overflow;
1862         (void) N1.ssub_ov(N2, Overflow);
1863         return Overflow;
1864       });
1865   TestNoWrapRegionExhaustive(
1866       Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap,
1867       [](const APInt &N1, const APInt &N2) {
1868         bool Overflow;
1869         (void) N1.umul_ov(N2, Overflow);
1870         return Overflow;
1871       });
1872   TestNoWrapRegionExhaustive(
1873       Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap,
1874       [](const APInt &N1, const APInt &N2) {
1875         bool Overflow;
1876         (void) N1.smul_ov(N2, Overflow);
1877         return Overflow;
1878       });
1879   TestNoWrapRegionExhaustive(Instruction::Shl,
1880                              OverflowingBinaryOperator::NoUnsignedWrap,
1881                              [](const APInt &N1, const APInt &N2) {
1882                                bool Overflow;
1883                                (void)N1.ushl_ov(N2, Overflow);
1884                                return Overflow;
1885                              });
1886   TestNoWrapRegionExhaustive(Instruction::Shl,
1887                              OverflowingBinaryOperator::NoSignedWrap,
1888                              [](const APInt &N1, const APInt &N2) {
1889                                bool Overflow;
1890                                (void)N1.sshl_ov(N2, Overflow);
1891                                return Overflow;
1892                              });
1893 }
1894 
1895 TEST(ConstantRange, GetEquivalentICmp) {
1896   APInt RHS;
1897   CmpInst::Predicate Pred;
1898 
1899   EXPECT_TRUE(ConstantRange(APInt::getMinValue(32), APInt(32, 100))
1900                   .getEquivalentICmp(Pred, RHS));
1901   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1902   EXPECT_EQ(RHS, APInt(32, 100));
1903 
1904   EXPECT_TRUE(ConstantRange(APInt::getSignedMinValue(32), APInt(32, 100))
1905                   .getEquivalentICmp(Pred, RHS));
1906   EXPECT_EQ(Pred, CmpInst::ICMP_SLT);
1907   EXPECT_EQ(RHS, APInt(32, 100));
1908 
1909   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getMinValue(32))
1910                   .getEquivalentICmp(Pred, RHS));
1911   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1912   EXPECT_EQ(RHS, APInt(32, 100));
1913 
1914   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getSignedMinValue(32))
1915                   .getEquivalentICmp(Pred, RHS));
1916   EXPECT_EQ(Pred, CmpInst::ICMP_SGE);
1917   EXPECT_EQ(RHS, APInt(32, 100));
1918 
1919   EXPECT_TRUE(
1920       ConstantRange(32, /*isFullSet=*/true).getEquivalentICmp(Pred, RHS));
1921   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1922   EXPECT_EQ(RHS, APInt(32, 0));
1923 
1924   EXPECT_TRUE(
1925       ConstantRange(32, /*isFullSet=*/false).getEquivalentICmp(Pred, RHS));
1926   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1927   EXPECT_EQ(RHS, APInt(32, 0));
1928 
1929   EXPECT_FALSE(ConstantRange(APInt(32, 100), APInt(32, 200))
1930                    .getEquivalentICmp(Pred, RHS));
1931 
1932   EXPECT_FALSE(ConstantRange(APInt::getSignedMinValue(32) - APInt(32, 100),
1933                              APInt::getSignedMinValue(32) + APInt(32, 100))
1934                    .getEquivalentICmp(Pred, RHS));
1935 
1936   EXPECT_FALSE(ConstantRange(APInt::getMinValue(32) - APInt(32, 100),
1937                              APInt::getMinValue(32) + APInt(32, 100))
1938                    .getEquivalentICmp(Pred, RHS));
1939 
1940   EXPECT_TRUE(ConstantRange(APInt(32, 100)).getEquivalentICmp(Pred, RHS));
1941   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1942   EXPECT_EQ(RHS, APInt(32, 100));
1943 
1944   EXPECT_TRUE(
1945       ConstantRange(APInt(32, 100)).inverse().getEquivalentICmp(Pred, RHS));
1946   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1947   EXPECT_EQ(RHS, APInt(32, 100));
1948 
1949   EXPECT_TRUE(
1950       ConstantRange(APInt(512, 100)).inverse().getEquivalentICmp(Pred, RHS));
1951   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1952   EXPECT_EQ(RHS, APInt(512, 100));
1953 
1954   // NB!  It would be correct for the following four calls to getEquivalentICmp
1955   // to return ordered predicates like CmpInst::ICMP_ULT or CmpInst::ICMP_UGT.
1956   // However, that's not the case today.
1957 
1958   EXPECT_TRUE(ConstantRange(APInt(32, 0)).getEquivalentICmp(Pred, RHS));
1959   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1960   EXPECT_EQ(RHS, APInt(32, 0));
1961 
1962   EXPECT_TRUE(
1963       ConstantRange(APInt(32, 0)).inverse().getEquivalentICmp(Pred, RHS));
1964   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1965   EXPECT_EQ(RHS, APInt(32, 0));
1966 
1967   EXPECT_TRUE(ConstantRange(APInt(32, -1)).getEquivalentICmp(Pred, RHS));
1968   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1969   EXPECT_EQ(RHS, APInt(32, -1));
1970 
1971   EXPECT_TRUE(
1972       ConstantRange(APInt(32, -1)).inverse().getEquivalentICmp(Pred, RHS));
1973   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1974   EXPECT_EQ(RHS, APInt(32, -1));
1975 
1976   EnumerateConstantRanges(4, [](const ConstantRange &CR) {
1977     CmpInst::Predicate Pred;
1978     APInt RHS, Offset;
1979     CR.getEquivalentICmp(Pred, RHS, Offset);
1980     ForeachNumInConstantRange(ConstantRange::getFull(4), [&](const APInt &N) {
1981       bool Result = ICmpInst::compare(N + Offset, RHS, Pred);
1982       EXPECT_EQ(CR.contains(N), Result);
1983     });
1984 
1985     if (CR.getEquivalentICmp(Pred, RHS)) {
1986       ForeachNumInConstantRange(ConstantRange::getFull(4), [&](const APInt &N) {
1987         bool Result = ICmpInst::compare(N, RHS, Pred);
1988         EXPECT_EQ(CR.contains(N), Result);
1989       });
1990     }
1991   });
1992 }
1993 
1994 #define EXPECT_MAY_OVERFLOW(op) \
1995   EXPECT_EQ(ConstantRange::OverflowResult::MayOverflow, (op))
1996 #define EXPECT_ALWAYS_OVERFLOWS_LOW(op) \
1997   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsLow, (op))
1998 #define EXPECT_ALWAYS_OVERFLOWS_HIGH(op) \
1999   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsHigh, (op))
2000 #define EXPECT_NEVER_OVERFLOWS(op) \
2001   EXPECT_EQ(ConstantRange::OverflowResult::NeverOverflows, (op))
2002 
2003 TEST_F(ConstantRangeTest, UnsignedAddOverflow) {
2004   // Ill-defined - may overflow is a conservative result.
2005   EXPECT_MAY_OVERFLOW(Some.unsignedAddMayOverflow(Empty));
2006   EXPECT_MAY_OVERFLOW(Empty.unsignedAddMayOverflow(Some));
2007 
2008   // Never overflow despite one full/wrap set.
2009   ConstantRange Zero(APInt::getZero(16));
2010   EXPECT_NEVER_OVERFLOWS(Full.unsignedAddMayOverflow(Zero));
2011   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedAddMayOverflow(Zero));
2012   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Full));
2013   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Wrap));
2014 
2015   // But usually full/wrap always may overflow.
2016   EXPECT_MAY_OVERFLOW(Full.unsignedAddMayOverflow(One));
2017   EXPECT_MAY_OVERFLOW(Wrap.unsignedAddMayOverflow(One));
2018   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Full));
2019   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Wrap));
2020 
2021   ConstantRange A(APInt(16, 0xfd00), APInt(16, 0xfe00));
2022   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2023   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2024   EXPECT_NEVER_OVERFLOWS(A.unsignedAddMayOverflow(B1));
2025   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(B2));
2026   EXPECT_NEVER_OVERFLOWS(B1.unsignedAddMayOverflow(A));
2027   EXPECT_MAY_OVERFLOW(B2.unsignedAddMayOverflow(A));
2028 
2029   ConstantRange C1(APInt(16, 0x0299), APInt(16, 0x0400));
2030   ConstantRange C2(APInt(16, 0x0300), APInt(16, 0x0400));
2031   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(C1));
2032   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.unsignedAddMayOverflow(C2));
2033   EXPECT_MAY_OVERFLOW(C1.unsignedAddMayOverflow(A));
2034   EXPECT_ALWAYS_OVERFLOWS_HIGH(C2.unsignedAddMayOverflow(A));
2035 }
2036 
2037 TEST_F(ConstantRangeTest, UnsignedSubOverflow) {
2038   // Ill-defined - may overflow is a conservative result.
2039   EXPECT_MAY_OVERFLOW(Some.unsignedSubMayOverflow(Empty));
2040   EXPECT_MAY_OVERFLOW(Empty.unsignedSubMayOverflow(Some));
2041 
2042   // Never overflow despite one full/wrap set.
2043   ConstantRange Zero(APInt::getZero(16));
2044   ConstantRange Max(APInt::getAllOnes(16));
2045   EXPECT_NEVER_OVERFLOWS(Full.unsignedSubMayOverflow(Zero));
2046   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedSubMayOverflow(Zero));
2047   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Full));
2048   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Wrap));
2049 
2050   // But usually full/wrap always may overflow.
2051   EXPECT_MAY_OVERFLOW(Full.unsignedSubMayOverflow(One));
2052   EXPECT_MAY_OVERFLOW(Wrap.unsignedSubMayOverflow(One));
2053   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Full));
2054   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Wrap));
2055 
2056   ConstantRange A(APInt(16, 0x0000), APInt(16, 0x0100));
2057   ConstantRange B(APInt(16, 0x0100), APInt(16, 0x0200));
2058   EXPECT_NEVER_OVERFLOWS(B.unsignedSubMayOverflow(A));
2059   EXPECT_ALWAYS_OVERFLOWS_LOW(A.unsignedSubMayOverflow(B));
2060 
2061   ConstantRange A1(APInt(16, 0x0000), APInt(16, 0x0101));
2062   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2063   EXPECT_NEVER_OVERFLOWS(B1.unsignedSubMayOverflow(A1));
2064   EXPECT_MAY_OVERFLOW(A1.unsignedSubMayOverflow(B1));
2065 
2066   ConstantRange A2(APInt(16, 0x0000), APInt(16, 0x0102));
2067   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2068   EXPECT_MAY_OVERFLOW(B2.unsignedSubMayOverflow(A2));
2069   EXPECT_MAY_OVERFLOW(A2.unsignedSubMayOverflow(B2));
2070 }
2071 
2072 TEST_F(ConstantRangeTest, SignedAddOverflow) {
2073   // Ill-defined - may overflow is a conservative result.
2074   EXPECT_MAY_OVERFLOW(Some.signedAddMayOverflow(Empty));
2075   EXPECT_MAY_OVERFLOW(Empty.signedAddMayOverflow(Some));
2076 
2077   // Never overflow despite one full/wrap set.
2078   ConstantRange Zero(APInt::getZero(16));
2079   EXPECT_NEVER_OVERFLOWS(Full.signedAddMayOverflow(Zero));
2080   EXPECT_NEVER_OVERFLOWS(Wrap.signedAddMayOverflow(Zero));
2081   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Full));
2082   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Wrap));
2083 
2084   // But usually full/wrap always may overflow.
2085   EXPECT_MAY_OVERFLOW(Full.signedAddMayOverflow(One));
2086   EXPECT_MAY_OVERFLOW(Wrap.signedAddMayOverflow(One));
2087   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Full));
2088   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Wrap));
2089 
2090   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2091   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2092   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2093   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B1));
2094   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B2));
2095   ConstantRange B3(APInt(16, 0x8000), APInt(16, 0x0201));
2096   ConstantRange B4(APInt(16, 0x8000), APInt(16, 0x0202));
2097   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B3));
2098   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B4));
2099   ConstantRange B5(APInt(16, 0x0299), APInt(16, 0x0400));
2100   ConstantRange B6(APInt(16, 0x0300), APInt(16, 0x0400));
2101   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B5));
2102   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedAddMayOverflow(B6));
2103 
2104   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2105   ConstantRange D1(APInt(16, 0xfe00), APInt(16, 0xff00));
2106   ConstantRange D2(APInt(16, 0xfd99), APInt(16, 0xff00));
2107   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D1));
2108   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D2));
2109   ConstantRange D3(APInt(16, 0xfe00), APInt(16, 0x8000));
2110   ConstantRange D4(APInt(16, 0xfd99), APInt(16, 0x8000));
2111   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D3));
2112   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D4));
2113   ConstantRange D5(APInt(16, 0xfc00), APInt(16, 0xfd02));
2114   ConstantRange D6(APInt(16, 0xfc00), APInt(16, 0xfd01));
2115   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D5));
2116   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedAddMayOverflow(D6));
2117 
2118   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2119   EXPECT_NEVER_OVERFLOWS(E.signedAddMayOverflow(E));
2120   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7000));
2121   EXPECT_MAY_OVERFLOW(F.signedAddMayOverflow(F));
2122 }
2123 
2124 TEST_F(ConstantRangeTest, SignedSubOverflow) {
2125   // Ill-defined - may overflow is a conservative result.
2126   EXPECT_MAY_OVERFLOW(Some.signedSubMayOverflow(Empty));
2127   EXPECT_MAY_OVERFLOW(Empty.signedSubMayOverflow(Some));
2128 
2129   // Never overflow despite one full/wrap set.
2130   ConstantRange Zero(APInt::getZero(16));
2131   EXPECT_NEVER_OVERFLOWS(Full.signedSubMayOverflow(Zero));
2132   EXPECT_NEVER_OVERFLOWS(Wrap.signedSubMayOverflow(Zero));
2133 
2134   // But usually full/wrap always may overflow.
2135   EXPECT_MAY_OVERFLOW(Full.signedSubMayOverflow(One));
2136   EXPECT_MAY_OVERFLOW(Wrap.signedSubMayOverflow(One));
2137   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Full));
2138   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Wrap));
2139 
2140   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2141   ConstantRange B1(APInt(16, 0xfe00), APInt(16, 0xff00));
2142   ConstantRange B2(APInt(16, 0xfd99), APInt(16, 0xff00));
2143   EXPECT_NEVER_OVERFLOWS(A.signedSubMayOverflow(B1));
2144   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B2));
2145   ConstantRange B3(APInt(16, 0xfc00), APInt(16, 0xfd02));
2146   ConstantRange B4(APInt(16, 0xfc00), APInt(16, 0xfd01));
2147   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B3));
2148   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedSubMayOverflow(B4));
2149 
2150   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2151   ConstantRange D1(APInt(16, 0x0100), APInt(16, 0x0201));
2152   ConstantRange D2(APInt(16, 0x0100), APInt(16, 0x0202));
2153   EXPECT_NEVER_OVERFLOWS(C.signedSubMayOverflow(D1));
2154   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D2));
2155   ConstantRange D3(APInt(16, 0x0299), APInt(16, 0x0400));
2156   ConstantRange D4(APInt(16, 0x0300), APInt(16, 0x0400));
2157   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D3));
2158   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedSubMayOverflow(D4));
2159 
2160   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2161   EXPECT_NEVER_OVERFLOWS(E.signedSubMayOverflow(E));
2162   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7001));
2163   EXPECT_MAY_OVERFLOW(F.signedSubMayOverflow(F));
2164 }
2165 
2166 template<typename Fn1, typename Fn2>
2167 static void TestOverflowExhaustive(Fn1 OverflowFn, Fn2 MayOverflowFn) {
2168   // Constant range overflow checks are tested exhaustively on 4-bit numbers.
2169   unsigned Bits = 4;
2170   EnumerateTwoConstantRanges(Bits, [=](const ConstantRange &CR1,
2171                                        const ConstantRange &CR2) {
2172     // Loop over all N1 in CR1 and N2 in CR2 and check whether any of the
2173     // operations have overflow / have no overflow.
2174     bool RangeHasOverflowLow = false;
2175     bool RangeHasOverflowHigh = false;
2176     bool RangeHasNoOverflow = false;
2177     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
2178       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
2179         bool IsOverflowHigh;
2180         if (!OverflowFn(IsOverflowHigh, N1, N2)) {
2181           RangeHasNoOverflow = true;
2182           return;
2183         }
2184 
2185         if (IsOverflowHigh)
2186           RangeHasOverflowHigh = true;
2187         else
2188           RangeHasOverflowLow = true;
2189       });
2190     });
2191 
2192     ConstantRange::OverflowResult OR = MayOverflowFn(CR1, CR2);
2193     switch (OR) {
2194     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
2195       EXPECT_TRUE(RangeHasOverflowLow);
2196       EXPECT_FALSE(RangeHasOverflowHigh);
2197       EXPECT_FALSE(RangeHasNoOverflow);
2198       break;
2199     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
2200       EXPECT_TRUE(RangeHasOverflowHigh);
2201       EXPECT_FALSE(RangeHasOverflowLow);
2202       EXPECT_FALSE(RangeHasNoOverflow);
2203       break;
2204     case ConstantRange::OverflowResult::NeverOverflows:
2205       EXPECT_FALSE(RangeHasOverflowLow);
2206       EXPECT_FALSE(RangeHasOverflowHigh);
2207       EXPECT_TRUE(RangeHasNoOverflow);
2208       break;
2209     case ConstantRange::OverflowResult::MayOverflow:
2210       // We return MayOverflow for empty sets as a conservative result,
2211       // but of course neither the RangeHasOverflow nor the
2212       // RangeHasNoOverflow flags will be set.
2213       if (CR1.isEmptySet() || CR2.isEmptySet())
2214         break;
2215 
2216       EXPECT_TRUE(RangeHasOverflowLow || RangeHasOverflowHigh);
2217       EXPECT_TRUE(RangeHasNoOverflow);
2218       break;
2219     }
2220   });
2221 }
2222 
2223 TEST_F(ConstantRangeTest, UnsignedAddOverflowExhaustive) {
2224   TestOverflowExhaustive(
2225       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2226         bool Overflow;
2227         (void) N1.uadd_ov(N2, Overflow);
2228         IsOverflowHigh = true;
2229         return Overflow;
2230       },
2231       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2232         return CR1.unsignedAddMayOverflow(CR2);
2233       });
2234 }
2235 
2236 TEST_F(ConstantRangeTest, UnsignedSubOverflowExhaustive) {
2237   TestOverflowExhaustive(
2238       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2239         bool Overflow;
2240         (void) N1.usub_ov(N2, Overflow);
2241         IsOverflowHigh = false;
2242         return Overflow;
2243       },
2244       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2245         return CR1.unsignedSubMayOverflow(CR2);
2246       });
2247 }
2248 
2249 TEST_F(ConstantRangeTest, UnsignedMulOverflowExhaustive) {
2250   TestOverflowExhaustive(
2251       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2252         bool Overflow;
2253         (void) N1.umul_ov(N2, Overflow);
2254         IsOverflowHigh = true;
2255         return Overflow;
2256       },
2257       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2258         return CR1.unsignedMulMayOverflow(CR2);
2259       });
2260 }
2261 
2262 TEST_F(ConstantRangeTest, SignedAddOverflowExhaustive) {
2263   TestOverflowExhaustive(
2264       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2265         bool Overflow;
2266         (void) N1.sadd_ov(N2, Overflow);
2267         IsOverflowHigh = N1.isNonNegative();
2268         return Overflow;
2269       },
2270       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2271         return CR1.signedAddMayOverflow(CR2);
2272       });
2273 }
2274 
2275 TEST_F(ConstantRangeTest, SignedSubOverflowExhaustive) {
2276   TestOverflowExhaustive(
2277       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2278         bool Overflow;
2279         (void) N1.ssub_ov(N2, Overflow);
2280         IsOverflowHigh = N1.isNonNegative();
2281         return Overflow;
2282       },
2283       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2284         return CR1.signedSubMayOverflow(CR2);
2285       });
2286 }
2287 
2288 TEST_F(ConstantRangeTest, FromKnownBits) {
2289   KnownBits Unknown(16);
2290   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/false));
2291   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/true));
2292 
2293   // .10..01. -> unsigned 01000010 (66)  to 11011011 (219)
2294   //          -> signed   11000010 (194) to 01011011 (91)
2295   KnownBits Known(8);
2296   Known.Zero = 36;
2297   Known.One = 66;
2298   ConstantRange Unsigned(APInt(8, 66), APInt(8, 219 + 1));
2299   ConstantRange Signed(APInt(8, 194), APInt(8, 91 + 1));
2300   EXPECT_EQ(Unsigned, ConstantRange::fromKnownBits(Known, /*signed*/false));
2301   EXPECT_EQ(Signed, ConstantRange::fromKnownBits(Known, /*signed*/true));
2302 
2303   // 1.10.10. -> 10100100 (164) to 11101101 (237)
2304   Known.Zero = 18;
2305   Known.One = 164;
2306   ConstantRange CR1(APInt(8, 164), APInt(8, 237 + 1));
2307   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/false));
2308   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/true));
2309 
2310   // 01.0.1.0 -> 01000100 (68) to 01101110 (110)
2311   Known.Zero = 145;
2312   Known.One = 68;
2313   ConstantRange CR2(APInt(8, 68), APInt(8, 110 + 1));
2314   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/false));
2315   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/true));
2316 }
2317 
2318 TEST_F(ConstantRangeTest, FromKnownBitsExhaustive) {
2319   unsigned Bits = 4;
2320   unsigned Max = 1 << Bits;
2321   KnownBits Known(Bits);
2322   for (unsigned Zero = 0; Zero < Max; ++Zero) {
2323     for (unsigned One = 0; One < Max; ++One) {
2324       Known.Zero = Zero;
2325       Known.One = One;
2326       if (Known.hasConflict() || Known.isUnknown())
2327         continue;
2328 
2329       UnsignedOpRangeGatherer UR(Bits);
2330       SignedOpRangeGatherer SR(Bits);
2331       for (unsigned N = 0; N < Max; ++N) {
2332         APInt Num(Bits, N);
2333         if ((Num & Known.Zero) != 0 || (~Num & Known.One) != 0)
2334           continue;
2335 
2336         UR.account(Num);
2337         SR.account(Num);
2338       }
2339 
2340       ConstantRange UnsignedCR = UR.getRange();
2341       ConstantRange SignedCR = SR.getRange();
2342       EXPECT_EQ(UnsignedCR, ConstantRange::fromKnownBits(Known, false));
2343       EXPECT_EQ(SignedCR, ConstantRange::fromKnownBits(Known, true));
2344     }
2345   }
2346 }
2347 
2348 TEST_F(ConstantRangeTest, Negative) {
2349   // All elements in an empty set (of which there are none) are both negative
2350   // and non-negative. Empty & full sets checked explicitly for clarity, but
2351   // they are also covered by the exhaustive test below.
2352   EXPECT_TRUE(Empty.isAllNegative());
2353   EXPECT_TRUE(Empty.isAllNonNegative());
2354   EXPECT_FALSE(Full.isAllNegative());
2355   EXPECT_FALSE(Full.isAllNonNegative());
2356 
2357   unsigned Bits = 4;
2358   EnumerateConstantRanges(Bits, [](const ConstantRange &CR) {
2359     bool AllNegative = true;
2360     bool AllNonNegative = true;
2361     ForeachNumInConstantRange(CR, [&](const APInt &N) {
2362       if (!N.isNegative())
2363         AllNegative = false;
2364       if (!N.isNonNegative())
2365         AllNonNegative = false;
2366     });
2367     assert((CR.isEmptySet() || !AllNegative || !AllNonNegative) &&
2368            "Only empty set can be both all negative and all non-negative");
2369 
2370     EXPECT_EQ(AllNegative, CR.isAllNegative());
2371     EXPECT_EQ(AllNonNegative, CR.isAllNonNegative());
2372   });
2373 }
2374 
2375 TEST_F(ConstantRangeTest, UAddSat) {
2376   TestBinaryOpExhaustive(
2377       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2378         return CR1.uadd_sat(CR2);
2379       },
2380       [](const APInt &N1, const APInt &N2) {
2381         return N1.uadd_sat(N2);
2382       },
2383       PreferSmallestUnsigned);
2384 }
2385 
2386 TEST_F(ConstantRangeTest, USubSat) {
2387   TestBinaryOpExhaustive(
2388       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2389         return CR1.usub_sat(CR2);
2390       },
2391       [](const APInt &N1, const APInt &N2) {
2392         return N1.usub_sat(N2);
2393       },
2394       PreferSmallestUnsigned);
2395 }
2396 
2397 TEST_F(ConstantRangeTest, UMulSat) {
2398   TestBinaryOpExhaustive(
2399       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2400         return CR1.umul_sat(CR2);
2401       },
2402       [](const APInt &N1, const APInt &N2) { return N1.umul_sat(N2); },
2403       PreferSmallestUnsigned);
2404 }
2405 
2406 TEST_F(ConstantRangeTest, UShlSat) {
2407   TestBinaryOpExhaustive(
2408       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2409         return CR1.ushl_sat(CR2);
2410       },
2411       [](const APInt &N1, const APInt &N2) { return N1.ushl_sat(N2); },
2412       PreferSmallestUnsigned);
2413 }
2414 
2415 TEST_F(ConstantRangeTest, SAddSat) {
2416   TestBinaryOpExhaustive(
2417       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2418         return CR1.sadd_sat(CR2);
2419       },
2420       [](const APInt &N1, const APInt &N2) {
2421         return N1.sadd_sat(N2);
2422       },
2423       PreferSmallestSigned);
2424 }
2425 
2426 TEST_F(ConstantRangeTest, SSubSat) {
2427   TestBinaryOpExhaustive(
2428       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2429         return CR1.ssub_sat(CR2);
2430       },
2431       [](const APInt &N1, const APInt &N2) {
2432         return N1.ssub_sat(N2);
2433       },
2434       PreferSmallestSigned);
2435 }
2436 
2437 TEST_F(ConstantRangeTest, SMulSat) {
2438   TestBinaryOpExhaustive(
2439       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2440         return CR1.smul_sat(CR2);
2441       },
2442       [](const APInt &N1, const APInt &N2) { return N1.smul_sat(N2); },
2443       PreferSmallestSigned);
2444 }
2445 
2446 TEST_F(ConstantRangeTest, SShlSat) {
2447   TestBinaryOpExhaustive(
2448       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2449         return CR1.sshl_sat(CR2);
2450       },
2451       [](const APInt &N1, const APInt &N2) { return N1.sshl_sat(N2); },
2452       PreferSmallestSigned);
2453 }
2454 
2455 TEST_F(ConstantRangeTest, Abs) {
2456   TestUnaryOpExhaustive(
2457       [](const ConstantRange &CR) { return CR.abs(); },
2458       [](const APInt &N) { return N.abs(); });
2459 
2460   TestUnaryOpExhaustive(
2461       [](const ConstantRange &CR) { return CR.abs(/*IntMinIsPoison=*/true); },
2462       [](const APInt &N) -> Optional<APInt> {
2463         if (N.isMinSignedValue())
2464           return None;
2465         return N.abs();
2466       });
2467 }
2468 
2469 TEST_F(ConstantRangeTest, castOps) {
2470   ConstantRange A(APInt(16, 66), APInt(16, 128));
2471   ConstantRange FpToI8 = A.castOp(Instruction::FPToSI, 8);
2472   EXPECT_EQ(8u, FpToI8.getBitWidth());
2473   EXPECT_TRUE(FpToI8.isFullSet());
2474 
2475   ConstantRange FpToI16 = A.castOp(Instruction::FPToSI, 16);
2476   EXPECT_EQ(16u, FpToI16.getBitWidth());
2477   EXPECT_EQ(A, FpToI16);
2478 
2479   ConstantRange FPExtToDouble = A.castOp(Instruction::FPExt, 64);
2480   EXPECT_EQ(64u, FPExtToDouble.getBitWidth());
2481   EXPECT_TRUE(FPExtToDouble.isFullSet());
2482 
2483   ConstantRange PtrToInt = A.castOp(Instruction::PtrToInt, 64);
2484   EXPECT_EQ(64u, PtrToInt.getBitWidth());
2485   EXPECT_TRUE(PtrToInt.isFullSet());
2486 
2487   ConstantRange IntToPtr = A.castOp(Instruction::IntToPtr, 64);
2488   EXPECT_EQ(64u, IntToPtr.getBitWidth());
2489   EXPECT_TRUE(IntToPtr.isFullSet());
2490 }
2491 
2492 TEST_F(ConstantRangeTest, binaryXor) {
2493   // Single element ranges.
2494   ConstantRange R16(APInt(8, 16));
2495   ConstantRange R20(APInt(8, 20));
2496   EXPECT_EQ(*R16.binaryXor(R16).getSingleElement(), APInt(8, 0));
2497   EXPECT_EQ(*R16.binaryXor(R20).getSingleElement(), APInt(8, 16 ^ 20));
2498 
2499   // Ranges with more than a single element. Handled conservatively for now.
2500   ConstantRange R16_35(APInt(8, 16), APInt(8, 35));
2501   ConstantRange R0_99(APInt(8, 0), APInt(8, 99));
2502   EXPECT_TRUE(R16_35.binaryXor(R16_35).isFullSet());
2503   EXPECT_TRUE(R16_35.binaryXor(R0_99).isFullSet());
2504   EXPECT_TRUE(R0_99.binaryXor(R16_35).isFullSet());
2505 }
2506 
2507 TEST_F(ConstantRangeTest, binaryNot) {
2508   TestUnaryOpExhaustive(
2509       [](const ConstantRange &CR) { return CR.binaryNot(); },
2510       [](const APInt &N) { return ~N; },
2511       PreferSmallest);
2512   TestUnaryOpExhaustive(
2513       [](const ConstantRange &CR) {
2514         return CR.binaryXor(ConstantRange(APInt::getAllOnes(CR.getBitWidth())));
2515       },
2516       [](const APInt &N) { return ~N; }, PreferSmallest);
2517   TestUnaryOpExhaustive(
2518       [](const ConstantRange &CR) {
2519         return ConstantRange(APInt::getAllOnes(CR.getBitWidth())).binaryXor(CR);
2520       },
2521       [](const APInt &N) { return ~N; }, PreferSmallest);
2522 }
2523 
2524 template <typename T>
2525 void testConstantRangeICmpPredEquivalence(ICmpInst::Predicate SrcPred, T Func) {
2526   unsigned Bits = 4;
2527   EnumerateTwoConstantRanges(
2528       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
2529         ICmpInst::Predicate TgtPred;
2530         bool ExpectedEquivalent;
2531         std::tie(TgtPred, ExpectedEquivalent) = Func(CR1, CR2);
2532         if (TgtPred == CmpInst::Predicate::BAD_ICMP_PREDICATE)
2533           return;
2534         bool TrulyEquivalent = true;
2535         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
2536           if (!TrulyEquivalent)
2537             return;
2538           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
2539             if (!TrulyEquivalent)
2540               return;
2541             TrulyEquivalent &= ICmpInst::compare(N1, N2, SrcPred) ==
2542                                ICmpInst::compare(N1, N2, TgtPred);
2543           });
2544         });
2545         ASSERT_EQ(TrulyEquivalent, ExpectedEquivalent);
2546       });
2547 }
2548 
2549 TEST_F(ConstantRangeTest, areInsensitiveToSignednessOfICmpPredicate) {
2550   for (auto Pred : ICmpInst::predicates()) {
2551     if (ICmpInst::isEquality(Pred))
2552       continue;
2553     ICmpInst::Predicate FlippedSignednessPred =
2554         ICmpInst::getFlippedSignednessPredicate(Pred);
2555     testConstantRangeICmpPredEquivalence(Pred, [FlippedSignednessPred](
2556                                                    const ConstantRange &CR1,
2557                                                    const ConstantRange &CR2) {
2558       return std::make_pair(
2559           FlippedSignednessPred,
2560           ConstantRange::areInsensitiveToSignednessOfICmpPredicate(CR1, CR2));
2561     });
2562   }
2563 }
2564 
2565 TEST_F(ConstantRangeTest, areInsensitiveToSignednessOfInvertedICmpPredicate) {
2566   for (auto Pred : ICmpInst::predicates()) {
2567     if (ICmpInst::isEquality(Pred))
2568       continue;
2569     ICmpInst::Predicate InvertedFlippedSignednessPred =
2570         ICmpInst::getInversePredicate(
2571             ICmpInst::getFlippedSignednessPredicate(Pred));
2572     testConstantRangeICmpPredEquivalence(
2573         Pred, [InvertedFlippedSignednessPred](const ConstantRange &CR1,
2574                                               const ConstantRange &CR2) {
2575           return std::make_pair(
2576               InvertedFlippedSignednessPred,
2577               ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(
2578                   CR1, CR2));
2579         });
2580   }
2581 }
2582 
2583 TEST_F(ConstantRangeTest, getEquivalentPredWithFlippedSignedness) {
2584   for (auto Pred : ICmpInst::predicates()) {
2585     if (ICmpInst::isEquality(Pred))
2586       continue;
2587     testConstantRangeICmpPredEquivalence(
2588         Pred, [Pred](const ConstantRange &CR1, const ConstantRange &CR2) {
2589           return std::make_pair(
2590               ConstantRange::getEquivalentPredWithFlippedSignedness(Pred, CR1,
2591                                                                     CR2),
2592               /*ExpectedEquivalent=*/true);
2593         });
2594   }
2595 }
2596 
2597 } // anonymous namespace
2598