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