Update code to eliminate calls to isInteger, calling isIntegral instead.
[oota-llvm.git] / lib / Support / ConstantRange.cpp
1 //===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Constants.h"
26 #include "llvm/Instruction.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Type.h"
29 #include "llvm/Support/Streams.h"
30 #include <ostream>
31 using namespace llvm;
32
33 static ConstantInt *getMaxValue(const Type *Ty, bool isSigned = false) {
34   if (Ty->isIntegral()) {
35     if (isSigned) {
36       // Calculate 011111111111111...
37       unsigned TypeBits = Ty->getPrimitiveSizeInBits();
38       int64_t Val = INT64_MAX;             // All ones
39       Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
40       return ConstantInt::get(Ty, Val);
41     }
42     return ConstantInt::getAllOnesValue(Ty);
43   }
44   return 0;
45 }
46
47 // Static constructor to create the minimum constant for an integral type...
48 static ConstantInt *getMinValue(const Type *Ty, bool isSigned = false) {
49   if (Ty->isIntegral()) {
50     if (isSigned) {
51       // Calculate 1111111111000000000000
52       unsigned TypeBits = Ty->getPrimitiveSizeInBits();
53       int64_t Val = -1;                    // All ones
54       Val <<= TypeBits-1;                  // Shift over to the right spot
55       return ConstantInt::get(Ty, Val);
56     }
57     return ConstantInt::get(Ty, 0);
58   }
59   return 0;
60 }
61 static ConstantInt *Next(ConstantInt *CI) {
62   Constant *Result = ConstantExpr::getAdd(CI,
63                                           ConstantInt::get(CI->getType(), 1));
64   return cast<ConstantInt>(Result);
65 }
66
67 static bool LT(ConstantInt *A, ConstantInt *B, bool isSigned) {
68   Constant *C = ConstantExpr::getICmp(
69     (isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT), A, B);
70   assert(isa<ConstantInt>(C) && "Constant folding of integrals not impl??");
71   return cast<ConstantInt>(C)->getZExtValue();
72 }
73
74 static bool LTE(ConstantInt *A, ConstantInt *B, bool isSigned) {
75   Constant *C = ConstantExpr::getICmp(
76     (isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE), A, B);
77   assert(isa<ConstantInt>(C) && "Constant folding of integrals not impl??");
78   return cast<ConstantInt>(C)->getZExtValue();
79 }
80
81 static bool GT(ConstantInt *A, ConstantInt *B, bool isSigned) { 
82   return LT(B, A, isSigned); }
83
84 static ConstantInt *Min(ConstantInt *A, ConstantInt *B, 
85                              bool isSigned) {
86   return LT(A, B, isSigned) ? A : B;
87 }
88 static ConstantInt *Max(ConstantInt *A, ConstantInt *B,
89                              bool isSigned) {
90   return GT(A, B, isSigned) ? A : B;
91 }
92
93 /// Initialize a full (the default) or empty set for the specified type.
94 ///
95 ConstantRange::ConstantRange(const Type *Ty, bool Full) {
96   assert(Ty->isIntegral() &&
97          "Cannot make constant range of non-integral type!");
98   if (Full)
99     Lower = Upper = getMaxValue(Ty);
100   else
101     Lower = Upper = getMinValue(Ty);
102 }
103
104 /// Initialize a range to hold the single specified value.
105 ///
106 ConstantRange::ConstantRange(Constant *V) 
107   : Lower(cast<ConstantInt>(V)), Upper(Next(cast<ConstantInt>(V))) { }
108
109 /// Initialize a range of values explicitly... this will assert out if
110 /// Lower==Upper and Lower != Min or Max for its type (or if the two constants
111 /// have different types)
112 ///
113 ConstantRange::ConstantRange(Constant *L, Constant *U) 
114   : Lower(cast<ConstantInt>(L)), Upper(cast<ConstantInt>(U)) {
115   assert(Lower->getType() == Upper->getType() &&
116          "Incompatible types for ConstantRange!");
117
118   // Make sure that if L & U are equal that they are either Min or Max...
119   assert((L != U || (L == getMaxValue(L->getType()) ||
120                      L == getMinValue(L->getType())))
121           && "Lower == Upper, but they aren't min or max for type!");
122 }
123
124 /// Initialize a set of values that all satisfy the condition with C.
125 ///
126 ConstantRange::ConstantRange(unsigned short ICmpOpcode, ConstantInt *C) {
127   switch (ICmpOpcode) {
128   default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
129   case ICmpInst::ICMP_EQ: Lower = C; Upper = Next(C); return;
130   case ICmpInst::ICMP_NE: Upper = C; Lower = Next(C); return;
131   case ICmpInst::ICMP_ULT:
132     Lower = getMinValue(C->getType());
133     Upper = C;
134     return;
135   case ICmpInst::ICMP_SLT:
136     Lower = getMinValue(C->getType(), true);
137     Upper = C;
138     return;
139   case ICmpInst::ICMP_UGT:
140     Lower = Next(C);
141     Upper = getMinValue(C->getType());        // Min = Next(Max)
142     return;
143   case ICmpInst::ICMP_SGT:
144     Lower = Next(C);
145     Upper = getMinValue(C->getType(), true);  // Min = Next(Max)
146     return;
147   case ICmpInst::ICMP_ULE:
148     Lower = getMinValue(C->getType());
149     Upper = Next(C);
150     return;
151   case ICmpInst::ICMP_SLE:
152     Lower = getMinValue(C->getType(), true);
153     Upper = Next(C);
154     return;
155   case ICmpInst::ICMP_UGE:
156     Lower = C;
157     Upper = getMinValue(C->getType());        // Min = Next(Max)
158     return;
159   case ICmpInst::ICMP_SGE:
160     Lower = C;
161     Upper = getMinValue(C->getType(), true);  // Min = Next(Max)
162     return;
163   }
164 }
165
166 /// getType - Return the LLVM data type of this range.
167 ///
168 const Type *ConstantRange::getType() const { return Lower->getType(); }
169
170 /// isFullSet - Return true if this set contains all of the elements possible
171 /// for this data-type
172 bool ConstantRange::isFullSet() const {
173   return Lower == Upper && Lower == getMaxValue(getType());
174 }
175
176 /// isEmptySet - Return true if this set contains no members.
177 ///
178 bool ConstantRange::isEmptySet() const {
179   return Lower == Upper && Lower == getMinValue(getType());
180 }
181
182 /// isWrappedSet - Return true if this set wraps around the top of the range,
183 /// for example: [100, 8)
184 ///
185 bool ConstantRange::isWrappedSet(bool isSigned) const {
186   return GT(Lower, Upper, isSigned);
187 }
188
189 /// getSingleElement - If this set contains a single element, return it,
190 /// otherwise return null.
191 ConstantInt *ConstantRange::getSingleElement() const {
192   if (Upper == Next(Lower))  // Is it a single element range?
193     return Lower;
194   return 0;
195 }
196
197 /// getSetSize - Return the number of elements in this set.
198 ///
199 uint64_t ConstantRange::getSetSize() const {
200   if (isEmptySet()) return 0;
201   if (getType() == Type::Int1Ty) {
202     if (Lower != Upper)  // One of T or F in the set...
203       return 1;
204     return 2;            // Must be full set...
205   }
206
207   // Simply subtract the bounds...
208   Constant *Result = ConstantExpr::getSub(Upper, Lower);
209   return cast<ConstantInt>(Result)->getZExtValue();
210 }
211
212 /// contains - Return true if the specified value is in the set.
213 ///
214 bool ConstantRange::contains(ConstantInt *Val, bool isSigned) const {
215   if (Lower == Upper) {
216     if (isFullSet()) return true;
217     return false;
218   }
219
220   if (!isWrappedSet(isSigned))
221     return LTE(Lower, Val, isSigned) && LT(Val, Upper, isSigned);
222   return LTE(Lower, Val, isSigned) || LT(Val, Upper, isSigned);
223 }
224
225 /// subtract - Subtract the specified constant from the endpoints of this
226 /// constant range.
227 ConstantRange ConstantRange::subtract(ConstantInt *CI) const {
228   assert(CI->getType() == getType() && getType()->isIntegral() &&
229          "Cannot subtract from different type range or non-integer!");
230   // If the set is empty or full, don't modify the endpoints.
231   if (Lower == Upper) return *this;
232   return ConstantRange(ConstantExpr::getSub(Lower, CI),
233                        ConstantExpr::getSub(Upper, CI));
234 }
235
236
237 // intersect1Wrapped - This helper function is used to intersect two ranges when
238 // it is known that LHS is wrapped and RHS isn't.
239 //
240 static ConstantRange intersect1Wrapped(const ConstantRange &LHS,
241                                        const ConstantRange &RHS,
242                                        bool isSigned) {
243   assert(LHS.isWrappedSet(isSigned) && !RHS.isWrappedSet(isSigned));
244
245   // Check to see if we overlap on the Left side of RHS...
246   //
247   if (LT(RHS.getLower(), LHS.getUpper(), isSigned)) {
248     // We do overlap on the left side of RHS, see if we overlap on the right of
249     // RHS...
250     if (GT(RHS.getUpper(), LHS.getLower(), isSigned)) {
251       // Ok, the result overlaps on both the left and right sides.  See if the
252       // resultant interval will be smaller if we wrap or not...
253       //
254       if (LHS.getSetSize() < RHS.getSetSize())
255         return LHS;
256       else
257         return RHS;
258
259     } else {
260       // No overlap on the right, just on the left.
261       return ConstantRange(RHS.getLower(), LHS.getUpper());
262     }
263   } else {
264     // We don't overlap on the left side of RHS, see if we overlap on the right
265     // of RHS...
266     if (GT(RHS.getUpper(), LHS.getLower(), isSigned)) {
267       // Simple overlap...
268       return ConstantRange(LHS.getLower(), RHS.getUpper());
269     } else {
270       // No overlap...
271       return ConstantRange(LHS.getType(), false);
272     }
273   }
274 }
275
276 /// intersect - Return the range that results from the intersection of this
277 /// range with another range.
278 ///
279 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
280                                            bool isSigned) const {
281   assert(getType() == CR.getType() && "ConstantRange types don't agree!");
282   // Handle common special cases
283   if (isEmptySet() || CR.isFullSet())  return *this;
284   if (isFullSet()  || CR.isEmptySet()) return CR;
285
286   if (!isWrappedSet(isSigned)) {
287     if (!CR.isWrappedSet(isSigned)) {
288       ConstantInt *L = Max(Lower, CR.Lower, isSigned);
289       ConstantInt *U = Min(Upper, CR.Upper, isSigned);
290
291       if (LT(L, U, isSigned))  // If range isn't empty...
292         return ConstantRange(L, U);
293       else
294         return ConstantRange(getType(), false);  // Otherwise, return empty set
295     } else
296       return intersect1Wrapped(CR, *this, isSigned);
297   } else {   // We know "this" is wrapped...
298     if (!CR.isWrappedSet(isSigned))
299       return intersect1Wrapped(*this, CR, isSigned);
300     else {
301       // Both ranges are wrapped...
302       ConstantInt *L = Max(Lower, CR.Lower, isSigned);
303       ConstantInt *U = Min(Upper, CR.Upper, isSigned);
304       return ConstantRange(L, U);
305     }
306   }
307   return *this;
308 }
309
310 /// union - Return the range that results from the union of this range with
311 /// another range.  The resultant range is guaranteed to include the elements of
312 /// both sets, but may contain more.  For example, [3, 9) union [12,15) is [3,
313 /// 15), which includes 9, 10, and 11, which were not included in either set
314 /// before.
315 ///
316 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
317                                        bool isSigned) const {
318   assert(getType() == CR.getType() && "ConstantRange types don't agree!");
319
320   assert(0 && "Range union not implemented yet!");
321
322   return *this;
323 }
324
325 /// zeroExtend - Return a new range in the specified integer type, which must
326 /// be strictly larger than the current type.  The returned range will
327 /// correspond to the possible range of values as if the source range had been
328 /// zero extended.
329 ConstantRange ConstantRange::zeroExtend(const Type *Ty) const {
330   unsigned SrcTySize = getLower()->getType()->getPrimitiveSizeInBits();
331   assert(SrcTySize < Ty->getPrimitiveSizeInBits() && "Not a value extension");
332   if (isFullSet()) {
333     // Change a source full set into [0, 1 << 8*numbytes)
334     return ConstantRange(Constant::getNullValue(Ty),
335                          ConstantInt::get(Ty, 1ULL << SrcTySize));
336   }
337
338   Constant *Lower = getLower();
339   Constant *Upper = getUpper();
340
341   return ConstantRange(ConstantExpr::getZExt(Lower, Ty),
342                        ConstantExpr::getZExt(Upper, Ty));
343 }
344
345 /// truncate - Return a new range in the specified integer type, which must be
346 /// strictly smaller than the current type.  The returned range will
347 /// correspond to the possible range of values as if the source range had been
348 /// truncated to the specified type.
349 ConstantRange ConstantRange::truncate(const Type *Ty) const {
350   unsigned SrcTySize = getLower()->getType()->getPrimitiveSizeInBits();
351   assert(SrcTySize > Ty->getPrimitiveSizeInBits() && "Not a value truncation");
352   uint64_t Size = 1ULL << Ty->getPrimitiveSizeInBits();
353   if (isFullSet() || getSetSize() >= Size)
354     return ConstantRange(getType());
355
356   return ConstantRange(
357       ConstantExpr::getTrunc(getLower(), Ty),
358       ConstantExpr::getTrunc(getUpper(), Ty));
359 }
360
361 /// print - Print out the bounds to a stream...
362 ///
363 void ConstantRange::print(std::ostream &OS) const {
364   OS << "[" << *Lower << "," << *Upper << " )";
365 }
366
367 /// dump - Allow printing from a debugger easily...
368 ///
369 void ConstantRange::dump() const {
370   print(cerr);
371 }