Clarify and simplify.
[oota-llvm.git] / lib / Support / ConstantRange.cpp
1 //===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Represent a range of possible values that may occur when the program is run
11 // for an integral value.  This keeps track of a lower and upper bound for the
12 // constant, which MAY wrap around the end of the numeric range.  To do this, it
13 // keeps track of a [lower, upper) bound, which specifies an interval just like
14 // STL iterators.  When used with boolean values, the following are important
15 // ranges (other integral ranges use min/max values for special range values):
16 //
17 //  [F, F) = {}     = Empty set
18 //  [T, F) = {T}
19 //  [F, T) = {F}
20 //  [T, T) = {F, T} = Full set
21 //
22 //===----------------------------------------------------------------------===//
23
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Instructions.h"
27 using namespace llvm;
28
29 /// Initialize a full (the default) or empty set for the specified type.
30 ///
31 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) {
32   if (Full)
33     Lower = Upper = APInt::getMaxValue(BitWidth);
34   else
35     Lower = Upper = APInt::getMinValue(BitWidth);
36 }
37
38 /// Initialize a range to hold the single specified value.
39 ///
40 ConstantRange::ConstantRange(const APInt & V) : Lower(V), Upper(V + 1) {}
41
42 ConstantRange::ConstantRange(const APInt &L, const APInt &U) :
43   Lower(L), Upper(U) {
44   assert(L.getBitWidth() == U.getBitWidth() &&
45          "ConstantRange with unequal bit widths");
46   assert((L != U || (L.isMaxValue() || L.isMinValue())) &&
47          "Lower == Upper, but they aren't min or max value!");
48 }
49
50 ConstantRange ConstantRange::makeICmpRegion(unsigned Pred,
51                                             const ConstantRange &CR) {
52   uint32_t W = CR.getBitWidth();
53   switch (Pred) {
54     default: assert(!"Invalid ICmp predicate to makeICmpRegion()");
55     case ICmpInst::ICMP_EQ:
56       return CR;
57     case ICmpInst::ICMP_NE:
58       if (CR.isSingleElement())
59         return ConstantRange(CR.getUpper(), CR.getLower());
60       return ConstantRange(W);
61     case ICmpInst::ICMP_ULT:
62       return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
63     case ICmpInst::ICMP_SLT:
64       return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
65     case ICmpInst::ICMP_ULE: {
66       APInt UMax(CR.getUnsignedMax());
67       if (UMax.isMaxValue())
68         return ConstantRange(W);
69       return ConstantRange(APInt::getMinValue(W), UMax + 1);
70     }
71     case ICmpInst::ICMP_SLE: {
72       APInt SMax(CR.getSignedMax());
73       if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
74         return ConstantRange(W);
75       return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
76     }
77     case ICmpInst::ICMP_UGT:
78       return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
79     case ICmpInst::ICMP_SGT:
80       return ConstantRange(CR.getSignedMin() + 1,
81                            APInt::getSignedMinValue(W));
82     case ICmpInst::ICMP_UGE: {
83       APInt UMin(CR.getUnsignedMin());
84       if (UMin.isMinValue())
85         return ConstantRange(W);
86       return ConstantRange(UMin, APInt::getNullValue(W));
87     }
88     case ICmpInst::ICMP_SGE: {
89       APInt SMin(CR.getSignedMin());
90       if (SMin.isMinSignedValue())
91         return ConstantRange(W);
92       return ConstantRange(SMin, APInt::getSignedMinValue(W));
93     }
94   }
95 }
96
97 /// isFullSet - Return true if this set contains all of the elements possible
98 /// for this data-type
99 bool ConstantRange::isFullSet() const {
100   return Lower == Upper && Lower.isMaxValue();
101 }
102
103 /// isEmptySet - Return true if this set contains no members.
104 ///
105 bool ConstantRange::isEmptySet() const {
106   return Lower == Upper && Lower.isMinValue();
107 }
108
109 /// isWrappedSet - Return true if this set wraps around the top of the range,
110 /// for example: [100, 8)
111 ///
112 bool ConstantRange::isWrappedSet() const {
113   return Lower.ugt(Upper);
114 }
115
116 /// getSetSize - Return the number of elements in this set.
117 ///
118 APInt ConstantRange::getSetSize() const {
119   if (isEmptySet()) 
120     return APInt(getBitWidth(), 0);
121   if (getBitWidth() == 1) {
122     if (Lower != Upper)  // One of T or F in the set...
123       return APInt(2, 1);
124     return APInt(2, 2);      // Must be full set...
125   }
126
127   // Simply subtract the bounds...
128   return Upper - Lower;
129 }
130
131 /// getUnsignedMax - Return the largest unsigned value contained in the
132 /// ConstantRange.
133 ///
134 APInt ConstantRange::getUnsignedMax() const {
135   if (isFullSet() || isWrappedSet())
136     return APInt::getMaxValue(getBitWidth());
137   else
138     return getUpper() - 1;
139 }
140
141 /// getUnsignedMin - Return the smallest unsigned value contained in the
142 /// ConstantRange.
143 ///
144 APInt ConstantRange::getUnsignedMin() const {
145   if (isFullSet() || (isWrappedSet() && getUpper() != 0))
146     return APInt::getMinValue(getBitWidth());
147   else
148     return getLower();
149 }
150
151 /// getSignedMax - Return the largest signed value contained in the
152 /// ConstantRange.
153 ///
154 APInt ConstantRange::getSignedMax() const {
155   APInt SignedMax(APInt::getSignedMaxValue(getBitWidth()));
156   if (!isWrappedSet()) {
157     if (getLower().sle(getUpper() - 1))
158       return getUpper() - 1;
159     else
160       return SignedMax;
161   } else {
162     if ((getUpper() - 1).slt(getLower())) {
163       if (getLower() != SignedMax)
164         return SignedMax;
165       else
166         return getUpper() - 1;
167     } else {
168       return getUpper() - 1;
169     }
170   }
171 }
172
173 /// getSignedMin - Return the smallest signed value contained in the
174 /// ConstantRange.
175 ///
176 APInt ConstantRange::getSignedMin() const {
177   APInt SignedMin(APInt::getSignedMinValue(getBitWidth()));
178   if (!isWrappedSet()) {
179     if (getLower().sle(getUpper() - 1))
180       return getLower();
181     else
182       return SignedMin;
183   } else {
184     if ((getUpper() - 1).slt(getLower())) {
185       if (getUpper() != SignedMin)
186         return SignedMin;
187       else
188         return getLower();
189     } else {
190       return getLower();
191     }
192   }
193 }
194
195 /// contains - Return true if the specified value is in the set.
196 ///
197 bool ConstantRange::contains(const APInt &V) const {
198   if (Lower == Upper)
199     return isFullSet();
200
201   if (!isWrappedSet())
202     return Lower.ule(V) && V.ult(Upper);
203   else
204     return Lower.ule(V) || V.ult(Upper);
205 }
206
207 /// contains - Return true if the argument is a subset of this range.
208 /// Two equal set contain each other. The empty set is considered to be
209 /// contained by all other sets.
210 ///
211 bool ConstantRange::contains(const ConstantRange &Other) const {
212   if (isFullSet()) return true;
213   if (Other.isFullSet()) return false;
214   if (Other.isEmptySet()) return true;
215   if (isEmptySet()) return false;
216
217   if (!isWrappedSet()) {
218     if (Other.isWrappedSet())
219       return false;
220
221     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
222   }
223
224   if (!Other.isWrappedSet())
225     return Other.getUpper().ule(Upper) ||
226            Lower.ule(Other.getLower());
227
228   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
229 }
230
231 /// subtract - Subtract the specified constant from the endpoints of this
232 /// constant range.
233 ConstantRange ConstantRange::subtract(const APInt &Val) const {
234   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
235   // If the set is empty or full, don't modify the endpoints.
236   if (Lower == Upper) 
237     return *this;
238   return ConstantRange(Lower - Val, Upper - Val);
239 }
240
241
242 // intersect1Wrapped - This helper function is used to intersect two ranges when
243 // it is known that LHS is wrapped and RHS isn't.
244 //
245 ConstantRange 
246 ConstantRange::intersect1Wrapped(const ConstantRange &LHS,
247                                  const ConstantRange &RHS) {
248   assert(LHS.isWrappedSet() && !RHS.isWrappedSet());
249
250   // Check to see if we overlap on the Left side of RHS...
251   //
252   if (RHS.Lower.ult(LHS.Upper)) {
253     // We do overlap on the left side of RHS, see if we overlap on the right of
254     // RHS...
255     if (RHS.Upper.ugt(LHS.Lower)) {
256       // Ok, the result overlaps on both the left and right sides.  See if the
257       // resultant interval will be smaller if we wrap or not...
258       //
259       if (LHS.getSetSize().ult(RHS.getSetSize()))
260         return LHS;
261       else
262         return RHS;
263
264     } else {
265       // No overlap on the right, just on the left.
266       return ConstantRange(RHS.Lower, LHS.Upper);
267     }
268   } else {
269     // We don't overlap on the left side of RHS, see if we overlap on the right
270     // of RHS...
271     if (RHS.Upper.ugt(LHS.Lower)) {
272       // Simple overlap...
273       return ConstantRange(LHS.Lower, RHS.Upper);
274     } else {
275       // No overlap...
276       return ConstantRange(LHS.getBitWidth(), false);
277     }
278   }
279 }
280
281 /// intersectWith - Return the range that results from the intersection of this
282 /// range with another range.
283 ///
284 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
285   assert(getBitWidth() == CR.getBitWidth() && 
286          "ConstantRange types don't agree!");
287   // Handle common special cases
288   if (isEmptySet() || CR.isFullSet())  
289     return *this;
290   if (isFullSet()  || CR.isEmptySet()) 
291     return CR;
292
293   if (!isWrappedSet()) {
294     if (!CR.isWrappedSet()) {
295       APInt L = APIntOps::umax(Lower, CR.Lower);
296       APInt U = APIntOps::umin(Upper, CR.Upper);
297
298       if (L.ult(U)) // If range isn't empty...
299         return ConstantRange(L, U);
300       else
301         return ConstantRange(getBitWidth(), false);// Otherwise, empty set
302     } else
303       return intersect1Wrapped(CR, *this);
304   } else {   // We know "this" is wrapped...
305     if (!CR.isWrappedSet())
306       return intersect1Wrapped(*this, CR);
307     else {
308       // Both ranges are wrapped...
309       APInt L = APIntOps::umax(Lower, CR.Lower);
310       APInt U = APIntOps::umin(Upper, CR.Upper);
311       return ConstantRange(L, U);
312     }
313   }
314   return *this;
315 }
316
317 /// maximalIntersectWith - Return the range that results from the intersection
318 /// of this range with another range.  The resultant range is guaranteed to
319 /// include all elements contained in both input ranges, and to have the
320 /// smallest possible set size that does so.  Because there may be two
321 /// intersections with the same set size, A.maximalIntersectWith(B) might not
322 /// be equal to B.maximalIntersect(A).
323 ConstantRange
324 ConstantRange::maximalIntersectWith(const ConstantRange &CR) const {
325   assert(getBitWidth() == CR.getBitWidth() && 
326          "ConstantRange types don't agree!");
327
328   // Handle common cases.
329   if (   isEmptySet() || CR.isFullSet()) return *this;
330   if (CR.isEmptySet() ||    isFullSet()) return CR;
331
332   if (!isWrappedSet() && CR.isWrappedSet())
333     return CR.maximalIntersectWith(*this);
334
335   if (!isWrappedSet() && !CR.isWrappedSet()) {
336     if (Lower.ult(CR.Lower)) {
337       if (Upper.ule(CR.Lower))
338         return ConstantRange(getBitWidth(), false);
339
340       if (Upper.ult(CR.Upper))
341         return ConstantRange(CR.Lower, Upper);
342
343       return CR;
344     } else {
345       if (Upper.ult(CR.Upper))
346         return *this;
347
348       if (Lower.ult(CR.Upper))
349         return ConstantRange(Lower, CR.Upper);
350
351       return ConstantRange(getBitWidth(), false);
352     }
353   }
354
355   if (isWrappedSet() && !CR.isWrappedSet()) {
356     if (CR.Lower.ult(Upper)) {
357       if (CR.Upper.ult(Upper))
358         return CR;
359
360       if (CR.Upper.ult(Lower))
361         return ConstantRange(CR.Lower, Upper);
362
363       if (getSetSize().ult(CR.getSetSize()))
364         return *this;
365       else
366         return CR;
367     } else if (CR.Lower.ult(Lower)) {
368       if (CR.Upper.ule(Lower))
369         return ConstantRange(getBitWidth(), false);
370
371       return ConstantRange(Lower, CR.Upper);
372     }
373     return CR;
374   }
375
376   if (CR.Upper.ult(Upper)) {
377     if (CR.Lower.ult(Upper)) {
378       if (getSetSize().ult(CR.getSetSize()))
379         return *this;
380       else
381         return CR;
382     }
383
384     if (CR.Lower.ult(Lower))
385       return ConstantRange(Lower, CR.Upper);
386
387     return CR;
388   } else if (CR.Upper.ult(Lower)) {
389     if (CR.Lower.ult(Lower))
390       return *this;
391
392     return ConstantRange(CR.Lower, Upper);
393   }
394   if (getSetSize().ult(CR.getSetSize()))
395     return *this;
396   else
397     return CR;
398 }
399
400
401 /// unionWith - Return the range that results from the union of this range with
402 /// another range.  The resultant range is guaranteed to include the elements of
403 /// both sets, but may contain more.  For example, [3, 9) union [12,15) is
404 /// [3, 15), which includes 9, 10, and 11, which were not included in either
405 /// set before.
406 ///
407 ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
408   assert(getBitWidth() == CR.getBitWidth() && 
409          "ConstantRange types don't agree!");
410
411   if (   isFullSet() || CR.isEmptySet()) return *this;
412   if (CR.isFullSet() ||    isEmptySet()) return CR;
413
414   if (!isWrappedSet() && CR.isWrappedSet()) return CR.unionWith(*this);
415
416   APInt L = Lower, U = Upper;
417
418   if (!isWrappedSet() && !CR.isWrappedSet()) {
419     if (CR.Lower.ult(L))
420       L = CR.Lower;
421
422     if (CR.Upper.ugt(U))
423       U = CR.Upper;
424   }
425
426   if (isWrappedSet() && !CR.isWrappedSet()) {
427     if ((CR.Lower.ult(Upper) && CR.Upper.ult(Upper)) ||
428         (CR.Lower.ugt(Lower) && CR.Upper.ugt(Lower))) {
429       return *this;
430     }
431
432     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper)) {
433       return ConstantRange(getBitWidth());
434     }
435
436     if (CR.Lower.ule(Upper) && CR.Upper.ule(Lower)) {
437       APInt d1 = CR.Upper - Upper, d2 = Lower - CR.Upper;
438       if (d1.ult(d2)) {
439         U = CR.Upper;
440       } else {
441         L = CR.Upper;
442       }
443     }
444
445     if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower)) {
446       APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
447       if (d1.ult(d2)) {
448         U = CR.Lower + 1;
449       } else {
450         L = CR.Upper - 1;
451       }
452     }
453
454     if (Upper.ult(CR.Lower) && Lower.ult(CR.Upper)) {
455       APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Lower;
456
457       if (d1.ult(d2)) {
458         U = CR.Lower + 1;
459       } else {
460         L = CR.Lower;
461       }
462     }
463   }
464
465   if (isWrappedSet() && CR.isWrappedSet()) {
466     if (Lower.ult(CR.Upper) || CR.Lower.ult(Upper))
467       return ConstantRange(getBitWidth());
468
469     if (CR.Upper.ugt(U)) {
470       U = CR.Upper;
471     }
472
473     if (CR.Lower.ult(L)) {
474       L = CR.Lower;
475     }
476
477     if (L == U) return ConstantRange(getBitWidth());
478   }
479
480   return ConstantRange(L, U);
481 }
482
483 /// zeroExtend - Return a new range in the specified integer type, which must
484 /// be strictly larger than the current type.  The returned range will
485 /// correspond to the possible range of values as if the source range had been
486 /// zero extended.
487 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
488   unsigned SrcTySize = getBitWidth();
489   assert(SrcTySize < DstTySize && "Not a value extension");
490   if (isFullSet())
491     // Change a source full set into [0, 1 << 8*numbytes)
492     return ConstantRange(APInt(DstTySize,0), APInt(DstTySize,1).shl(SrcTySize));
493
494   APInt L = Lower; L.zext(DstTySize);
495   APInt U = Upper; U.zext(DstTySize);
496   return ConstantRange(L, U);
497 }
498
499 /// signExtend - Return a new range in the specified integer type, which must
500 /// be strictly larger than the current type.  The returned range will
501 /// correspond to the possible range of values as if the source range had been
502 /// sign extended.
503 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
504   unsigned SrcTySize = getBitWidth();
505   assert(SrcTySize < DstTySize && "Not a value extension");
506   if (isFullSet()) {
507     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
508                          APInt::getLowBitsSet(DstTySize, SrcTySize-1));
509   }
510
511   APInt L = Lower; L.sext(DstTySize);
512   APInt U = Upper; U.sext(DstTySize);
513   return ConstantRange(L, U);
514 }
515
516 /// truncate - Return a new range in the specified integer type, which must be
517 /// strictly smaller than the current type.  The returned range will
518 /// correspond to the possible range of values as if the source range had been
519 /// truncated to the specified type.
520 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
521   unsigned SrcTySize = getBitWidth();
522   assert(SrcTySize > DstTySize && "Not a value truncation");
523   APInt Size(APInt::getLowBitsSet(SrcTySize, DstTySize));
524   if (isFullSet() || getSetSize().ugt(Size))
525     return ConstantRange(DstTySize);
526
527   APInt L = Lower; L.trunc(DstTySize);
528   APInt U = Upper; U.trunc(DstTySize);
529   return ConstantRange(L, U);
530 }
531
532 ConstantRange
533 ConstantRange::add(const ConstantRange &Other) const {
534   if (isEmptySet() || Other.isEmptySet())
535     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
536
537   APInt Spread_X = getSetSize(), Spread_Y = Other.getSetSize();
538   APInt NewLower = getLower() + Other.getLower();
539   APInt NewUpper = getUpper() + Other.getUpper() - 1;
540   if (NewLower == NewUpper)
541     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
542
543   ConstantRange X = ConstantRange(NewLower, NewUpper);
544   if (X.getSetSize().ult(Spread_X) || X.getSetSize().ult(Spread_Y))
545     // We've wrapped, therefore, full set.
546     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
547
548   return X;
549 }
550
551 ConstantRange
552 ConstantRange::multiply(const ConstantRange &Other) const {
553   // TODO: Implement multiply.
554   return ConstantRange(getBitWidth(),
555                        !(isEmptySet() || Other.isEmptySet()));
556 }
557
558 ConstantRange
559 ConstantRange::smax(const ConstantRange &Other) const {
560   // X smax Y is: range(smax(X_smin, Y_smin),
561   //                    smax(X_smax, Y_smax))
562   if (isEmptySet() || Other.isEmptySet())
563     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
564   if (isFullSet() || Other.isFullSet())
565     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
566   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
567   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
568   if (NewU == NewL)
569     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
570   return ConstantRange(NewL, NewU);
571 }
572
573 ConstantRange
574 ConstantRange::umax(const ConstantRange &Other) const {
575   // X umax Y is: range(umax(X_umin, Y_umin),
576   //                    umax(X_umax, Y_umax))
577   if (isEmptySet() || Other.isEmptySet())
578     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
579   if (isFullSet() || Other.isFullSet())
580     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
581   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
582   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
583   if (NewU == NewL)
584     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
585   return ConstantRange(NewL, NewU);
586 }
587
588 ConstantRange
589 ConstantRange::udiv(const ConstantRange &Other) const {
590   // TODO: Implement udiv.
591   return ConstantRange(getBitWidth(),
592                        !(isEmptySet() || Other.isEmptySet()));
593 }
594
595 /// print - Print out the bounds to a stream...
596 ///
597 void ConstantRange::print(raw_ostream &OS) const {
598   OS << "[" << Lower << "," << Upper << ")";
599 }
600
601 /// dump - Allow printing from a debugger easily...
602 ///
603 void ConstantRange::dump() const {
604   print(errs());
605 }
606
607 std::ostream &llvm::operator<<(std::ostream &o,
608                                const ConstantRange &CR) {
609   raw_os_ostream OS(o);
610   OS << CR;
611   return o;
612 }