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, typename Fn3>
562 void testBinarySetOperationExhaustive(Fn1 OpFn, Fn2 ExactOpFn, Fn3 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         Optional<ConstantRange> ExactCR = ExactOpFn(CR1, CR2);
582         if (SmallestCR.isSizeLargerThan(Elems.count())) {
583           EXPECT_TRUE(!ExactCR.hasValue());
584         } else {
585           EXPECT_EQ(SmallestCR, *ExactCR);
586         }
587       });
588 }
589 
590 TEST_F(ConstantRangeTest, IntersectWithExhaustive) {
591   testBinarySetOperationExhaustive(
592       [](const ConstantRange &CR1, const ConstantRange &CR2,
593          ConstantRange::PreferredRangeType Type) {
594         return CR1.intersectWith(CR2, Type);
595       },
596       [](const ConstantRange &CR1, const ConstantRange &CR2) {
597         return CR1.exactIntersectWith(CR2);
598       },
599       [](const ConstantRange &CR1, const ConstantRange &CR2, const APInt &N) {
600         return CR1.contains(N) && CR2.contains(N);
601       });
602 }
603 
604 TEST_F(ConstantRangeTest, UnionWithExhaustive) {
605   testBinarySetOperationExhaustive(
606       [](const ConstantRange &CR1, const ConstantRange &CR2,
607          ConstantRange::PreferredRangeType Type) {
608         return CR1.unionWith(CR2, Type);
609       },
610       [](const ConstantRange &CR1, const ConstantRange &CR2) {
611         return CR1.exactUnionWith(CR2);
612       },
613       [](const ConstantRange &CR1, const ConstantRange &CR2, const APInt &N) {
614         return CR1.contains(N) || CR2.contains(N);
615       });
616 }
617 
618 TEST_F(ConstantRangeTest, UnionWith) {
619   EXPECT_EQ(Wrap.unionWith(One),
620             ConstantRange(APInt(16, 0xaaa), APInt(16, 0xb)));
621   EXPECT_EQ(One.unionWith(Wrap), Wrap.unionWith(One));
622   EXPECT_EQ(Empty.unionWith(Empty), Empty);
623   EXPECT_EQ(Full.unionWith(Full), Full);
624   EXPECT_EQ(Some.unionWith(Wrap), Full);
625 
626   // PR4545
627   EXPECT_EQ(ConstantRange(APInt(16, 14), APInt(16, 1)).unionWith(
628                                     ConstantRange(APInt(16, 0), APInt(16, 8))),
629             ConstantRange(APInt(16, 14), APInt(16, 8)));
630   EXPECT_EQ(ConstantRange(APInt(16, 6), APInt(16, 4)).unionWith(
631                                     ConstantRange(APInt(16, 4), APInt(16, 0))),
632             ConstantRange::getFull(16));
633   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 0)).unionWith(
634                                     ConstantRange(APInt(16, 2), APInt(16, 1))),
635             ConstantRange::getFull(16));
636 }
637 
638 TEST_F(ConstantRangeTest, SetDifference) {
639   EXPECT_EQ(Full.difference(Empty), Full);
640   EXPECT_EQ(Full.difference(Full), Empty);
641   EXPECT_EQ(Empty.difference(Empty), Empty);
642   EXPECT_EQ(Empty.difference(Full), Empty);
643 
644   ConstantRange A(APInt(16, 3), APInt(16, 7));
645   ConstantRange B(APInt(16, 5), APInt(16, 9));
646   ConstantRange C(APInt(16, 3), APInt(16, 5));
647   ConstantRange D(APInt(16, 7), APInt(16, 9));
648   ConstantRange E(APInt(16, 5), APInt(16, 4));
649   ConstantRange F(APInt(16, 7), APInt(16, 3));
650   EXPECT_EQ(A.difference(B), C);
651   EXPECT_EQ(B.difference(A), D);
652   EXPECT_EQ(E.difference(A), F);
653 }
654 
655 TEST_F(ConstantRangeTest, getActiveBits) {
656   unsigned Bits = 4;
657   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
658     unsigned Exact = 0;
659     ForeachNumInConstantRange(CR, [&](const APInt &N) {
660       Exact = std::max(Exact, N.getActiveBits());
661     });
662 
663     unsigned ResultCR = CR.getActiveBits();
664     EXPECT_EQ(Exact, ResultCR);
665   });
666 }
667 TEST_F(ConstantRangeTest, losslessUnsignedTruncationZeroext) {
668   unsigned Bits = 4;
669   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
670     unsigned MinBitWidth = CR.getActiveBits();
671     if (MinBitWidth == 0) {
672       EXPECT_TRUE(CR.isEmptySet() ||
673                   (CR.isSingleElement() && CR.getSingleElement()->isZero()));
674       return;
675     }
676     if (MinBitWidth == Bits)
677       return;
678     EXPECT_EQ(CR, CR.truncate(MinBitWidth).zeroExtend(Bits));
679   });
680 }
681 
682 TEST_F(ConstantRangeTest, getMinSignedBits) {
683   unsigned Bits = 4;
684   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
685     unsigned Exact = 0;
686     ForeachNumInConstantRange(CR, [&](const APInt &N) {
687       Exact = std::max(Exact, N.getMinSignedBits());
688     });
689 
690     unsigned ResultCR = CR.getMinSignedBits();
691     EXPECT_EQ(Exact, ResultCR);
692   });
693 }
694 TEST_F(ConstantRangeTest, losslessSignedTruncationSignext) {
695   unsigned Bits = 4;
696   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
697     unsigned MinBitWidth = CR.getMinSignedBits();
698     if (MinBitWidth == 0) {
699       EXPECT_TRUE(CR.isEmptySet());
700       return;
701     }
702     if (MinBitWidth == Bits)
703       return;
704     EXPECT_EQ(CR, CR.truncate(MinBitWidth).signExtend(Bits));
705   });
706 }
707 
708 TEST_F(ConstantRangeTest, SubtractAPInt) {
709   EXPECT_EQ(Full.subtract(APInt(16, 4)), Full);
710   EXPECT_EQ(Empty.subtract(APInt(16, 4)), Empty);
711   EXPECT_EQ(Some.subtract(APInt(16, 4)),
712             ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6)));
713   EXPECT_EQ(Wrap.subtract(APInt(16, 4)),
714             ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6)));
715   EXPECT_EQ(One.subtract(APInt(16, 4)),
716             ConstantRange(APInt(16, 0x6)));
717 }
718 
719 TEST_F(ConstantRangeTest, Add) {
720   EXPECT_EQ(Full.add(APInt(16, 4)), Full);
721   EXPECT_EQ(Full.add(Full), Full);
722   EXPECT_EQ(Full.add(Empty), Empty);
723   EXPECT_EQ(Full.add(One), Full);
724   EXPECT_EQ(Full.add(Some), Full);
725   EXPECT_EQ(Full.add(Wrap), Full);
726   EXPECT_EQ(Empty.add(Empty), Empty);
727   EXPECT_EQ(Empty.add(One), Empty);
728   EXPECT_EQ(Empty.add(Some), Empty);
729   EXPECT_EQ(Empty.add(Wrap), Empty);
730   EXPECT_EQ(Empty.add(APInt(16, 4)), Empty);
731   EXPECT_EQ(Some.add(APInt(16, 4)),
732             ConstantRange(APInt(16, 0xe), APInt(16, 0xaae)));
733   EXPECT_EQ(Wrap.add(APInt(16, 4)),
734             ConstantRange(APInt(16, 0xaae), APInt(16, 0xe)));
735   EXPECT_EQ(One.add(APInt(16, 4)),
736             ConstantRange(APInt(16, 0xe)));
737 
738   TestBinaryOpExhaustive(
739       [](const ConstantRange &CR1, const ConstantRange &CR2) {
740         return CR1.add(CR2);
741       },
742       [](const APInt &N1, const APInt &N2) {
743         return N1 + N2;
744       });
745 }
746 
747 template <typename Fn1, typename Fn2>
748 static void TestAddWithNoSignedWrapExhaustive(Fn1 RangeFn, Fn2 IntFn) {
749   unsigned Bits = 4;
750   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
751                                        const ConstantRange &CR2) {
752     ConstantRange CR = RangeFn(CR1, CR2);
753     SignedOpRangeGatherer R(CR.getBitWidth());
754     bool AllOverflow = true;
755     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
756       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
757         bool IsOverflow = false;
758         APInt N = IntFn(IsOverflow, N1, N2);
759         if (!IsOverflow) {
760           AllOverflow = false;
761           R.account(N);
762           EXPECT_TRUE(CR.contains(N));
763         }
764       });
765     });
766 
767     EXPECT_EQ(CR.isEmptySet(), AllOverflow);
768 
769     if (CR1.isSignWrappedSet() || CR2.isSignWrappedSet())
770       return;
771 
772     ConstantRange Exact = R.getRange();
773     EXPECT_EQ(Exact, CR);
774   });
775 }
776 
777 template <typename Fn1, typename Fn2>
778 static void TestAddWithNoUnsignedWrapExhaustive(Fn1 RangeFn, Fn2 IntFn) {
779   unsigned Bits = 4;
780   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
781                                        const ConstantRange &CR2) {
782     ConstantRange CR = RangeFn(CR1, CR2);
783     UnsignedOpRangeGatherer R(CR.getBitWidth());
784     bool AllOverflow = true;
785     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
786       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
787         bool IsOverflow = false;
788         APInt N = IntFn(IsOverflow, N1, N2);
789         if (!IsOverflow) {
790           AllOverflow = false;
791           R.account(N);
792           EXPECT_TRUE(CR.contains(N));
793         }
794       });
795     });
796 
797     EXPECT_EQ(CR.isEmptySet(), AllOverflow);
798 
799     if (CR1.isWrappedSet() || CR2.isWrappedSet())
800       return;
801 
802     ConstantRange Exact = R.getRange();
803     EXPECT_EQ(Exact, CR);
804   });
805 }
806 
807 template <typename Fn1, typename Fn2, typename Fn3>
808 static void TestAddWithNoSignedUnsignedWrapExhaustive(Fn1 RangeFn,
809                                                       Fn2 IntFnSigned,
810                                                       Fn3 IntFnUnsigned) {
811   unsigned Bits = 4;
812   EnumerateTwoConstantRanges(
813       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
814         ConstantRange CR = RangeFn(CR1, CR2);
815         UnsignedOpRangeGatherer UR(CR.getBitWidth());
816         SignedOpRangeGatherer SR(CR.getBitWidth());
817         bool AllOverflow = true;
818         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
819           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
820             bool IsOverflow = false, IsSignedOverflow = false;
821             APInt N = IntFnSigned(IsSignedOverflow, N1, N2);
822             (void) IntFnUnsigned(IsOverflow, N1, N2);
823             if (!IsSignedOverflow && !IsOverflow) {
824               AllOverflow = false;
825               UR.account(N);
826               SR.account(N);
827               EXPECT_TRUE(CR.contains(N));
828             }
829           });
830         });
831 
832         EXPECT_EQ(CR.isEmptySet(), AllOverflow);
833 
834         if (CR1.isWrappedSet() || CR2.isWrappedSet() ||
835             CR1.isSignWrappedSet() || CR2.isSignWrappedSet())
836           return;
837 
838         ConstantRange ExactUnsignedCR = UR.getRange();
839         ConstantRange ExactSignedCR = SR.getRange();
840 
841         if (ExactUnsignedCR.isEmptySet() || ExactSignedCR.isEmptySet()) {
842           EXPECT_TRUE(CR.isEmptySet());
843           return;
844         }
845 
846         ConstantRange Exact = ExactSignedCR.intersectWith(ExactUnsignedCR);
847         EXPECT_EQ(Exact, CR);
848       });
849 }
850 
851 TEST_F(ConstantRangeTest, AddWithNoWrap) {
852   typedef OverflowingBinaryOperator OBO;
853   EXPECT_EQ(Empty.addWithNoWrap(Some, OBO::NoSignedWrap), Empty);
854   EXPECT_EQ(Some.addWithNoWrap(Empty, OBO::NoSignedWrap), Empty);
855   EXPECT_EQ(Full.addWithNoWrap(Full, OBO::NoSignedWrap), Full);
856   EXPECT_NE(Full.addWithNoWrap(Some, OBO::NoSignedWrap), Full);
857   EXPECT_NE(Some.addWithNoWrap(Full, OBO::NoSignedWrap), Full);
858   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, 1), APInt(16, 2)),
859                                OBO::NoSignedWrap),
860             ConstantRange(APInt(16, INT16_MIN + 1), APInt(16, INT16_MIN)));
861   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 2))
862                 .addWithNoWrap(Full, OBO::NoSignedWrap),
863             ConstantRange(APInt(16, INT16_MIN + 1), APInt(16, INT16_MIN)));
864   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, -1), APInt(16, 0)),
865                                OBO::NoSignedWrap),
866             ConstantRange(APInt(16, INT16_MIN), APInt(16, INT16_MAX)));
867   EXPECT_EQ(ConstantRange(APInt(8, 100), APInt(8, 120))
868                 .addWithNoWrap(ConstantRange(APInt(8, 120), APInt(8, 123)),
869                                OBO::NoSignedWrap),
870             ConstantRange(8, false));
871   EXPECT_EQ(ConstantRange(APInt(8, -120), APInt(8, -100))
872                 .addWithNoWrap(ConstantRange(APInt(8, -110), APInt(8, -100)),
873                                OBO::NoSignedWrap),
874             ConstantRange(8, false));
875   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
876                 .addWithNoWrap(ConstantRange(APInt(8, -128), APInt(8, 28)),
877                                OBO::NoSignedWrap),
878             ConstantRange(8, true));
879   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
880                 .addWithNoWrap(ConstantRange(APInt(8, -120), APInt(8, 29)),
881                                OBO::NoSignedWrap),
882             ConstantRange(APInt(8, -120), APInt(8, -128)));
883   EXPECT_EQ(ConstantRange(APInt(8, -50), APInt(8, 50))
884                 .addWithNoWrap(ConstantRange(APInt(8, 10), APInt(8, 20)),
885                                OBO::NoSignedWrap),
886             ConstantRange(APInt(8, -40), APInt(8, 69)));
887   EXPECT_EQ(ConstantRange(APInt(8, 10), APInt(8, 20))
888                 .addWithNoWrap(ConstantRange(APInt(8, -50), APInt(8, 50)),
889                                OBO::NoSignedWrap),
890             ConstantRange(APInt(8, -40), APInt(8, 69)));
891   EXPECT_EQ(ConstantRange(APInt(8, 120), APInt(8, -10))
892                 .addWithNoWrap(ConstantRange(APInt(8, 5), APInt(8, 20)),
893                                OBO::NoSignedWrap),
894             ConstantRange(APInt(8, 125), APInt(8, 9)));
895   EXPECT_EQ(ConstantRange(APInt(8, 5), APInt(8, 20))
896                 .addWithNoWrap(ConstantRange(APInt(8, 120), APInt(8, -10)),
897                                OBO::NoSignedWrap),
898             ConstantRange(APInt(8, 125), APInt(8, 9)));
899 
900   TestAddWithNoSignedWrapExhaustive(
901       [](const ConstantRange &CR1, const ConstantRange &CR2) {
902         return CR1.addWithNoWrap(CR2, OBO::NoSignedWrap);
903       },
904       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
905         return N1.sadd_ov(N2, IsOverflow);
906       });
907 
908   EXPECT_EQ(Empty.addWithNoWrap(Some, OBO::NoUnsignedWrap), Empty);
909   EXPECT_EQ(Some.addWithNoWrap(Empty, OBO::NoUnsignedWrap), Empty);
910   EXPECT_EQ(Full.addWithNoWrap(Full, OBO::NoUnsignedWrap), Full);
911   EXPECT_NE(Full.addWithNoWrap(Some, OBO::NoUnsignedWrap), Full);
912   EXPECT_NE(Some.addWithNoWrap(Full, OBO::NoUnsignedWrap), Full);
913   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, 1), APInt(16, 2)),
914                                OBO::NoUnsignedWrap),
915             ConstantRange(APInt(16, 1), APInt(16, 0)));
916   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 2))
917                 .addWithNoWrap(Full, OBO::NoUnsignedWrap),
918             ConstantRange(APInt(16, 1), APInt(16, 0)));
919   EXPECT_EQ(ConstantRange(APInt(8, 200), APInt(8, 220))
920                 .addWithNoWrap(ConstantRange(APInt(8, 100), APInt(8, 123)),
921                                OBO::NoUnsignedWrap),
922             ConstantRange(8, false));
923   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
924                 .addWithNoWrap(ConstantRange(APInt(8, 0), APInt(8, 156)),
925                                OBO::NoUnsignedWrap),
926             ConstantRange(8, true));
927   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
928                 .addWithNoWrap(ConstantRange(APInt(8, 10), APInt(8, 29)),
929                                OBO::NoUnsignedWrap),
930             ConstantRange(APInt(8, 10), APInt(8, 129)));
931   EXPECT_EQ(ConstantRange(APInt(8, 20), APInt(8, 10))
932                 .addWithNoWrap(ConstantRange(APInt(8, 50), APInt(8, 200)),
933                                OBO::NoUnsignedWrap),
934             ConstantRange(APInt(8, 50), APInt(8, 0)));
935   EXPECT_EQ(ConstantRange(APInt(8, 10), APInt(8, 20))
936                 .addWithNoWrap(ConstantRange(APInt(8, 50), APInt(8, 200)),
937                                OBO::NoUnsignedWrap),
938             ConstantRange(APInt(8, 60), APInt(8, -37)));
939   EXPECT_EQ(ConstantRange(APInt(8, 20), APInt(8, -30))
940                 .addWithNoWrap(ConstantRange(APInt(8, 5), APInt(8, 20)),
941                                OBO::NoUnsignedWrap),
942             ConstantRange(APInt(8, 25), APInt(8, -11)));
943   EXPECT_EQ(ConstantRange(APInt(8, 5), APInt(8, 20))
944                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, -30)),
945                                OBO::NoUnsignedWrap),
946             ConstantRange(APInt(8, 25), APInt(8, -11)));
947 
948   TestAddWithNoUnsignedWrapExhaustive(
949       [](const ConstantRange &CR1, const ConstantRange &CR2) {
950         return CR1.addWithNoWrap(CR2, OBO::NoUnsignedWrap);
951       },
952       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
953         return N1.uadd_ov(N2, IsOverflow);
954       });
955 
956   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
957                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
958                                OBO::NoSignedWrap),
959             ConstantRange(APInt(8, 70), APInt(8, -128)));
960   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
961                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
962                                OBO::NoUnsignedWrap),
963             ConstantRange(APInt(8, 70), APInt(8, 169)));
964   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
965                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
966                                OBO::NoUnsignedWrap | OBO::NoSignedWrap),
967             ConstantRange(APInt(8, 70), APInt(8, -128)));
968 
969   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
970                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
971                                OBO::NoSignedWrap),
972             ConstantRange(APInt(8, -80), APInt(8, -21)));
973   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
974                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
975                                OBO::NoUnsignedWrap),
976             ConstantRange(APInt(8, 176), APInt(8, 235)));
977   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
978                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
979                                OBO::NoUnsignedWrap | OBO::NoSignedWrap),
980             ConstantRange(APInt(8, 176), APInt(8, 235)));
981 
982   TestAddWithNoSignedUnsignedWrapExhaustive(
983       [](const ConstantRange &CR1, const ConstantRange &CR2) {
984         return CR1.addWithNoWrap(CR2, OBO::NoUnsignedWrap | OBO::NoSignedWrap);
985       },
986       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
987         return N1.sadd_ov(N2, IsOverflow);
988       },
989       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
990         return N1.uadd_ov(N2, IsOverflow);
991       });
992 }
993 
994 TEST_F(ConstantRangeTest, Sub) {
995   EXPECT_EQ(Full.sub(APInt(16, 4)), Full);
996   EXPECT_EQ(Full.sub(Full), Full);
997   EXPECT_EQ(Full.sub(Empty), Empty);
998   EXPECT_EQ(Full.sub(One), Full);
999   EXPECT_EQ(Full.sub(Some), Full);
1000   EXPECT_EQ(Full.sub(Wrap), Full);
1001   EXPECT_EQ(Empty.sub(Empty), Empty);
1002   EXPECT_EQ(Empty.sub(One), Empty);
1003   EXPECT_EQ(Empty.sub(Some), Empty);
1004   EXPECT_EQ(Empty.sub(Wrap), Empty);
1005   EXPECT_EQ(Empty.sub(APInt(16, 4)), Empty);
1006   EXPECT_EQ(Some.sub(APInt(16, 4)),
1007             ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6)));
1008   EXPECT_EQ(Some.sub(Some),
1009             ConstantRange(APInt(16, 0xf561), APInt(16, 0xaa0)));
1010   EXPECT_EQ(Wrap.sub(APInt(16, 4)),
1011             ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6)));
1012   EXPECT_EQ(One.sub(APInt(16, 4)),
1013             ConstantRange(APInt(16, 0x6)));
1014 
1015   TestBinaryOpExhaustive(
1016       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1017         return CR1.sub(CR2);
1018       },
1019       [](const APInt &N1, const APInt &N2) {
1020         return N1 - N2;
1021       });
1022 }
1023 
1024 TEST_F(ConstantRangeTest, SubWithNoWrap) {
1025   typedef OverflowingBinaryOperator OBO;
1026   TestAddWithNoSignedWrapExhaustive(
1027       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1028         return CR1.subWithNoWrap(CR2, OBO::NoSignedWrap);
1029       },
1030       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1031         return N1.ssub_ov(N2, IsOverflow);
1032       });
1033   TestAddWithNoUnsignedWrapExhaustive(
1034       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1035         return CR1.subWithNoWrap(CR2, OBO::NoUnsignedWrap);
1036       },
1037       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1038         return N1.usub_ov(N2, IsOverflow);
1039       });
1040   TestAddWithNoSignedUnsignedWrapExhaustive(
1041       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1042         return CR1.subWithNoWrap(CR2, OBO::NoUnsignedWrap | OBO::NoSignedWrap);
1043       },
1044       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1045         return N1.ssub_ov(N2, IsOverflow);
1046       },
1047       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1048         return N1.usub_ov(N2, IsOverflow);
1049       });
1050 }
1051 
1052 TEST_F(ConstantRangeTest, Multiply) {
1053   EXPECT_EQ(Full.multiply(Full), Full);
1054   EXPECT_EQ(Full.multiply(Empty), Empty);
1055   EXPECT_EQ(Full.multiply(One), Full);
1056   EXPECT_EQ(Full.multiply(Some), Full);
1057   EXPECT_EQ(Full.multiply(Wrap), Full);
1058   EXPECT_EQ(Empty.multiply(Empty), Empty);
1059   EXPECT_EQ(Empty.multiply(One), Empty);
1060   EXPECT_EQ(Empty.multiply(Some), Empty);
1061   EXPECT_EQ(Empty.multiply(Wrap), Empty);
1062   EXPECT_EQ(One.multiply(One), ConstantRange(APInt(16, 0xa*0xa),
1063                                              APInt(16, 0xa*0xa + 1)));
1064   EXPECT_EQ(One.multiply(Some), ConstantRange(APInt(16, 0xa*0xa),
1065                                               APInt(16, 0xa*0xaa9 + 1)));
1066   EXPECT_EQ(One.multiply(Wrap), Full);
1067   EXPECT_EQ(Some.multiply(Some), Full);
1068   EXPECT_EQ(Some.multiply(Wrap), Full);
1069   EXPECT_EQ(Wrap.multiply(Wrap), Full);
1070 
1071   ConstantRange Zero(APInt(16, 0));
1072   EXPECT_EQ(Zero.multiply(Full), Zero);
1073   EXPECT_EQ(Zero.multiply(Some), Zero);
1074   EXPECT_EQ(Zero.multiply(Wrap), Zero);
1075   EXPECT_EQ(Full.multiply(Zero), Zero);
1076   EXPECT_EQ(Some.multiply(Zero), Zero);
1077   EXPECT_EQ(Wrap.multiply(Zero), Zero);
1078 
1079   // http://llvm.org/PR4545
1080   EXPECT_EQ(ConstantRange(APInt(4, 1), APInt(4, 6)).multiply(
1081                 ConstantRange(APInt(4, 6), APInt(4, 2))),
1082             ConstantRange(4, /*isFullSet=*/true));
1083 
1084   EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 0)).multiply(
1085               ConstantRange(APInt(8, 252), APInt(8, 4))),
1086             ConstantRange(APInt(8, 250), APInt(8, 9)));
1087   EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 255)).multiply(
1088               ConstantRange(APInt(8, 2), APInt(8, 4))),
1089             ConstantRange(APInt(8, 250), APInt(8, 253)));
1090 
1091   // TODO: This should be return [-2, 0]
1092   EXPECT_EQ(ConstantRange(APInt(8, -2)).multiply(
1093               ConstantRange(APInt(8, 0), APInt(8, 2))),
1094             ConstantRange(APInt(8, -2), APInt(8, 1)));
1095 }
1096 
1097 TEST_F(ConstantRangeTest, smul_fast) {
1098   TestBinaryOpExhaustive(
1099       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1100         return CR1.smul_fast(CR2);
1101       },
1102       [](const APInt &N1, const APInt &N2) {
1103         return N1 * N2;
1104       },
1105       PreferSmallest,
1106       [](const ConstantRange &, const ConstantRange &) {
1107         return false; // Check correctness only.
1108       });
1109 }
1110 
1111 TEST_F(ConstantRangeTest, UMax) {
1112   EXPECT_EQ(Full.umax(Full), Full);
1113   EXPECT_EQ(Full.umax(Empty), Empty);
1114   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1115   EXPECT_EQ(Full.umax(Wrap), Full);
1116   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1117   EXPECT_EQ(Empty.umax(Empty), Empty);
1118   EXPECT_EQ(Empty.umax(Some), Empty);
1119   EXPECT_EQ(Empty.umax(Wrap), Empty);
1120   EXPECT_EQ(Empty.umax(One), Empty);
1121   EXPECT_EQ(Some.umax(Some), Some);
1122   EXPECT_EQ(Some.umax(Wrap), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1123   EXPECT_EQ(Some.umax(One), Some);
1124   EXPECT_EQ(Wrap.umax(Wrap), Wrap);
1125   EXPECT_EQ(Wrap.umax(One), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1126   EXPECT_EQ(One.umax(One), One);
1127 
1128   TestBinaryOpExhaustive(
1129       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1130         return CR1.umax(CR2);
1131       },
1132       [](const APInt &N1, const APInt &N2) {
1133         return APIntOps::umax(N1, N2);
1134       },
1135       PreferSmallestNonFullUnsigned);
1136 }
1137 
1138 TEST_F(ConstantRangeTest, SMax) {
1139   EXPECT_EQ(Full.smax(Full), Full);
1140   EXPECT_EQ(Full.smax(Empty), Empty);
1141   EXPECT_EQ(Full.smax(Some), ConstantRange(APInt(16, 0xa),
1142                                            APInt::getSignedMinValue(16)));
1143   EXPECT_EQ(Full.smax(Wrap), Full);
1144   EXPECT_EQ(Full.smax(One), ConstantRange(APInt(16, 0xa),
1145                                           APInt::getSignedMinValue(16)));
1146   EXPECT_EQ(Empty.smax(Empty), Empty);
1147   EXPECT_EQ(Empty.smax(Some), Empty);
1148   EXPECT_EQ(Empty.smax(Wrap), Empty);
1149   EXPECT_EQ(Empty.smax(One), Empty);
1150   EXPECT_EQ(Some.smax(Some), Some);
1151   EXPECT_EQ(Some.smax(Wrap), ConstantRange(APInt(16, 0xa),
1152                                            APInt(16, (uint64_t)INT16_MIN)));
1153   EXPECT_EQ(Some.smax(One), Some);
1154   EXPECT_EQ(Wrap.smax(One), ConstantRange(APInt(16, 0xa),
1155                                           APInt(16, (uint64_t)INT16_MIN)));
1156   EXPECT_EQ(One.smax(One), One);
1157 
1158   TestBinaryOpExhaustive(
1159       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1160         return CR1.smax(CR2);
1161       },
1162       [](const APInt &N1, const APInt &N2) {
1163         return APIntOps::smax(N1, N2);
1164       },
1165       PreferSmallestNonFullSigned);
1166 }
1167 
1168 TEST_F(ConstantRangeTest, UMin) {
1169   EXPECT_EQ(Full.umin(Full), Full);
1170   EXPECT_EQ(Full.umin(Empty), Empty);
1171   EXPECT_EQ(Full.umin(Some), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1172   EXPECT_EQ(Full.umin(Wrap), Full);
1173   EXPECT_EQ(Empty.umin(Empty), Empty);
1174   EXPECT_EQ(Empty.umin(Some), Empty);
1175   EXPECT_EQ(Empty.umin(Wrap), Empty);
1176   EXPECT_EQ(Empty.umin(One), Empty);
1177   EXPECT_EQ(Some.umin(Some), Some);
1178   EXPECT_EQ(Some.umin(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1179   EXPECT_EQ(Some.umin(One), One);
1180   EXPECT_EQ(Wrap.umin(Wrap), Wrap);
1181   EXPECT_EQ(Wrap.umin(One), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1182   EXPECT_EQ(One.umin(One), One);
1183 
1184   TestBinaryOpExhaustive(
1185       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1186         return CR1.umin(CR2);
1187       },
1188       [](const APInt &N1, const APInt &N2) {
1189         return APIntOps::umin(N1, N2);
1190       },
1191       PreferSmallestNonFullUnsigned);
1192 }
1193 
1194 TEST_F(ConstantRangeTest, SMin) {
1195   EXPECT_EQ(Full.smin(Full), Full);
1196   EXPECT_EQ(Full.smin(Empty), Empty);
1197   EXPECT_EQ(Full.smin(Some), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1198                                            APInt(16, 0xaaa)));
1199   EXPECT_EQ(Full.smin(Wrap), Full);
1200   EXPECT_EQ(Empty.smin(Empty), Empty);
1201   EXPECT_EQ(Empty.smin(Some), Empty);
1202   EXPECT_EQ(Empty.smin(Wrap), Empty);
1203   EXPECT_EQ(Empty.smin(One), Empty);
1204   EXPECT_EQ(Some.smin(Some), Some);
1205   EXPECT_EQ(Some.smin(Wrap), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1206                                            APInt(16, 0xaaa)));
1207   EXPECT_EQ(Some.smin(One), One);
1208   EXPECT_EQ(Wrap.smin(Wrap), Wrap);
1209   EXPECT_EQ(Wrap.smin(One), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1210                                           APInt(16, 0xb)));
1211   EXPECT_EQ(One.smin(One), One);
1212 
1213   TestBinaryOpExhaustive(
1214       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1215         return CR1.smin(CR2);
1216       },
1217       [](const APInt &N1, const APInt &N2) {
1218         return APIntOps::smin(N1, N2);
1219       },
1220       PreferSmallestNonFullSigned);
1221 }
1222 
1223 TEST_F(ConstantRangeTest, UDiv) {
1224   EXPECT_EQ(Full.udiv(Full), Full);
1225   EXPECT_EQ(Full.udiv(Empty), Empty);
1226   EXPECT_EQ(Full.udiv(One), ConstantRange(APInt(16, 0),
1227                                           APInt(16, 0xffff / 0xa + 1)));
1228   EXPECT_EQ(Full.udiv(Some), ConstantRange(APInt(16, 0),
1229                                            APInt(16, 0xffff / 0xa + 1)));
1230   EXPECT_EQ(Full.udiv(Wrap), Full);
1231   EXPECT_EQ(Empty.udiv(Empty), Empty);
1232   EXPECT_EQ(Empty.udiv(One), Empty);
1233   EXPECT_EQ(Empty.udiv(Some), Empty);
1234   EXPECT_EQ(Empty.udiv(Wrap), Empty);
1235   EXPECT_EQ(One.udiv(One), ConstantRange(APInt(16, 1)));
1236   EXPECT_EQ(One.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 2)));
1237   EXPECT_EQ(One.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1238   EXPECT_EQ(Some.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 0x111)));
1239   EXPECT_EQ(Some.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1240   EXPECT_EQ(Wrap.udiv(Wrap), Full);
1241 
1242 
1243   ConstantRange Zero(APInt(16, 0));
1244   EXPECT_EQ(Zero.udiv(One), Zero);
1245   EXPECT_EQ(Zero.udiv(Full), Zero);
1246 
1247   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 99)).udiv(Full),
1248             ConstantRange(APInt(16, 0), APInt(16, 99)));
1249   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 99)).udiv(Full),
1250             ConstantRange(APInt(16, 0), APInt(16, 99)));
1251 }
1252 
1253 TEST_F(ConstantRangeTest, SDiv) {
1254   unsigned Bits = 4;
1255   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
1256                                        const ConstantRange &CR2) {
1257     // Collect possible results in a bit vector. We store the signed value plus
1258     // a bias to make it unsigned.
1259     int Bias = 1 << (Bits - 1);
1260     BitVector Results(1 << Bits);
1261     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1262       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
1263         // Division by zero is UB.
1264         if (N2 == 0)
1265           return;
1266 
1267         // SignedMin / -1 is UB.
1268         if (N1.isMinSignedValue() && N2.isAllOnes())
1269           return;
1270 
1271         APInt N = N1.sdiv(N2);
1272         Results.set(N.getSExtValue() + Bias);
1273       });
1274     });
1275 
1276     ConstantRange CR = CR1.sdiv(CR2);
1277     if (Results.none()) {
1278       EXPECT_TRUE(CR.isEmptySet());
1279       return;
1280     }
1281 
1282     // If there is a non-full signed envelope, that should be the result.
1283     APInt SMin(Bits, Results.find_first() - Bias);
1284     APInt SMax(Bits, Results.find_last() - Bias);
1285     ConstantRange Envelope = ConstantRange::getNonEmpty(SMin, SMax + 1);
1286     if (!Envelope.isFullSet()) {
1287       EXPECT_EQ(Envelope, CR);
1288       return;
1289     }
1290 
1291     // If the signed envelope is a full set, try to find a smaller sign wrapped
1292     // set that is separated in negative and positive components (or one which
1293     // can also additionally contain zero).
1294     int LastNeg = Results.find_last_in(0, Bias) - Bias;
1295     int LastPos = Results.find_next(Bias) - Bias;
1296     if (Results[Bias]) {
1297       if (LastNeg == -1)
1298         ++LastNeg;
1299       else if (LastPos == 1)
1300         --LastPos;
1301     }
1302 
1303     APInt WMax(Bits, LastNeg);
1304     APInt WMin(Bits, LastPos);
1305     ConstantRange Wrapped = ConstantRange::getNonEmpty(WMin, WMax + 1);
1306     EXPECT_EQ(Wrapped, CR);
1307   });
1308 }
1309 
1310 TEST_F(ConstantRangeTest, URem) {
1311   EXPECT_EQ(Full.urem(Empty), Empty);
1312   EXPECT_EQ(Empty.urem(Full), Empty);
1313   // urem by zero is poison.
1314   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0))), Empty);
1315   // urem by full range doesn't contain MaxValue.
1316   EXPECT_EQ(Full.urem(Full), ConstantRange(APInt(16, 0), APInt(16, 0xffff)));
1317   // urem is upper bounded by maximum RHS minus one.
1318   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0), APInt(16, 123))),
1319             ConstantRange(APInt(16, 0), APInt(16, 122)));
1320   // urem is upper bounded by maximum LHS.
1321   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 123)).urem(Full),
1322             ConstantRange(APInt(16, 0), APInt(16, 123)));
1323   // If the LHS is always lower than the RHS, the result is the LHS.
1324   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1325                 .urem(ConstantRange(APInt(16, 20), APInt(16, 30))),
1326             ConstantRange(APInt(16, 10), APInt(16, 20)));
1327   // It has to be strictly lower, otherwise the top value may wrap to zero.
1328   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1329                 .urem(ConstantRange(APInt(16, 19), APInt(16, 30))),
1330             ConstantRange(APInt(16, 0), APInt(16, 20)));
1331   // [12, 14] % 10 is [2, 4], but we conservatively compute [0, 9].
1332   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1333                 .urem(ConstantRange(APInt(16, 10))),
1334             ConstantRange(APInt(16, 0), APInt(16, 10)));
1335 
1336   TestBinaryOpExhaustive(
1337       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1338         return CR1.urem(CR2);
1339       },
1340       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1341         if (N2.isZero())
1342           return None;
1343         return N1.urem(N2);
1344       },
1345       PreferSmallest,
1346       CheckSingleElementsOnly);
1347 }
1348 
1349 TEST_F(ConstantRangeTest, SRem) {
1350   EXPECT_EQ(Full.srem(Empty), Empty);
1351   EXPECT_EQ(Empty.srem(Full), Empty);
1352   // srem by zero is UB.
1353   EXPECT_EQ(Full.srem(ConstantRange(APInt(16, 0))), Empty);
1354   // srem by full range doesn't contain SignedMinValue.
1355   EXPECT_EQ(Full.srem(Full), ConstantRange(APInt::getSignedMinValue(16) + 1,
1356                                            APInt::getSignedMinValue(16)));
1357 
1358   ConstantRange PosMod(APInt(16, 10), APInt(16, 21));  // [10, 20]
1359   ConstantRange NegMod(APInt(16, -20), APInt(16, -9)); // [-20, -10]
1360   ConstantRange IntMinMod(APInt::getSignedMinValue(16));
1361 
1362   ConstantRange Expected(16, true);
1363 
1364   // srem is bounded by abs(RHS) minus one.
1365   ConstantRange PosLargeLHS(APInt(16, 0), APInt(16, 41));
1366   Expected = ConstantRange(APInt(16, 0), APInt(16, 20));
1367   EXPECT_EQ(PosLargeLHS.srem(PosMod), Expected);
1368   EXPECT_EQ(PosLargeLHS.srem(NegMod), Expected);
1369   ConstantRange NegLargeLHS(APInt(16, -40), APInt(16, 1));
1370   Expected = ConstantRange(APInt(16, -19), APInt(16, 1));
1371   EXPECT_EQ(NegLargeLHS.srem(PosMod), Expected);
1372   EXPECT_EQ(NegLargeLHS.srem(NegMod), Expected);
1373   ConstantRange PosNegLargeLHS(APInt(16, -32), APInt(16, 38));
1374   Expected = ConstantRange(APInt(16, -19), APInt(16, 20));
1375   EXPECT_EQ(PosNegLargeLHS.srem(PosMod), Expected);
1376   EXPECT_EQ(PosNegLargeLHS.srem(NegMod), Expected);
1377 
1378   // srem is bounded by LHS.
1379   ConstantRange PosLHS(APInt(16, 0), APInt(16, 16));
1380   EXPECT_EQ(PosLHS.srem(PosMod), PosLHS);
1381   EXPECT_EQ(PosLHS.srem(NegMod), PosLHS);
1382   EXPECT_EQ(PosLHS.srem(IntMinMod), PosLHS);
1383   ConstantRange NegLHS(APInt(16, -15), APInt(16, 1));
1384   EXPECT_EQ(NegLHS.srem(PosMod), NegLHS);
1385   EXPECT_EQ(NegLHS.srem(NegMod), NegLHS);
1386   EXPECT_EQ(NegLHS.srem(IntMinMod), NegLHS);
1387   ConstantRange PosNegLHS(APInt(16, -12), APInt(16, 18));
1388   EXPECT_EQ(PosNegLHS.srem(PosMod), PosNegLHS);
1389   EXPECT_EQ(PosNegLHS.srem(NegMod), PosNegLHS);
1390   EXPECT_EQ(PosNegLHS.srem(IntMinMod), PosNegLHS);
1391 
1392   // srem is LHS if it is smaller than RHS.
1393   ConstantRange PosSmallLHS(APInt(16, 3), APInt(16, 8));
1394   EXPECT_EQ(PosSmallLHS.srem(PosMod), PosSmallLHS);
1395   EXPECT_EQ(PosSmallLHS.srem(NegMod), PosSmallLHS);
1396   EXPECT_EQ(PosSmallLHS.srem(IntMinMod), PosSmallLHS);
1397   ConstantRange NegSmallLHS(APInt(16, -7), APInt(16, -2));
1398   EXPECT_EQ(NegSmallLHS.srem(PosMod), NegSmallLHS);
1399   EXPECT_EQ(NegSmallLHS.srem(NegMod), NegSmallLHS);
1400   EXPECT_EQ(NegSmallLHS.srem(IntMinMod), NegSmallLHS);
1401   ConstantRange PosNegSmallLHS(APInt(16, -3), APInt(16, 8));
1402   EXPECT_EQ(PosNegSmallLHS.srem(PosMod), PosNegSmallLHS);
1403   EXPECT_EQ(PosNegSmallLHS.srem(NegMod), PosNegSmallLHS);
1404   EXPECT_EQ(PosNegSmallLHS.srem(IntMinMod), PosNegSmallLHS);
1405 
1406   // Example of a suboptimal result:
1407   // [12, 14] srem 10 is [2, 4], but we conservatively compute [0, 9].
1408   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1409                 .srem(ConstantRange(APInt(16, 10))),
1410             ConstantRange(APInt(16, 0), APInt(16, 10)));
1411 
1412   TestBinaryOpExhaustive(
1413       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1414         return CR1.srem(CR2);
1415       },
1416       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1417         if (N2.isZero())
1418           return None;
1419         return N1.srem(N2);
1420       },
1421       PreferSmallest,
1422       CheckSingleElementsOnly);
1423 }
1424 
1425 TEST_F(ConstantRangeTest, Shl) {
1426   ConstantRange Some2(APInt(16, 0xfff), APInt(16, 0x8000));
1427   ConstantRange WrapNullMax(APInt(16, 0x1), APInt(16, 0x0));
1428   EXPECT_EQ(Full.shl(Full), Full);
1429   EXPECT_EQ(Full.shl(Empty), Empty);
1430   EXPECT_EQ(Full.shl(One), ConstantRange(APInt(16, 0),
1431                                          APInt(16, 0xfc00) + 1));
1432   EXPECT_EQ(Full.shl(Some), Full);   // TODO: [0, (-1 << 0xa) + 1)
1433   EXPECT_EQ(Full.shl(Wrap), Full);
1434   EXPECT_EQ(Empty.shl(Empty), Empty);
1435   EXPECT_EQ(Empty.shl(One), Empty);
1436   EXPECT_EQ(Empty.shl(Some), Empty);
1437   EXPECT_EQ(Empty.shl(Wrap), Empty);
1438   EXPECT_EQ(One.shl(One), ConstantRange(APInt(16, 0xa << 0xa),
1439                                         APInt(16, (0xa << 0xa) + 1)));
1440   EXPECT_EQ(One.shl(Some), Full);    // TODO: [0xa << 0xa, 0)
1441   EXPECT_EQ(One.shl(Wrap), Full);    // TODO: [0xa, 0xa << 14 + 1)
1442   EXPECT_EQ(Some.shl(Some), Full);   // TODO: [0xa << 0xa, 0xfc01)
1443   EXPECT_EQ(Some.shl(Wrap), Full);   // TODO: [0xa, 0x7ff << 0x5 + 1)
1444   EXPECT_EQ(Wrap.shl(Wrap), Full);
1445   EXPECT_EQ(
1446       Some2.shl(ConstantRange(APInt(16, 0x1))),
1447       ConstantRange(APInt(16, 0xfff << 0x1), APInt(16, 0x7fff << 0x1) + 1));
1448   EXPECT_EQ(One.shl(WrapNullMax), Full);
1449 
1450   TestBinaryOpExhaustive(
1451       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1452         return CR1.shl(CR2);
1453       },
1454       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1455         if (N2.uge(N2.getBitWidth()))
1456           return None;
1457         return N1.shl(N2);
1458       },
1459       PreferSmallestUnsigned,
1460       [](const ConstantRange &, const ConstantRange &CR2) {
1461         // We currently only produce precise results for single element RHS.
1462         return CR2.isSingleElement();
1463       });
1464 }
1465 
1466 TEST_F(ConstantRangeTest, Lshr) {
1467   EXPECT_EQ(Full.lshr(Full), Full);
1468   EXPECT_EQ(Full.lshr(Empty), Empty);
1469   EXPECT_EQ(Full.lshr(One), ConstantRange(APInt(16, 0),
1470                                           APInt(16, (0xffff >> 0xa) + 1)));
1471   EXPECT_EQ(Full.lshr(Some), ConstantRange(APInt(16, 0),
1472                                            APInt(16, (0xffff >> 0xa) + 1)));
1473   EXPECT_EQ(Full.lshr(Wrap), Full);
1474   EXPECT_EQ(Empty.lshr(Empty), Empty);
1475   EXPECT_EQ(Empty.lshr(One), Empty);
1476   EXPECT_EQ(Empty.lshr(Some), Empty);
1477   EXPECT_EQ(Empty.lshr(Wrap), Empty);
1478   EXPECT_EQ(One.lshr(One), ConstantRange(APInt(16, 0)));
1479   EXPECT_EQ(One.lshr(Some), ConstantRange(APInt(16, 0)));
1480   EXPECT_EQ(One.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1481   EXPECT_EQ(Some.lshr(Some), ConstantRange(APInt(16, 0),
1482                                            APInt(16, (0xaaa >> 0xa) + 1)));
1483   EXPECT_EQ(Some.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1484   EXPECT_EQ(Wrap.lshr(Wrap), Full);
1485 }
1486 
1487 TEST_F(ConstantRangeTest, Ashr) {
1488   EXPECT_EQ(Full.ashr(Full), Full);
1489   EXPECT_EQ(Full.ashr(Empty), Empty);
1490   EXPECT_EQ(Full.ashr(One), ConstantRange(APInt(16, 0xffe0),
1491                                           APInt(16, (0x7fff >> 0xa) + 1 )));
1492   ConstantRange Small(APInt(16, 0xa), APInt(16, 0xb));
1493   EXPECT_EQ(Full.ashr(Small), ConstantRange(APInt(16, 0xffe0),
1494                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1495   EXPECT_EQ(Full.ashr(Some), ConstantRange(APInt(16, 0xffe0),
1496                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1497   EXPECT_EQ(Full.ashr(Wrap), Full);
1498   EXPECT_EQ(Empty.ashr(Empty), Empty);
1499   EXPECT_EQ(Empty.ashr(One), Empty);
1500   EXPECT_EQ(Empty.ashr(Some), Empty);
1501   EXPECT_EQ(Empty.ashr(Wrap), Empty);
1502   EXPECT_EQ(One.ashr(One), ConstantRange(APInt(16, 0)));
1503   EXPECT_EQ(One.ashr(Some), ConstantRange(APInt(16, 0)));
1504   EXPECT_EQ(One.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1505   EXPECT_EQ(Some.ashr(Some), ConstantRange(APInt(16, 0),
1506                                            APInt(16, (0xaaa >> 0xa) + 1)));
1507   EXPECT_EQ(Some.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1508   EXPECT_EQ(Wrap.ashr(Wrap), Full);
1509   ConstantRange Neg(APInt(16, 0xf3f0, true), APInt(16, 0xf7f8, true));
1510   EXPECT_EQ(Neg.ashr(Small), ConstantRange(APInt(16, 0xfffc, true),
1511                                            APInt(16, 0xfffe, true)));
1512 }
1513 
1514 TEST(ConstantRange, MakeAllowedICmpRegion) {
1515   // PR8250
1516   ConstantRange SMax = ConstantRange(APInt::getSignedMaxValue(32));
1517   EXPECT_TRUE(ConstantRange::makeAllowedICmpRegion(ICmpInst::ICMP_SGT, SMax)
1518                   .isEmptySet());
1519 }
1520 
1521 TEST(ConstantRange, MakeSatisfyingICmpRegion) {
1522   ConstantRange LowHalf(APInt(8, 0), APInt(8, 128));
1523   ConstantRange HighHalf(APInt(8, 128), APInt(8, 0));
1524   ConstantRange EmptySet(8, /* isFullSet = */ false);
1525 
1526   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, LowHalf),
1527             HighHalf);
1528 
1529   EXPECT_EQ(
1530       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, HighHalf),
1531       LowHalf);
1532 
1533   EXPECT_TRUE(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_EQ,
1534                                                       HighHalf).isEmptySet());
1535 
1536   ConstantRange UnsignedSample(APInt(8, 5), APInt(8, 200));
1537 
1538   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULT,
1539                                                     UnsignedSample),
1540             ConstantRange(APInt(8, 0), APInt(8, 5)));
1541 
1542   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULE,
1543                                                     UnsignedSample),
1544             ConstantRange(APInt(8, 0), APInt(8, 6)));
1545 
1546   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGT,
1547                                                     UnsignedSample),
1548             ConstantRange(APInt(8, 200), APInt(8, 0)));
1549 
1550   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGE,
1551                                                     UnsignedSample),
1552             ConstantRange(APInt(8, 199), APInt(8, 0)));
1553 
1554   ConstantRange SignedSample(APInt(8, -5), APInt(8, 5));
1555 
1556   EXPECT_EQ(
1557       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLT, SignedSample),
1558       ConstantRange(APInt(8, -128), APInt(8, -5)));
1559 
1560   EXPECT_EQ(
1561       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLE, SignedSample),
1562       ConstantRange(APInt(8, -128), APInt(8, -4)));
1563 
1564   EXPECT_EQ(
1565       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGT, SignedSample),
1566       ConstantRange(APInt(8, 5), APInt(8, -128)));
1567 
1568   EXPECT_EQ(
1569       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGE, SignedSample),
1570       ConstantRange(APInt(8, 4), APInt(8, -128)));
1571 }
1572 
1573 void ICmpTestImpl(CmpInst::Predicate Pred) {
1574   unsigned Bits = 4;
1575   EnumerateTwoConstantRanges(
1576       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
1577         bool Exhaustive = true;
1578         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1579           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
1580             Exhaustive &= ICmpInst::compare(N1, N2, Pred);
1581           });
1582         });
1583         EXPECT_EQ(CR1.icmp(Pred, CR2), Exhaustive);
1584       });
1585 }
1586 
1587 TEST(ConstantRange, ICmp) {
1588   for (auto Pred : ICmpInst::predicates())
1589     ICmpTestImpl(Pred);
1590 }
1591 
1592 TEST(ConstantRange, MakeGuaranteedNoWrapRegion) {
1593   const int IntMin4Bits = 8;
1594   const int IntMax4Bits = 7;
1595   typedef OverflowingBinaryOperator OBO;
1596 
1597   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1598     APInt C(4, Const, true /* = isSigned */);
1599 
1600     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1601         Instruction::Add, C, OBO::NoUnsignedWrap);
1602 
1603     EXPECT_FALSE(NUWRegion.isEmptySet());
1604 
1605     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1606         Instruction::Add, C, OBO::NoSignedWrap);
1607 
1608     EXPECT_FALSE(NSWRegion.isEmptySet());
1609 
1610     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1611          ++I) {
1612       bool Overflow = false;
1613       (void)I.uadd_ov(C, Overflow);
1614       EXPECT_FALSE(Overflow);
1615     }
1616 
1617     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1618          ++I) {
1619       bool Overflow = false;
1620       (void)I.sadd_ov(C, Overflow);
1621       EXPECT_FALSE(Overflow);
1622     }
1623   }
1624 
1625   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1626     APInt C(4, Const, true /* = isSigned */);
1627 
1628     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1629         Instruction::Sub, C, OBO::NoUnsignedWrap);
1630 
1631     EXPECT_FALSE(NUWRegion.isEmptySet());
1632 
1633     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1634         Instruction::Sub, C, OBO::NoSignedWrap);
1635 
1636     EXPECT_FALSE(NSWRegion.isEmptySet());
1637 
1638     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1639          ++I) {
1640       bool Overflow = false;
1641       (void)I.usub_ov(C, Overflow);
1642       EXPECT_FALSE(Overflow);
1643     }
1644 
1645     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1646          ++I) {
1647       bool Overflow = false;
1648       (void)I.ssub_ov(C, Overflow);
1649       EXPECT_FALSE(Overflow);
1650     }
1651   }
1652 
1653   auto NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1654       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1655       OBO::NoSignedWrap);
1656   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1657               NSWForAllValues.getSingleElement()->isMinValue());
1658 
1659   NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1660       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1661       OBO::NoSignedWrap);
1662   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1663               NSWForAllValues.getSingleElement()->isMaxValue());
1664 
1665   auto NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1666       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1667       OBO::NoUnsignedWrap);
1668   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1669               NUWForAllValues.getSingleElement()->isMinValue());
1670 
1671   NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1672       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1673       OBO::NoUnsignedWrap);
1674   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1675               NUWForAllValues.getSingleElement()->isMaxValue());
1676 
1677   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1678       Instruction::Add, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1679   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1680       Instruction::Add, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1681   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1682       Instruction::Sub, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1683   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1684       Instruction::Sub, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1685 
1686   ConstantRange OneToFive(APInt(32, 1), APInt(32, 6));
1687   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1688                 Instruction::Add, OneToFive, OBO::NoSignedWrap),
1689             ConstantRange(APInt::getSignedMinValue(32),
1690                           APInt::getSignedMaxValue(32) - 4));
1691   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1692                 Instruction::Add, OneToFive, OBO::NoUnsignedWrap),
1693             ConstantRange(APInt::getMinValue(32), APInt::getMinValue(32) - 5));
1694   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1695                 Instruction::Sub, OneToFive, OBO::NoSignedWrap),
1696             ConstantRange(APInt::getSignedMinValue(32) + 5,
1697                           APInt::getSignedMinValue(32)));
1698   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1699                 Instruction::Sub, OneToFive, OBO::NoUnsignedWrap),
1700             ConstantRange(APInt::getMinValue(32) + 5, APInt::getMinValue(32)));
1701 
1702   ConstantRange MinusFiveToMinusTwo(APInt(32, -5), APInt(32, -1));
1703   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1704                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1705             ConstantRange(APInt::getSignedMinValue(32) + 5,
1706                           APInt::getSignedMinValue(32)));
1707   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1708                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1709             ConstantRange(APInt(32, 0), APInt(32, 2)));
1710   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1711                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1712             ConstantRange(APInt::getSignedMinValue(32),
1713                           APInt::getSignedMaxValue(32) - 4));
1714   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1715                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1716             ConstantRange(APInt::getMaxValue(32) - 1,
1717                           APInt::getMinValue(32)));
1718 
1719   ConstantRange MinusOneToOne(APInt(32, -1), APInt(32, 2));
1720   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1721                 Instruction::Add, MinusOneToOne, OBO::NoSignedWrap),
1722             ConstantRange(APInt::getSignedMinValue(32) + 1,
1723                           APInt::getSignedMinValue(32) - 1));
1724   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1725                 Instruction::Add, MinusOneToOne, OBO::NoUnsignedWrap),
1726             ConstantRange(APInt(32, 0), APInt(32, 1)));
1727   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1728                 Instruction::Sub, MinusOneToOne, OBO::NoSignedWrap),
1729             ConstantRange(APInt::getSignedMinValue(32) + 1,
1730                           APInt::getSignedMinValue(32) - 1));
1731   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1732                 Instruction::Sub, MinusOneToOne, OBO::NoUnsignedWrap),
1733             ConstantRange(APInt::getMaxValue(32),
1734                           APInt::getMinValue(32)));
1735 
1736   ConstantRange One(APInt(32, 1), APInt(32, 2));
1737   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1738                 Instruction::Add, One, OBO::NoSignedWrap),
1739             ConstantRange(APInt::getSignedMinValue(32),
1740                           APInt::getSignedMaxValue(32)));
1741   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1742                 Instruction::Add, One, OBO::NoUnsignedWrap),
1743             ConstantRange(APInt::getMinValue(32), APInt::getMaxValue(32)));
1744   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1745                 Instruction::Sub, One, OBO::NoSignedWrap),
1746             ConstantRange(APInt::getSignedMinValue(32) + 1,
1747                           APInt::getSignedMinValue(32)));
1748   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1749                 Instruction::Sub, One, OBO::NoUnsignedWrap),
1750             ConstantRange(APInt::getMinValue(32) + 1, APInt::getMinValue(32)));
1751 
1752   ConstantRange OneLessThanBitWidth(APInt(32, 0), APInt(32, 31) + 1);
1753   ConstantRange UpToBitWidth(APInt(32, 0), APInt(32, 32) + 1);
1754   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1755                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1756             ConstantRange::makeGuaranteedNoWrapRegion(
1757                 Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1758   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1759                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1760             ConstantRange::makeGuaranteedNoWrapRegion(
1761                 Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1762   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1763                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1764             ConstantRange(APInt(32, 0), APInt(32, 1) + 1));
1765   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1766                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1767             ConstantRange(APInt(32, -1), APInt(32, 0) + 1));
1768 
1769   EXPECT_EQ(
1770       ConstantRange::makeGuaranteedNoWrapRegion(
1771           Instruction::Shl, ConstantRange::getFull(32), OBO::NoUnsignedWrap),
1772       ConstantRange::makeGuaranteedNoWrapRegion(
1773           Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1774   EXPECT_EQ(
1775       ConstantRange::makeGuaranteedNoWrapRegion(
1776           Instruction::Shl, ConstantRange::getFull(32), OBO::NoSignedWrap),
1777       ConstantRange::makeGuaranteedNoWrapRegion(
1778           Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1779 
1780   ConstantRange IllegalShAmt(APInt(32, 32), APInt(32, 0) + 1);
1781   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1782                 Instruction::Shl, IllegalShAmt, OBO::NoUnsignedWrap),
1783             ConstantRange::getFull(32));
1784   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1785                 Instruction::Shl, IllegalShAmt, OBO::NoSignedWrap),
1786             ConstantRange::getFull(32));
1787 
1788   EXPECT_EQ(
1789       ConstantRange::makeGuaranteedNoWrapRegion(
1790           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1791           OBO::NoUnsignedWrap),
1792       ConstantRange::makeGuaranteedNoWrapRegion(
1793           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1794           OBO::NoUnsignedWrap));
1795   EXPECT_EQ(
1796       ConstantRange::makeGuaranteedNoWrapRegion(
1797           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1798           OBO::NoSignedWrap),
1799       ConstantRange::makeGuaranteedNoWrapRegion(
1800           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1801           OBO::NoSignedWrap));
1802 
1803   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1804                 Instruction::Shl,
1805                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1806                 OBO::NoUnsignedWrap),
1807             ConstantRange(APInt(32, 0), APInt(32, 65535) + 1));
1808   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1809                 Instruction::Shl,
1810                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1811                 OBO::NoSignedWrap),
1812             ConstantRange(APInt(32, -32768), APInt(32, 32767) + 1));
1813 }
1814 
1815 template<typename Fn>
1816 void TestNoWrapRegionExhaustive(Instruction::BinaryOps BinOp,
1817                                 unsigned NoWrapKind, Fn OverflowFn) {
1818   unsigned Bits = 5;
1819   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
1820     if (CR.isEmptySet())
1821       return;
1822     if (Instruction::isShift(BinOp) && CR.getUnsignedMax().uge(Bits))
1823       return;
1824 
1825     ConstantRange NoWrap =
1826         ConstantRange::makeGuaranteedNoWrapRegion(BinOp, CR, NoWrapKind);
1827     ConstantRange Full = ConstantRange::getFull(Bits);
1828     ForeachNumInConstantRange(Full, [&](const APInt &N1) {
1829       bool NoOverflow = true;
1830       bool Overflow = true;
1831       ForeachNumInConstantRange(CR, [&](const APInt &N2) {
1832         if (OverflowFn(N1, N2))
1833           NoOverflow = false;
1834         else
1835           Overflow = false;
1836       });
1837       EXPECT_EQ(NoOverflow, NoWrap.contains(N1));
1838 
1839       // The no-wrap range is exact for single-element ranges.
1840       if (CR.isSingleElement()) {
1841         EXPECT_EQ(Overflow, !NoWrap.contains(N1));
1842       }
1843     });
1844   });
1845 }
1846 
1847 // Show that makeGuaranteedNoWrapRegion() is maximal, and for single-element
1848 // ranges also exact.
1849 TEST(ConstantRange, NoWrapRegionExhaustive) {
1850   TestNoWrapRegionExhaustive(
1851       Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap,
1852       [](const APInt &N1, const APInt &N2) {
1853         bool Overflow;
1854         (void) N1.uadd_ov(N2, Overflow);
1855         return Overflow;
1856       });
1857   TestNoWrapRegionExhaustive(
1858       Instruction::Add, OverflowingBinaryOperator::NoSignedWrap,
1859       [](const APInt &N1, const APInt &N2) {
1860         bool Overflow;
1861         (void) N1.sadd_ov(N2, Overflow);
1862         return Overflow;
1863       });
1864   TestNoWrapRegionExhaustive(
1865       Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap,
1866       [](const APInt &N1, const APInt &N2) {
1867         bool Overflow;
1868         (void) N1.usub_ov(N2, Overflow);
1869         return Overflow;
1870       });
1871   TestNoWrapRegionExhaustive(
1872       Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap,
1873       [](const APInt &N1, const APInt &N2) {
1874         bool Overflow;
1875         (void) N1.ssub_ov(N2, Overflow);
1876         return Overflow;
1877       });
1878   TestNoWrapRegionExhaustive(
1879       Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap,
1880       [](const APInt &N1, const APInt &N2) {
1881         bool Overflow;
1882         (void) N1.umul_ov(N2, Overflow);
1883         return Overflow;
1884       });
1885   TestNoWrapRegionExhaustive(
1886       Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap,
1887       [](const APInt &N1, const APInt &N2) {
1888         bool Overflow;
1889         (void) N1.smul_ov(N2, Overflow);
1890         return Overflow;
1891       });
1892   TestNoWrapRegionExhaustive(Instruction::Shl,
1893                              OverflowingBinaryOperator::NoUnsignedWrap,
1894                              [](const APInt &N1, const APInt &N2) {
1895                                bool Overflow;
1896                                (void)N1.ushl_ov(N2, Overflow);
1897                                return Overflow;
1898                              });
1899   TestNoWrapRegionExhaustive(Instruction::Shl,
1900                              OverflowingBinaryOperator::NoSignedWrap,
1901                              [](const APInt &N1, const APInt &N2) {
1902                                bool Overflow;
1903                                (void)N1.sshl_ov(N2, Overflow);
1904                                return Overflow;
1905                              });
1906 }
1907 
1908 TEST(ConstantRange, GetEquivalentICmp) {
1909   APInt RHS;
1910   CmpInst::Predicate Pred;
1911 
1912   EXPECT_TRUE(ConstantRange(APInt::getMinValue(32), APInt(32, 100))
1913                   .getEquivalentICmp(Pred, RHS));
1914   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1915   EXPECT_EQ(RHS, APInt(32, 100));
1916 
1917   EXPECT_TRUE(ConstantRange(APInt::getSignedMinValue(32), APInt(32, 100))
1918                   .getEquivalentICmp(Pred, RHS));
1919   EXPECT_EQ(Pred, CmpInst::ICMP_SLT);
1920   EXPECT_EQ(RHS, APInt(32, 100));
1921 
1922   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getMinValue(32))
1923                   .getEquivalentICmp(Pred, RHS));
1924   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1925   EXPECT_EQ(RHS, APInt(32, 100));
1926 
1927   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getSignedMinValue(32))
1928                   .getEquivalentICmp(Pred, RHS));
1929   EXPECT_EQ(Pred, CmpInst::ICMP_SGE);
1930   EXPECT_EQ(RHS, APInt(32, 100));
1931 
1932   EXPECT_TRUE(
1933       ConstantRange(32, /*isFullSet=*/true).getEquivalentICmp(Pred, RHS));
1934   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1935   EXPECT_EQ(RHS, APInt(32, 0));
1936 
1937   EXPECT_TRUE(
1938       ConstantRange(32, /*isFullSet=*/false).getEquivalentICmp(Pred, RHS));
1939   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1940   EXPECT_EQ(RHS, APInt(32, 0));
1941 
1942   EXPECT_FALSE(ConstantRange(APInt(32, 100), APInt(32, 200))
1943                    .getEquivalentICmp(Pred, RHS));
1944 
1945   EXPECT_FALSE(ConstantRange(APInt::getSignedMinValue(32) - APInt(32, 100),
1946                              APInt::getSignedMinValue(32) + APInt(32, 100))
1947                    .getEquivalentICmp(Pred, RHS));
1948 
1949   EXPECT_FALSE(ConstantRange(APInt::getMinValue(32) - APInt(32, 100),
1950                              APInt::getMinValue(32) + APInt(32, 100))
1951                    .getEquivalentICmp(Pred, RHS));
1952 
1953   EXPECT_TRUE(ConstantRange(APInt(32, 100)).getEquivalentICmp(Pred, RHS));
1954   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1955   EXPECT_EQ(RHS, APInt(32, 100));
1956 
1957   EXPECT_TRUE(
1958       ConstantRange(APInt(32, 100)).inverse().getEquivalentICmp(Pred, RHS));
1959   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1960   EXPECT_EQ(RHS, APInt(32, 100));
1961 
1962   EXPECT_TRUE(
1963       ConstantRange(APInt(512, 100)).inverse().getEquivalentICmp(Pred, RHS));
1964   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1965   EXPECT_EQ(RHS, APInt(512, 100));
1966 
1967   // NB!  It would be correct for the following four calls to getEquivalentICmp
1968   // to return ordered predicates like CmpInst::ICMP_ULT or CmpInst::ICMP_UGT.
1969   // However, that's not the case today.
1970 
1971   EXPECT_TRUE(ConstantRange(APInt(32, 0)).getEquivalentICmp(Pred, RHS));
1972   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1973   EXPECT_EQ(RHS, APInt(32, 0));
1974 
1975   EXPECT_TRUE(
1976       ConstantRange(APInt(32, 0)).inverse().getEquivalentICmp(Pred, RHS));
1977   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1978   EXPECT_EQ(RHS, APInt(32, 0));
1979 
1980   EXPECT_TRUE(ConstantRange(APInt(32, -1)).getEquivalentICmp(Pred, RHS));
1981   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1982   EXPECT_EQ(RHS, APInt(32, -1));
1983 
1984   EXPECT_TRUE(
1985       ConstantRange(APInt(32, -1)).inverse().getEquivalentICmp(Pred, RHS));
1986   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1987   EXPECT_EQ(RHS, APInt(32, -1));
1988 
1989   EnumerateConstantRanges(4, [](const ConstantRange &CR) {
1990     CmpInst::Predicate Pred;
1991     APInt RHS, Offset;
1992     CR.getEquivalentICmp(Pred, RHS, Offset);
1993     ForeachNumInConstantRange(ConstantRange::getFull(4), [&](const APInt &N) {
1994       bool Result = ICmpInst::compare(N + Offset, RHS, Pred);
1995       EXPECT_EQ(CR.contains(N), Result);
1996     });
1997 
1998     if (CR.getEquivalentICmp(Pred, RHS)) {
1999       ForeachNumInConstantRange(ConstantRange::getFull(4), [&](const APInt &N) {
2000         bool Result = ICmpInst::compare(N, RHS, Pred);
2001         EXPECT_EQ(CR.contains(N), Result);
2002       });
2003     }
2004   });
2005 }
2006 
2007 #define EXPECT_MAY_OVERFLOW(op) \
2008   EXPECT_EQ(ConstantRange::OverflowResult::MayOverflow, (op))
2009 #define EXPECT_ALWAYS_OVERFLOWS_LOW(op) \
2010   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsLow, (op))
2011 #define EXPECT_ALWAYS_OVERFLOWS_HIGH(op) \
2012   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsHigh, (op))
2013 #define EXPECT_NEVER_OVERFLOWS(op) \
2014   EXPECT_EQ(ConstantRange::OverflowResult::NeverOverflows, (op))
2015 
2016 TEST_F(ConstantRangeTest, UnsignedAddOverflow) {
2017   // Ill-defined - may overflow is a conservative result.
2018   EXPECT_MAY_OVERFLOW(Some.unsignedAddMayOverflow(Empty));
2019   EXPECT_MAY_OVERFLOW(Empty.unsignedAddMayOverflow(Some));
2020 
2021   // Never overflow despite one full/wrap set.
2022   ConstantRange Zero(APInt::getZero(16));
2023   EXPECT_NEVER_OVERFLOWS(Full.unsignedAddMayOverflow(Zero));
2024   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedAddMayOverflow(Zero));
2025   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Full));
2026   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Wrap));
2027 
2028   // But usually full/wrap always may overflow.
2029   EXPECT_MAY_OVERFLOW(Full.unsignedAddMayOverflow(One));
2030   EXPECT_MAY_OVERFLOW(Wrap.unsignedAddMayOverflow(One));
2031   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Full));
2032   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Wrap));
2033 
2034   ConstantRange A(APInt(16, 0xfd00), APInt(16, 0xfe00));
2035   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2036   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2037   EXPECT_NEVER_OVERFLOWS(A.unsignedAddMayOverflow(B1));
2038   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(B2));
2039   EXPECT_NEVER_OVERFLOWS(B1.unsignedAddMayOverflow(A));
2040   EXPECT_MAY_OVERFLOW(B2.unsignedAddMayOverflow(A));
2041 
2042   ConstantRange C1(APInt(16, 0x0299), APInt(16, 0x0400));
2043   ConstantRange C2(APInt(16, 0x0300), APInt(16, 0x0400));
2044   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(C1));
2045   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.unsignedAddMayOverflow(C2));
2046   EXPECT_MAY_OVERFLOW(C1.unsignedAddMayOverflow(A));
2047   EXPECT_ALWAYS_OVERFLOWS_HIGH(C2.unsignedAddMayOverflow(A));
2048 }
2049 
2050 TEST_F(ConstantRangeTest, UnsignedSubOverflow) {
2051   // Ill-defined - may overflow is a conservative result.
2052   EXPECT_MAY_OVERFLOW(Some.unsignedSubMayOverflow(Empty));
2053   EXPECT_MAY_OVERFLOW(Empty.unsignedSubMayOverflow(Some));
2054 
2055   // Never overflow despite one full/wrap set.
2056   ConstantRange Zero(APInt::getZero(16));
2057   ConstantRange Max(APInt::getAllOnes(16));
2058   EXPECT_NEVER_OVERFLOWS(Full.unsignedSubMayOverflow(Zero));
2059   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedSubMayOverflow(Zero));
2060   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Full));
2061   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Wrap));
2062 
2063   // But usually full/wrap always may overflow.
2064   EXPECT_MAY_OVERFLOW(Full.unsignedSubMayOverflow(One));
2065   EXPECT_MAY_OVERFLOW(Wrap.unsignedSubMayOverflow(One));
2066   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Full));
2067   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Wrap));
2068 
2069   ConstantRange A(APInt(16, 0x0000), APInt(16, 0x0100));
2070   ConstantRange B(APInt(16, 0x0100), APInt(16, 0x0200));
2071   EXPECT_NEVER_OVERFLOWS(B.unsignedSubMayOverflow(A));
2072   EXPECT_ALWAYS_OVERFLOWS_LOW(A.unsignedSubMayOverflow(B));
2073 
2074   ConstantRange A1(APInt(16, 0x0000), APInt(16, 0x0101));
2075   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2076   EXPECT_NEVER_OVERFLOWS(B1.unsignedSubMayOverflow(A1));
2077   EXPECT_MAY_OVERFLOW(A1.unsignedSubMayOverflow(B1));
2078 
2079   ConstantRange A2(APInt(16, 0x0000), APInt(16, 0x0102));
2080   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2081   EXPECT_MAY_OVERFLOW(B2.unsignedSubMayOverflow(A2));
2082   EXPECT_MAY_OVERFLOW(A2.unsignedSubMayOverflow(B2));
2083 }
2084 
2085 TEST_F(ConstantRangeTest, SignedAddOverflow) {
2086   // Ill-defined - may overflow is a conservative result.
2087   EXPECT_MAY_OVERFLOW(Some.signedAddMayOverflow(Empty));
2088   EXPECT_MAY_OVERFLOW(Empty.signedAddMayOverflow(Some));
2089 
2090   // Never overflow despite one full/wrap set.
2091   ConstantRange Zero(APInt::getZero(16));
2092   EXPECT_NEVER_OVERFLOWS(Full.signedAddMayOverflow(Zero));
2093   EXPECT_NEVER_OVERFLOWS(Wrap.signedAddMayOverflow(Zero));
2094   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Full));
2095   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Wrap));
2096 
2097   // But usually full/wrap always may overflow.
2098   EXPECT_MAY_OVERFLOW(Full.signedAddMayOverflow(One));
2099   EXPECT_MAY_OVERFLOW(Wrap.signedAddMayOverflow(One));
2100   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Full));
2101   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Wrap));
2102 
2103   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2104   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2105   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2106   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B1));
2107   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B2));
2108   ConstantRange B3(APInt(16, 0x8000), APInt(16, 0x0201));
2109   ConstantRange B4(APInt(16, 0x8000), APInt(16, 0x0202));
2110   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B3));
2111   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B4));
2112   ConstantRange B5(APInt(16, 0x0299), APInt(16, 0x0400));
2113   ConstantRange B6(APInt(16, 0x0300), APInt(16, 0x0400));
2114   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B5));
2115   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedAddMayOverflow(B6));
2116 
2117   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2118   ConstantRange D1(APInt(16, 0xfe00), APInt(16, 0xff00));
2119   ConstantRange D2(APInt(16, 0xfd99), APInt(16, 0xff00));
2120   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D1));
2121   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D2));
2122   ConstantRange D3(APInt(16, 0xfe00), APInt(16, 0x8000));
2123   ConstantRange D4(APInt(16, 0xfd99), APInt(16, 0x8000));
2124   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D3));
2125   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D4));
2126   ConstantRange D5(APInt(16, 0xfc00), APInt(16, 0xfd02));
2127   ConstantRange D6(APInt(16, 0xfc00), APInt(16, 0xfd01));
2128   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D5));
2129   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedAddMayOverflow(D6));
2130 
2131   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2132   EXPECT_NEVER_OVERFLOWS(E.signedAddMayOverflow(E));
2133   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7000));
2134   EXPECT_MAY_OVERFLOW(F.signedAddMayOverflow(F));
2135 }
2136 
2137 TEST_F(ConstantRangeTest, SignedSubOverflow) {
2138   // Ill-defined - may overflow is a conservative result.
2139   EXPECT_MAY_OVERFLOW(Some.signedSubMayOverflow(Empty));
2140   EXPECT_MAY_OVERFLOW(Empty.signedSubMayOverflow(Some));
2141 
2142   // Never overflow despite one full/wrap set.
2143   ConstantRange Zero(APInt::getZero(16));
2144   EXPECT_NEVER_OVERFLOWS(Full.signedSubMayOverflow(Zero));
2145   EXPECT_NEVER_OVERFLOWS(Wrap.signedSubMayOverflow(Zero));
2146 
2147   // But usually full/wrap always may overflow.
2148   EXPECT_MAY_OVERFLOW(Full.signedSubMayOverflow(One));
2149   EXPECT_MAY_OVERFLOW(Wrap.signedSubMayOverflow(One));
2150   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Full));
2151   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Wrap));
2152 
2153   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2154   ConstantRange B1(APInt(16, 0xfe00), APInt(16, 0xff00));
2155   ConstantRange B2(APInt(16, 0xfd99), APInt(16, 0xff00));
2156   EXPECT_NEVER_OVERFLOWS(A.signedSubMayOverflow(B1));
2157   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B2));
2158   ConstantRange B3(APInt(16, 0xfc00), APInt(16, 0xfd02));
2159   ConstantRange B4(APInt(16, 0xfc00), APInt(16, 0xfd01));
2160   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B3));
2161   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedSubMayOverflow(B4));
2162 
2163   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2164   ConstantRange D1(APInt(16, 0x0100), APInt(16, 0x0201));
2165   ConstantRange D2(APInt(16, 0x0100), APInt(16, 0x0202));
2166   EXPECT_NEVER_OVERFLOWS(C.signedSubMayOverflow(D1));
2167   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D2));
2168   ConstantRange D3(APInt(16, 0x0299), APInt(16, 0x0400));
2169   ConstantRange D4(APInt(16, 0x0300), APInt(16, 0x0400));
2170   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D3));
2171   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedSubMayOverflow(D4));
2172 
2173   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2174   EXPECT_NEVER_OVERFLOWS(E.signedSubMayOverflow(E));
2175   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7001));
2176   EXPECT_MAY_OVERFLOW(F.signedSubMayOverflow(F));
2177 }
2178 
2179 template<typename Fn1, typename Fn2>
2180 static void TestOverflowExhaustive(Fn1 OverflowFn, Fn2 MayOverflowFn) {
2181   // Constant range overflow checks are tested exhaustively on 4-bit numbers.
2182   unsigned Bits = 4;
2183   EnumerateTwoConstantRanges(Bits, [=](const ConstantRange &CR1,
2184                                        const ConstantRange &CR2) {
2185     // Loop over all N1 in CR1 and N2 in CR2 and check whether any of the
2186     // operations have overflow / have no overflow.
2187     bool RangeHasOverflowLow = false;
2188     bool RangeHasOverflowHigh = false;
2189     bool RangeHasNoOverflow = false;
2190     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
2191       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
2192         bool IsOverflowHigh;
2193         if (!OverflowFn(IsOverflowHigh, N1, N2)) {
2194           RangeHasNoOverflow = true;
2195           return;
2196         }
2197 
2198         if (IsOverflowHigh)
2199           RangeHasOverflowHigh = true;
2200         else
2201           RangeHasOverflowLow = true;
2202       });
2203     });
2204 
2205     ConstantRange::OverflowResult OR = MayOverflowFn(CR1, CR2);
2206     switch (OR) {
2207     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
2208       EXPECT_TRUE(RangeHasOverflowLow);
2209       EXPECT_FALSE(RangeHasOverflowHigh);
2210       EXPECT_FALSE(RangeHasNoOverflow);
2211       break;
2212     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
2213       EXPECT_TRUE(RangeHasOverflowHigh);
2214       EXPECT_FALSE(RangeHasOverflowLow);
2215       EXPECT_FALSE(RangeHasNoOverflow);
2216       break;
2217     case ConstantRange::OverflowResult::NeverOverflows:
2218       EXPECT_FALSE(RangeHasOverflowLow);
2219       EXPECT_FALSE(RangeHasOverflowHigh);
2220       EXPECT_TRUE(RangeHasNoOverflow);
2221       break;
2222     case ConstantRange::OverflowResult::MayOverflow:
2223       // We return MayOverflow for empty sets as a conservative result,
2224       // but of course neither the RangeHasOverflow nor the
2225       // RangeHasNoOverflow flags will be set.
2226       if (CR1.isEmptySet() || CR2.isEmptySet())
2227         break;
2228 
2229       EXPECT_TRUE(RangeHasOverflowLow || RangeHasOverflowHigh);
2230       EXPECT_TRUE(RangeHasNoOverflow);
2231       break;
2232     }
2233   });
2234 }
2235 
2236 TEST_F(ConstantRangeTest, UnsignedAddOverflowExhaustive) {
2237   TestOverflowExhaustive(
2238       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2239         bool Overflow;
2240         (void) N1.uadd_ov(N2, Overflow);
2241         IsOverflowHigh = true;
2242         return Overflow;
2243       },
2244       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2245         return CR1.unsignedAddMayOverflow(CR2);
2246       });
2247 }
2248 
2249 TEST_F(ConstantRangeTest, UnsignedSubOverflowExhaustive) {
2250   TestOverflowExhaustive(
2251       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2252         bool Overflow;
2253         (void) N1.usub_ov(N2, Overflow);
2254         IsOverflowHigh = false;
2255         return Overflow;
2256       },
2257       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2258         return CR1.unsignedSubMayOverflow(CR2);
2259       });
2260 }
2261 
2262 TEST_F(ConstantRangeTest, UnsignedMulOverflowExhaustive) {
2263   TestOverflowExhaustive(
2264       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2265         bool Overflow;
2266         (void) N1.umul_ov(N2, Overflow);
2267         IsOverflowHigh = true;
2268         return Overflow;
2269       },
2270       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2271         return CR1.unsignedMulMayOverflow(CR2);
2272       });
2273 }
2274 
2275 TEST_F(ConstantRangeTest, SignedAddOverflowExhaustive) {
2276   TestOverflowExhaustive(
2277       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2278         bool Overflow;
2279         (void) N1.sadd_ov(N2, Overflow);
2280         IsOverflowHigh = N1.isNonNegative();
2281         return Overflow;
2282       },
2283       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2284         return CR1.signedAddMayOverflow(CR2);
2285       });
2286 }
2287 
2288 TEST_F(ConstantRangeTest, SignedSubOverflowExhaustive) {
2289   TestOverflowExhaustive(
2290       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2291         bool Overflow;
2292         (void) N1.ssub_ov(N2, Overflow);
2293         IsOverflowHigh = N1.isNonNegative();
2294         return Overflow;
2295       },
2296       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2297         return CR1.signedSubMayOverflow(CR2);
2298       });
2299 }
2300 
2301 TEST_F(ConstantRangeTest, FromKnownBits) {
2302   KnownBits Unknown(16);
2303   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/false));
2304   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/true));
2305 
2306   // .10..01. -> unsigned 01000010 (66)  to 11011011 (219)
2307   //          -> signed   11000010 (194) to 01011011 (91)
2308   KnownBits Known(8);
2309   Known.Zero = 36;
2310   Known.One = 66;
2311   ConstantRange Unsigned(APInt(8, 66), APInt(8, 219 + 1));
2312   ConstantRange Signed(APInt(8, 194), APInt(8, 91 + 1));
2313   EXPECT_EQ(Unsigned, ConstantRange::fromKnownBits(Known, /*signed*/false));
2314   EXPECT_EQ(Signed, ConstantRange::fromKnownBits(Known, /*signed*/true));
2315 
2316   // 1.10.10. -> 10100100 (164) to 11101101 (237)
2317   Known.Zero = 18;
2318   Known.One = 164;
2319   ConstantRange CR1(APInt(8, 164), APInt(8, 237 + 1));
2320   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/false));
2321   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/true));
2322 
2323   // 01.0.1.0 -> 01000100 (68) to 01101110 (110)
2324   Known.Zero = 145;
2325   Known.One = 68;
2326   ConstantRange CR2(APInt(8, 68), APInt(8, 110 + 1));
2327   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/false));
2328   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/true));
2329 }
2330 
2331 TEST_F(ConstantRangeTest, FromKnownBitsExhaustive) {
2332   unsigned Bits = 4;
2333   unsigned Max = 1 << Bits;
2334   KnownBits Known(Bits);
2335   for (unsigned Zero = 0; Zero < Max; ++Zero) {
2336     for (unsigned One = 0; One < Max; ++One) {
2337       Known.Zero = Zero;
2338       Known.One = One;
2339       if (Known.hasConflict() || Known.isUnknown())
2340         continue;
2341 
2342       UnsignedOpRangeGatherer UR(Bits);
2343       SignedOpRangeGatherer SR(Bits);
2344       for (unsigned N = 0; N < Max; ++N) {
2345         APInt Num(Bits, N);
2346         if ((Num & Known.Zero) != 0 || (~Num & Known.One) != 0)
2347           continue;
2348 
2349         UR.account(Num);
2350         SR.account(Num);
2351       }
2352 
2353       ConstantRange UnsignedCR = UR.getRange();
2354       ConstantRange SignedCR = SR.getRange();
2355       EXPECT_EQ(UnsignedCR, ConstantRange::fromKnownBits(Known, false));
2356       EXPECT_EQ(SignedCR, ConstantRange::fromKnownBits(Known, true));
2357     }
2358   }
2359 }
2360 
2361 TEST_F(ConstantRangeTest, Negative) {
2362   // All elements in an empty set (of which there are none) are both negative
2363   // and non-negative. Empty & full sets checked explicitly for clarity, but
2364   // they are also covered by the exhaustive test below.
2365   EXPECT_TRUE(Empty.isAllNegative());
2366   EXPECT_TRUE(Empty.isAllNonNegative());
2367   EXPECT_FALSE(Full.isAllNegative());
2368   EXPECT_FALSE(Full.isAllNonNegative());
2369 
2370   unsigned Bits = 4;
2371   EnumerateConstantRanges(Bits, [](const ConstantRange &CR) {
2372     bool AllNegative = true;
2373     bool AllNonNegative = true;
2374     ForeachNumInConstantRange(CR, [&](const APInt &N) {
2375       if (!N.isNegative())
2376         AllNegative = false;
2377       if (!N.isNonNegative())
2378         AllNonNegative = false;
2379     });
2380     assert((CR.isEmptySet() || !AllNegative || !AllNonNegative) &&
2381            "Only empty set can be both all negative and all non-negative");
2382 
2383     EXPECT_EQ(AllNegative, CR.isAllNegative());
2384     EXPECT_EQ(AllNonNegative, CR.isAllNonNegative());
2385   });
2386 }
2387 
2388 TEST_F(ConstantRangeTest, UAddSat) {
2389   TestBinaryOpExhaustive(
2390       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2391         return CR1.uadd_sat(CR2);
2392       },
2393       [](const APInt &N1, const APInt &N2) {
2394         return N1.uadd_sat(N2);
2395       },
2396       PreferSmallestUnsigned);
2397 }
2398 
2399 TEST_F(ConstantRangeTest, USubSat) {
2400   TestBinaryOpExhaustive(
2401       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2402         return CR1.usub_sat(CR2);
2403       },
2404       [](const APInt &N1, const APInt &N2) {
2405         return N1.usub_sat(N2);
2406       },
2407       PreferSmallestUnsigned);
2408 }
2409 
2410 TEST_F(ConstantRangeTest, UMulSat) {
2411   TestBinaryOpExhaustive(
2412       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2413         return CR1.umul_sat(CR2);
2414       },
2415       [](const APInt &N1, const APInt &N2) { return N1.umul_sat(N2); },
2416       PreferSmallestUnsigned);
2417 }
2418 
2419 TEST_F(ConstantRangeTest, UShlSat) {
2420   TestBinaryOpExhaustive(
2421       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2422         return CR1.ushl_sat(CR2);
2423       },
2424       [](const APInt &N1, const APInt &N2) { return N1.ushl_sat(N2); },
2425       PreferSmallestUnsigned);
2426 }
2427 
2428 TEST_F(ConstantRangeTest, SAddSat) {
2429   TestBinaryOpExhaustive(
2430       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2431         return CR1.sadd_sat(CR2);
2432       },
2433       [](const APInt &N1, const APInt &N2) {
2434         return N1.sadd_sat(N2);
2435       },
2436       PreferSmallestSigned);
2437 }
2438 
2439 TEST_F(ConstantRangeTest, SSubSat) {
2440   TestBinaryOpExhaustive(
2441       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2442         return CR1.ssub_sat(CR2);
2443       },
2444       [](const APInt &N1, const APInt &N2) {
2445         return N1.ssub_sat(N2);
2446       },
2447       PreferSmallestSigned);
2448 }
2449 
2450 TEST_F(ConstantRangeTest, SMulSat) {
2451   TestBinaryOpExhaustive(
2452       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2453         return CR1.smul_sat(CR2);
2454       },
2455       [](const APInt &N1, const APInt &N2) { return N1.smul_sat(N2); },
2456       PreferSmallestSigned);
2457 }
2458 
2459 TEST_F(ConstantRangeTest, SShlSat) {
2460   TestBinaryOpExhaustive(
2461       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2462         return CR1.sshl_sat(CR2);
2463       },
2464       [](const APInt &N1, const APInt &N2) { return N1.sshl_sat(N2); },
2465       PreferSmallestSigned);
2466 }
2467 
2468 TEST_F(ConstantRangeTest, Abs) {
2469   TestUnaryOpExhaustive(
2470       [](const ConstantRange &CR) { return CR.abs(); },
2471       [](const APInt &N) { return N.abs(); });
2472 
2473   TestUnaryOpExhaustive(
2474       [](const ConstantRange &CR) { return CR.abs(/*IntMinIsPoison=*/true); },
2475       [](const APInt &N) -> Optional<APInt> {
2476         if (N.isMinSignedValue())
2477           return None;
2478         return N.abs();
2479       });
2480 }
2481 
2482 TEST_F(ConstantRangeTest, castOps) {
2483   ConstantRange A(APInt(16, 66), APInt(16, 128));
2484   ConstantRange FpToI8 = A.castOp(Instruction::FPToSI, 8);
2485   EXPECT_EQ(8u, FpToI8.getBitWidth());
2486   EXPECT_TRUE(FpToI8.isFullSet());
2487 
2488   ConstantRange FpToI16 = A.castOp(Instruction::FPToSI, 16);
2489   EXPECT_EQ(16u, FpToI16.getBitWidth());
2490   EXPECT_EQ(A, FpToI16);
2491 
2492   ConstantRange FPExtToDouble = A.castOp(Instruction::FPExt, 64);
2493   EXPECT_EQ(64u, FPExtToDouble.getBitWidth());
2494   EXPECT_TRUE(FPExtToDouble.isFullSet());
2495 
2496   ConstantRange PtrToInt = A.castOp(Instruction::PtrToInt, 64);
2497   EXPECT_EQ(64u, PtrToInt.getBitWidth());
2498   EXPECT_TRUE(PtrToInt.isFullSet());
2499 
2500   ConstantRange IntToPtr = A.castOp(Instruction::IntToPtr, 64);
2501   EXPECT_EQ(64u, IntToPtr.getBitWidth());
2502   EXPECT_TRUE(IntToPtr.isFullSet());
2503 }
2504 
2505 TEST_F(ConstantRangeTest, binaryXor) {
2506   // Single element ranges.
2507   ConstantRange R16(APInt(8, 16));
2508   ConstantRange R20(APInt(8, 20));
2509   EXPECT_EQ(*R16.binaryXor(R16).getSingleElement(), APInt(8, 0));
2510   EXPECT_EQ(*R16.binaryXor(R20).getSingleElement(), APInt(8, 16 ^ 20));
2511 
2512   // Ranges with more than a single element. Handled conservatively for now.
2513   ConstantRange R16_35(APInt(8, 16), APInt(8, 35));
2514   ConstantRange R0_99(APInt(8, 0), APInt(8, 99));
2515   EXPECT_TRUE(R16_35.binaryXor(R16_35).isFullSet());
2516   EXPECT_TRUE(R16_35.binaryXor(R0_99).isFullSet());
2517   EXPECT_TRUE(R0_99.binaryXor(R16_35).isFullSet());
2518 }
2519 
2520 TEST_F(ConstantRangeTest, binaryNot) {
2521   TestUnaryOpExhaustive(
2522       [](const ConstantRange &CR) { return CR.binaryNot(); },
2523       [](const APInt &N) { return ~N; },
2524       PreferSmallest);
2525   TestUnaryOpExhaustive(
2526       [](const ConstantRange &CR) {
2527         return CR.binaryXor(ConstantRange(APInt::getAllOnes(CR.getBitWidth())));
2528       },
2529       [](const APInt &N) { return ~N; }, PreferSmallest);
2530   TestUnaryOpExhaustive(
2531       [](const ConstantRange &CR) {
2532         return ConstantRange(APInt::getAllOnes(CR.getBitWidth())).binaryXor(CR);
2533       },
2534       [](const APInt &N) { return ~N; }, PreferSmallest);
2535 }
2536 
2537 template <typename T>
2538 void testConstantRangeICmpPredEquivalence(ICmpInst::Predicate SrcPred, T Func) {
2539   unsigned Bits = 4;
2540   EnumerateTwoConstantRanges(
2541       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
2542         ICmpInst::Predicate TgtPred;
2543         bool ExpectedEquivalent;
2544         std::tie(TgtPred, ExpectedEquivalent) = Func(CR1, CR2);
2545         if (TgtPred == CmpInst::Predicate::BAD_ICMP_PREDICATE)
2546           return;
2547         bool TrulyEquivalent = true;
2548         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
2549           if (!TrulyEquivalent)
2550             return;
2551           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
2552             if (!TrulyEquivalent)
2553               return;
2554             TrulyEquivalent &= ICmpInst::compare(N1, N2, SrcPred) ==
2555                                ICmpInst::compare(N1, N2, TgtPred);
2556           });
2557         });
2558         ASSERT_EQ(TrulyEquivalent, ExpectedEquivalent);
2559       });
2560 }
2561 
2562 TEST_F(ConstantRangeTest, areInsensitiveToSignednessOfICmpPredicate) {
2563   for (auto Pred : ICmpInst::predicates()) {
2564     if (ICmpInst::isEquality(Pred))
2565       continue;
2566     ICmpInst::Predicate FlippedSignednessPred =
2567         ICmpInst::getFlippedSignednessPredicate(Pred);
2568     testConstantRangeICmpPredEquivalence(Pred, [FlippedSignednessPred](
2569                                                    const ConstantRange &CR1,
2570                                                    const ConstantRange &CR2) {
2571       return std::make_pair(
2572           FlippedSignednessPred,
2573           ConstantRange::areInsensitiveToSignednessOfICmpPredicate(CR1, CR2));
2574     });
2575   }
2576 }
2577 
2578 TEST_F(ConstantRangeTest, areInsensitiveToSignednessOfInvertedICmpPredicate) {
2579   for (auto Pred : ICmpInst::predicates()) {
2580     if (ICmpInst::isEquality(Pred))
2581       continue;
2582     ICmpInst::Predicate InvertedFlippedSignednessPred =
2583         ICmpInst::getInversePredicate(
2584             ICmpInst::getFlippedSignednessPredicate(Pred));
2585     testConstantRangeICmpPredEquivalence(
2586         Pred, [InvertedFlippedSignednessPred](const ConstantRange &CR1,
2587                                               const ConstantRange &CR2) {
2588           return std::make_pair(
2589               InvertedFlippedSignednessPred,
2590               ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(
2591                   CR1, CR2));
2592         });
2593   }
2594 }
2595 
2596 TEST_F(ConstantRangeTest, getEquivalentPredWithFlippedSignedness) {
2597   for (auto Pred : ICmpInst::predicates()) {
2598     if (ICmpInst::isEquality(Pred))
2599       continue;
2600     testConstantRangeICmpPredEquivalence(
2601         Pred, [Pred](const ConstantRange &CR1, const ConstantRange &CR2) {
2602           return std::make_pair(
2603               ConstantRange::getEquivalentPredWithFlippedSignedness(Pred, CR1,
2604                                                                     CR2),
2605               /*ExpectedEquivalent=*/true);
2606         });
2607   }
2608 }
2609 
2610 TEST_F(ConstantRangeTest, isSizeLargerThan) {
2611   EXPECT_FALSE(Empty.isSizeLargerThan(0));
2612 
2613   EXPECT_TRUE(Full.isSizeLargerThan(0));
2614   EXPECT_TRUE(Full.isSizeLargerThan(65535));
2615   EXPECT_FALSE(Full.isSizeLargerThan(65536));
2616 
2617   EXPECT_TRUE(One.isSizeLargerThan(0));
2618   EXPECT_FALSE(One.isSizeLargerThan(1));
2619 }
2620 
2621 } // anonymous namespace
2622