blob: a85ad465317ca94a45c1af8b175fcc047ba76aa4 [file] [log] [blame]
Chris Lattner113f2ae2002-09-01 23:53:36 +00001//===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner113f2ae2002-09-01 23:53:36 +00009//
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
Sanjoy Das6ed05302015-10-22 03:12:57 +000024#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/InstrTypes.h"
Sanjoy Das6ed05302015-10-22 03:12:57 +000026#include "llvm/IR/Operator.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000027#include "llvm/IR/ConstantRange.h"
David Greenede7b3532010-01-05 01:28:32 +000028#include "llvm/Support/Debug.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc9499b62003-12-14 21:35:53 +000030using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000031
Chris Lattner113f2ae2002-09-01 23:53:36 +000032/// Initialize a full (the default) or empty set for the specified type.
33///
Dan Gohmandc33ae22009-07-09 23:16:10 +000034ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) {
Chris Lattner113f2ae2002-09-01 23:53:36 +000035 if (Full)
Reid Spencere1f3f192007-02-28 17:36:23 +000036 Lower = Upper = APInt::getMaxValue(BitWidth);
Chris Lattner113f2ae2002-09-01 23:53:36 +000037 else
Reid Spencere1f3f192007-02-28 17:36:23 +000038 Lower = Upper = APInt::getMinValue(BitWidth);
Chris Lattner113f2ae2002-09-01 23:53:36 +000039}
40
Chris Lattner55481f72004-03-30 00:20:08 +000041/// Initialize a range to hold the single specified value.
42///
Benjamin Kramercce97be2013-07-11 15:37:27 +000043ConstantRange::ConstantRange(APIntMoveTy V)
Chandler Carruth002da5d2014-03-02 04:08:41 +000044 : Lower(std::move(V)), Upper(Lower + 1) {}
Chris Lattner113f2ae2002-09-01 23:53:36 +000045
Benjamin Kramercce97be2013-07-11 15:37:27 +000046ConstantRange::ConstantRange(APIntMoveTy L, APIntMoveTy U)
Chandler Carruth002da5d2014-03-02 04:08:41 +000047 : Lower(std::move(L)), Upper(std::move(U)) {
Benjamin Kramercce97be2013-07-11 15:37:27 +000048 assert(Lower.getBitWidth() == Upper.getBitWidth() &&
Dan Gohmandc33ae22009-07-09 23:16:10 +000049 "ConstantRange with unequal bit widths");
Benjamin Kramercce97be2013-07-11 15:37:27 +000050 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
Reid Spencere1f3f192007-02-28 17:36:23 +000051 "Lower == Upper, but they aren't min or max value!");
52}
53
Sanjoy Das7182d362015-03-18 00:41:24 +000054ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
55 const ConstantRange &CR) {
Nick Lewycky5154ee02010-09-28 18:18:36 +000056 if (CR.isEmptySet())
57 return CR;
58
Nick Lewyckydcfdce92009-07-11 06:15:39 +000059 uint32_t W = CR.getBitWidth();
60 switch (Pred) {
Sanjoy Das7182d362015-03-18 00:41:24 +000061 default:
62 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000063 case CmpInst::ICMP_EQ:
64 return CR;
65 case CmpInst::ICMP_NE:
66 if (CR.isSingleElement())
67 return ConstantRange(CR.getUpper(), CR.getLower());
68 return ConstantRange(W);
69 case CmpInst::ICMP_ULT: {
70 APInt UMax(CR.getUnsignedMax());
71 if (UMax.isMinValue())
72 return ConstantRange(W, /* empty */ false);
73 return ConstantRange(APInt::getMinValue(W), UMax);
74 }
75 case CmpInst::ICMP_SLT: {
76 APInt SMax(CR.getSignedMax());
77 if (SMax.isMinSignedValue())
78 return ConstantRange(W, /* empty */ false);
79 return ConstantRange(APInt::getSignedMinValue(W), SMax);
80 }
81 case CmpInst::ICMP_ULE: {
82 APInt UMax(CR.getUnsignedMax());
83 if (UMax.isMaxValue())
Nick Lewyckydcfdce92009-07-11 06:15:39 +000084 return ConstantRange(W);
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000085 return ConstantRange(APInt::getMinValue(W), UMax + 1);
86 }
87 case CmpInst::ICMP_SLE: {
88 APInt SMax(CR.getSignedMax());
89 if (SMax.isMaxSignedValue())
90 return ConstantRange(W);
91 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
92 }
93 case CmpInst::ICMP_UGT: {
94 APInt UMin(CR.getUnsignedMin());
95 if (UMin.isMaxValue())
96 return ConstantRange(W, /* empty */ false);
97 return ConstantRange(UMin + 1, APInt::getNullValue(W));
98 }
99 case CmpInst::ICMP_SGT: {
100 APInt SMin(CR.getSignedMin());
101 if (SMin.isMaxSignedValue())
102 return ConstantRange(W, /* empty */ false);
103 return ConstantRange(SMin + 1, APInt::getSignedMinValue(W));
104 }
105 case CmpInst::ICMP_UGE: {
106 APInt UMin(CR.getUnsignedMin());
107 if (UMin.isMinValue())
108 return ConstantRange(W);
109 return ConstantRange(UMin, APInt::getNullValue(W));
110 }
111 case CmpInst::ICMP_SGE: {
112 APInt SMin(CR.getSignedMin());
113 if (SMin.isMinSignedValue())
114 return ConstantRange(W);
115 return ConstantRange(SMin, APInt::getSignedMinValue(W));
116 }
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000117 }
118}
119
Sanjoy Das7182d362015-03-18 00:41:24 +0000120ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
121 const ConstantRange &CR) {
122 // Follows from De-Morgan's laws:
123 //
124 // ~(~A union ~B) == A intersect B.
125 //
126 return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
127 .inverse();
128}
129
Balaram Makam569eaec2016-05-04 21:32:14 +0000130ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
131 const APInt &C) {
132 // Computes the exact range that is equal to both the constant ranges returned
133 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
134 // when RHS is a singleton such as an APInt and so the assert is valid.
135 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
136 // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
137 //
138 assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
139 return makeAllowedICmpRegion(Pred, C);
140}
141
Sanjoy Das590614c2016-05-19 03:53:06 +0000142bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
143 APInt &RHS) const {
144 bool Success = false;
145
146 if (isFullSet() || isEmptySet()) {
147 Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
148 RHS = APInt(getBitWidth(), 0);
149 Success = true;
Sanjoy Dasc7d32912016-10-02 20:59:05 +0000150 } else if (auto *OnlyElt = getSingleElement()) {
151 Pred = CmpInst::ICMP_EQ;
152 RHS = *OnlyElt;
153 Success = true;
154 } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
155 Pred = CmpInst::ICMP_NE;
156 RHS = *OnlyMissingElt;
157 Success = true;
Sanjoy Das590614c2016-05-19 03:53:06 +0000158 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
159 Pred =
160 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
161 RHS = getUpper();
162 Success = true;
163 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
164 Pred =
165 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
166 RHS = getLower();
167 Success = true;
168 }
169
170 assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
171 "Bad result!");
172
173 return Success;
174}
175
Sanjoy Das5079f622016-02-22 16:13:02 +0000176ConstantRange
177ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000178 const ConstantRange &Other,
179 unsigned NoWrapKind) {
Sanjoy Das6ed05302015-10-22 03:12:57 +0000180 typedef OverflowingBinaryOperator OBO;
181
182 // Computes the intersection of CR0 and CR1. It is different from
183 // intersectWith in that the ConstantRange returned will only contain elements
184 // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or
185 // not, of both X and Y).
186 auto SubsetIntersect =
187 [](const ConstantRange &CR0, const ConstantRange &CR1) {
188 return CR0.inverse().unionWith(CR1.inverse()).inverse();
189 };
190
191 assert(BinOp >= Instruction::BinaryOpsBegin &&
192 BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
193
194 assert((NoWrapKind == OBO::NoSignedWrap ||
195 NoWrapKind == OBO::NoUnsignedWrap ||
196 NoWrapKind == (OBO::NoUnsignedWrap | OBO::NoSignedWrap)) &&
197 "NoWrapKind invalid!");
198
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000199 unsigned BitWidth = Other.getBitWidth();
Sanjoy Das6ed05302015-10-22 03:12:57 +0000200 if (BinOp != Instruction::Add)
201 // Conservative answer: empty set
202 return ConstantRange(BitWidth, false);
203
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000204 if (auto *C = Other.getSingleElement())
205 if (C->isMinValue())
206 // Full set: nothing signed / unsigned wraps when added to 0.
207 return ConstantRange(BitWidth);
Sanjoy Das6ed05302015-10-22 03:12:57 +0000208
209 ConstantRange Result(BitWidth);
210
211 if (NoWrapKind & OBO::NoUnsignedWrap)
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000212 Result =
213 SubsetIntersect(Result, ConstantRange(APInt::getNullValue(BitWidth),
214 -Other.getUnsignedMax()));
Sanjoy Das6ed05302015-10-22 03:12:57 +0000215
216 if (NoWrapKind & OBO::NoSignedWrap) {
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000217 APInt SignedMin = Other.getSignedMin();
218 APInt SignedMax = Other.getSignedMax();
219
220 if (SignedMax.isStrictlyPositive())
Sanjoy Das6ed05302015-10-22 03:12:57 +0000221 Result = SubsetIntersect(
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000222 Result,
223 ConstantRange(APInt::getSignedMinValue(BitWidth),
224 APInt::getSignedMinValue(BitWidth) - SignedMax));
225
226 if (SignedMin.isNegative())
Sanjoy Das6ed05302015-10-22 03:12:57 +0000227 Result = SubsetIntersect(
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000228 Result, ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin,
Sanjoy Das6ed05302015-10-22 03:12:57 +0000229 APInt::getSignedMinValue(BitWidth)));
230 }
231
232 return Result;
233}
234
Chris Lattner113f2ae2002-09-01 23:53:36 +0000235/// isFullSet - Return true if this set contains all of the elements possible
236/// for this data-type
237bool ConstantRange::isFullSet() const {
Zhou Sheng31787362007-04-26 16:42:07 +0000238 return Lower == Upper && Lower.isMaxValue();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000239}
Misha Brukmanb1c93172005-04-21 23:48:37 +0000240
Chris Lattner113f2ae2002-09-01 23:53:36 +0000241/// isEmptySet - Return true if this set contains no members.
242///
243bool ConstantRange::isEmptySet() const {
Zhou Sheng31787362007-04-26 16:42:07 +0000244 return Lower == Upper && Lower.isMinValue();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000245}
246
247/// isWrappedSet - Return true if this set wraps around the top of the range,
248/// for example: [100, 8)
249///
Reid Spencer6a440332007-03-01 07:54:15 +0000250bool ConstantRange::isWrappedSet() const {
Reid Spencere1f3f192007-02-28 17:36:23 +0000251 return Lower.ugt(Upper);
Chris Lattner113f2ae2002-09-01 23:53:36 +0000252}
253
Nick Lewyckya35462d2010-09-06 23:52:49 +0000254/// isSignWrappedSet - Return true if this set wraps around the INT_MIN of
255/// its bitwidth, for example: i8 [120, 140).
256///
257bool ConstantRange::isSignWrappedSet() const {
258 return contains(APInt::getSignedMaxValue(getBitWidth())) &&
259 contains(APInt::getSignedMinValue(getBitWidth()));
260}
261
Chris Lattner113f2ae2002-09-01 23:53:36 +0000262/// getSetSize - Return the number of elements in this set.
263///
Reid Spencere1f3f192007-02-28 17:36:23 +0000264APInt ConstantRange::getSetSize() const {
Nuno Lopes216d5712012-07-17 15:43:59 +0000265 if (isFullSet()) {
266 APInt Size(getBitWidth()+1, 0);
267 Size.setBit(getBitWidth());
268 return Size;
Chris Lattner113f2ae2002-09-01 23:53:36 +0000269 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000270
Nuno Lopes216d5712012-07-17 15:43:59 +0000271 // This is also correct for wrapped sets.
Nuno Lopes99504c52012-07-16 18:08:12 +0000272 return (Upper - Lower).zext(getBitWidth()+1);
Chris Lattner113f2ae2002-09-01 23:53:36 +0000273}
274
Nick Lewyckye4559372007-03-10 15:54:12 +0000275/// getUnsignedMax - Return the largest unsigned value contained in the
276/// ConstantRange.
277///
278APInt ConstantRange::getUnsignedMax() const {
279 if (isFullSet() || isWrappedSet())
280 return APInt::getMaxValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000281 return getUpper() - 1;
Nick Lewyckye4559372007-03-10 15:54:12 +0000282}
283
284/// getUnsignedMin - Return the smallest unsigned value contained in the
285/// ConstantRange.
286///
287APInt ConstantRange::getUnsignedMin() const {
288 if (isFullSet() || (isWrappedSet() && getUpper() != 0))
289 return APInt::getMinValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000290 return getLower();
Nick Lewyckye4559372007-03-10 15:54:12 +0000291}
292
293/// getSignedMax - Return the largest signed value contained in the
294/// ConstantRange.
295///
296APInt ConstantRange::getSignedMax() const {
Zhou Sheng01c175e2007-04-13 05:57:32 +0000297 APInt SignedMax(APInt::getSignedMaxValue(getBitWidth()));
Nick Lewyckye4559372007-03-10 15:54:12 +0000298 if (!isWrappedSet()) {
Nick Lewyckyd18b1602007-06-09 04:20:33 +0000299 if (getLower().sle(getUpper() - 1))
Nick Lewyckye4559372007-03-10 15:54:12 +0000300 return getUpper() - 1;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000301 return SignedMax;
Nick Lewyckye4559372007-03-10 15:54:12 +0000302 }
Nick Lewycky228f5b42012-01-03 20:33:00 +0000303 if (getLower().isNegative() == getUpper().isNegative())
304 return SignedMax;
305 return getUpper() - 1;
Nick Lewyckye4559372007-03-10 15:54:12 +0000306}
307
308/// getSignedMin - Return the smallest signed value contained in the
309/// ConstantRange.
310///
311APInt ConstantRange::getSignedMin() const {
Zhou Sheng01c175e2007-04-13 05:57:32 +0000312 APInt SignedMin(APInt::getSignedMinValue(getBitWidth()));
Nick Lewyckye4559372007-03-10 15:54:12 +0000313 if (!isWrappedSet()) {
Nick Lewyckyd18b1602007-06-09 04:20:33 +0000314 if (getLower().sle(getUpper() - 1))
Nick Lewyckye4559372007-03-10 15:54:12 +0000315 return getLower();
Nick Lewycky228f5b42012-01-03 20:33:00 +0000316 return SignedMin;
Nick Lewyckye4559372007-03-10 15:54:12 +0000317 }
Nick Lewycky228f5b42012-01-03 20:33:00 +0000318 if ((getUpper() - 1).slt(getLower())) {
319 if (getUpper() != SignedMin)
320 return SignedMin;
321 }
322 return getLower();
Nick Lewyckye4559372007-03-10 15:54:12 +0000323}
324
Chris Lattner55481f72004-03-30 00:20:08 +0000325/// contains - Return true if the specified value is in the set.
326///
Reid Spencer6a440332007-03-01 07:54:15 +0000327bool ConstantRange::contains(const APInt &V) const {
328 if (Lower == Upper)
329 return isFullSet();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000330
Reid Spencer6a440332007-03-01 07:54:15 +0000331 if (!isWrappedSet())
332 return Lower.ule(V) && V.ult(Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000333 return Lower.ule(V) || V.ult(Upper);
Chris Lattner55481f72004-03-30 00:20:08 +0000334}
335
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000336/// contains - Return true if the argument is a subset of this range.
Nick Lewyckyd385c222010-08-11 22:04:36 +0000337/// Two equal sets contain each other. The empty set contained by all other
338/// sets.
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000339///
340bool ConstantRange::contains(const ConstantRange &Other) const {
Nick Lewyckyd385c222010-08-11 22:04:36 +0000341 if (isFullSet() || Other.isEmptySet()) return true;
342 if (isEmptySet() || Other.isFullSet()) return false;
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000343
344 if (!isWrappedSet()) {
345 if (Other.isWrappedSet())
346 return false;
347
348 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
349 }
350
351 if (!Other.isWrappedSet())
352 return Other.getUpper().ule(Upper) ||
353 Lower.ule(Other.getLower());
354
355 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
356}
357
Chris Lattner55481f72004-03-30 00:20:08 +0000358/// subtract - Subtract the specified constant from the endpoints of this
359/// constant range.
Reid Spencer3a7e9d82007-02-28 19:57:34 +0000360ConstantRange ConstantRange::subtract(const APInt &Val) const {
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000361 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
Chris Lattner55481f72004-03-30 00:20:08 +0000362 // If the set is empty or full, don't modify the endpoints.
Reid Spencere1f3f192007-02-28 17:36:23 +0000363 if (Lower == Upper)
364 return *this;
Reid Spencere1f3f192007-02-28 17:36:23 +0000365 return ConstantRange(Lower - Val, Upper - Val);
Chris Lattner55481f72004-03-30 00:20:08 +0000366}
Chris Lattner113f2ae2002-09-01 23:53:36 +0000367
Nuno Lopes5020db22012-06-28 16:10:13 +0000368/// \brief Subtract the specified range from this range (aka relative complement
369/// of the sets).
370ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
371 return intersectWith(CR.inverse());
372}
373
Nick Lewycky63f11082007-02-11 00:58:49 +0000374/// intersectWith - Return the range that results from the intersection of this
Nick Lewycky0d139032009-07-18 06:34:42 +0000375/// range with another range. The resultant range is guaranteed to include all
376/// elements contained in both input ranges, and to have the smallest possible
377/// set size that does so. Because there may be two intersections with the
378/// same set size, A.intersectWith(B) might not be equal to B.intersectWith(A).
Reid Spencer6a440332007-03-01 07:54:15 +0000379ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000380 assert(getBitWidth() == CR.getBitWidth() &&
381 "ConstantRange types don't agree!");
Nick Lewycky61b4a262007-07-14 02:51:34 +0000382
383 // Handle common cases.
384 if ( isEmptySet() || CR.isFullSet()) return *this;
385 if (CR.isEmptySet() || isFullSet()) return CR;
386
387 if (!isWrappedSet() && CR.isWrappedSet())
Nick Lewycky0d139032009-07-18 06:34:42 +0000388 return CR.intersectWith(*this);
Nick Lewycky61b4a262007-07-14 02:51:34 +0000389
390 if (!isWrappedSet() && !CR.isWrappedSet()) {
391 if (Lower.ult(CR.Lower)) {
392 if (Upper.ule(CR.Lower))
393 return ConstantRange(getBitWidth(), false);
394
395 if (Upper.ult(CR.Upper))
396 return ConstantRange(CR.Lower, Upper);
397
398 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000399 }
Nick Lewycky228f5b42012-01-03 20:33:00 +0000400 if (Upper.ult(CR.Upper))
401 return *this;
402
403 if (Lower.ult(CR.Upper))
404 return ConstantRange(Lower, CR.Upper);
405
406 return ConstantRange(getBitWidth(), false);
Nick Lewycky61b4a262007-07-14 02:51:34 +0000407 }
408
409 if (isWrappedSet() && !CR.isWrappedSet()) {
410 if (CR.Lower.ult(Upper)) {
411 if (CR.Upper.ult(Upper))
412 return CR;
413
Nuno Lopes63afc082012-05-18 00:14:36 +0000414 if (CR.Upper.ule(Lower))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000415 return ConstantRange(CR.Lower, Upper);
416
417 if (getSetSize().ult(CR.getSetSize()))
418 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000419 return CR;
420 }
421 if (CR.Lower.ult(Lower)) {
Nick Lewycky61b4a262007-07-14 02:51:34 +0000422 if (CR.Upper.ule(Lower))
423 return ConstantRange(getBitWidth(), false);
424
425 return ConstantRange(Lower, CR.Upper);
426 }
427 return CR;
428 }
429
430 if (CR.Upper.ult(Upper)) {
431 if (CR.Lower.ult(Upper)) {
432 if (getSetSize().ult(CR.getSetSize()))
433 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000434 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000435 }
436
437 if (CR.Lower.ult(Lower))
438 return ConstantRange(Lower, CR.Upper);
439
440 return CR;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000441 }
Nuno Lopesebb0c942012-06-28 00:59:33 +0000442 if (CR.Upper.ule(Lower)) {
Nick Lewycky61b4a262007-07-14 02:51:34 +0000443 if (CR.Lower.ult(Lower))
444 return *this;
445
446 return ConstantRange(CR.Lower, Upper);
447 }
448 if (getSetSize().ult(CR.getSetSize()))
449 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000450 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000451}
452
453
Nick Lewycky63f11082007-02-11 00:58:49 +0000454/// unionWith - Return the range that results from the union of this range with
Chris Lattner113f2ae2002-09-01 23:53:36 +0000455/// another range. The resultant range is guaranteed to include the elements of
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000456/// both sets, but may contain more. For example, [3, 9) union [12,15) is
457/// [3, 15), which includes 9, 10, and 11, which were not included in either
458/// set before.
Chris Lattner113f2ae2002-09-01 23:53:36 +0000459///
Reid Spencer6a440332007-03-01 07:54:15 +0000460ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000461 assert(getBitWidth() == CR.getBitWidth() &&
462 "ConstantRange types don't agree!");
Chris Lattner113f2ae2002-09-01 23:53:36 +0000463
Nick Lewyckycf87f9e2007-03-02 03:33:05 +0000464 if ( isFullSet() || CR.isEmptySet()) return *this;
465 if (CR.isFullSet() || isEmptySet()) return CR;
Chris Lattner113f2ae2002-09-01 23:53:36 +0000466
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000467 if (!isWrappedSet() && CR.isWrappedSet()) return CR.unionWith(*this);
468
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000469 if (!isWrappedSet() && !CR.isWrappedSet()) {
Nick Lewycky567daf32009-07-19 03:44:35 +0000470 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) {
471 // If the two ranges are disjoint, find the smaller gap and bridge it.
472 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
473 if (d1.ult(d2))
474 return ConstantRange(Lower, CR.Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000475 return ConstantRange(CR.Lower, Upper);
Nick Lewycky567daf32009-07-19 03:44:35 +0000476 }
477
478 APInt L = Lower, U = Upper;
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000479 if (CR.Lower.ult(L))
480 L = CR.Lower;
Nick Lewycky567daf32009-07-19 03:44:35 +0000481 if ((CR.Upper - 1).ugt(U - 1))
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000482 U = CR.Upper;
Nick Lewycky567daf32009-07-19 03:44:35 +0000483
484 if (L == 0 && U == 0)
485 return ConstantRange(getBitWidth());
486
487 return ConstantRange(L, U);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000488 }
489
Nick Lewycky567daf32009-07-19 03:44:35 +0000490 if (!CR.isWrappedSet()) {
491 // ------U L----- and ------U L----- : this
492 // L--U L--U : CR
493 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000494 return *this;
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000495
Nick Lewycky567daf32009-07-19 03:44:35 +0000496 // ------U L----- : this
497 // L---------U : CR
498 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000499 return ConstantRange(getBitWidth());
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000500
Nick Lewycky567daf32009-07-19 03:44:35 +0000501 // ----U L---- : this
502 // L---U : CR
503 // <d1> <d2>
504 if (Upper.ule(CR.Lower) && CR.Upper.ule(Lower)) {
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000505 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
Nick Lewycky567daf32009-07-19 03:44:35 +0000506 if (d1.ult(d2))
507 return ConstantRange(Lower, CR.Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000508 return ConstantRange(CR.Lower, Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000509 }
510
Nick Lewycky567daf32009-07-19 03:44:35 +0000511 // ----U L----- : this
512 // L----U : CR
513 if (Upper.ult(CR.Lower) && Lower.ult(CR.Upper))
514 return ConstantRange(CR.Lower, Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000515
Nick Lewycky567daf32009-07-19 03:44:35 +0000516 // ------U L---- : this
517 // L-----U : CR
Nick Lewycky228f5b42012-01-03 20:33:00 +0000518 assert(CR.Lower.ult(Upper) && CR.Upper.ult(Lower) &&
519 "ConstantRange::unionWith missed a case with one range wrapped");
520 return ConstantRange(Lower, CR.Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000521 }
522
Nick Lewycky567daf32009-07-19 03:44:35 +0000523 // ------U L---- and ------U L---- : this
524 // -U L----------- and ------------U L : CR
525 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
526 return ConstantRange(getBitWidth());
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000527
Nick Lewycky567daf32009-07-19 03:44:35 +0000528 APInt L = Lower, U = Upper;
529 if (CR.Upper.ugt(U))
530 U = CR.Upper;
531 if (CR.Lower.ult(L))
532 L = CR.Lower;
Nick Lewyckycf87f9e2007-03-02 03:33:05 +0000533
534 return ConstantRange(L, U);
Chris Lattner113f2ae2002-09-01 23:53:36 +0000535}
Chris Lattnere0bb9eb2002-09-02 00:18:22 +0000536
Philip Reames4d00af12016-12-01 20:08:47 +0000537ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
538 uint32_t ResultBitWidth) const {
539 switch (CastOp) {
540 default:
541 llvm_unreachable("unsupported cast type");
542 case Instruction::Trunc:
543 return truncate(ResultBitWidth);
544 case Instruction::SExt:
545 return signExtend(ResultBitWidth);
546 case Instruction::ZExt:
547 return zeroExtend(ResultBitWidth);
548 case Instruction::BitCast:
549 return *this;
550 case Instruction::FPToUI:
551 case Instruction::FPToSI:
552 if (getBitWidth() == ResultBitWidth)
553 return *this;
554 else
555 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
556 case Instruction::UIToFP: {
557 // TODO: use input range if available
558 auto BW = getBitWidth();
559 APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
560 APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
561 return ConstantRange(Min, Max);
562 }
563 case Instruction::SIToFP: {
564 // TODO: use input range if available
565 auto BW = getBitWidth();
566 APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
567 APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
568 return ConstantRange(SMin, SMax);
569 }
570 case Instruction::FPTrunc:
571 case Instruction::FPExt:
572 case Instruction::IntToPtr:
573 case Instruction::PtrToInt:
574 case Instruction::AddrSpaceCast:
575 // Conservatively return full set.
576 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
577 };
578}
579
Chris Lattner55481f72004-03-30 00:20:08 +0000580/// zeroExtend - Return a new range in the specified integer type, which must
581/// be strictly larger than the current type. The returned range will
Reid Spencer266e42b2006-12-23 06:05:41 +0000582/// correspond to the possible range of values as if the source range had been
Chris Lattner55481f72004-03-30 00:20:08 +0000583/// zero extended.
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000584ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000585 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
586
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000587 unsigned SrcTySize = getBitWidth();
Reid Spencere1f3f192007-02-28 17:36:23 +0000588 assert(SrcTySize < DstTySize && "Not a value extension");
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000589 if (isFullSet() || isWrappedSet()) {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000590 // Change into [0, 1 << src bit width)
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000591 APInt LowerExt(DstTySize, 0);
592 if (!Upper) // special case: [X, 0) -- not really wrapping around
593 LowerExt = Lower.zext(DstTySize);
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000594 return ConstantRange(LowerExt, APInt::getOneBitSet(DstTySize, SrcTySize));
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000595 }
Chris Lattner55481f72004-03-30 00:20:08 +0000596
Jay Foad583abbc2010-12-07 08:25:19 +0000597 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
Chris Lattner55481f72004-03-30 00:20:08 +0000598}
599
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000600/// signExtend - Return a new range in the specified integer type, which must
601/// be strictly larger than the current type. The returned range will
602/// correspond to the possible range of values as if the source range had been
603/// sign extended.
604ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000605 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
606
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000607 unsigned SrcTySize = getBitWidth();
608 assert(SrcTySize < DstTySize && "Not a value extension");
Nuno Lopes1112eca2013-10-30 15:36:50 +0000609
610 // special case: [X, INT_MIN) -- not really wrapping around
Nuno Lopes14d4b0c2013-10-31 19:53:53 +0000611 if (Upper.isMinSignedValue())
Nuno Lopes1112eca2013-10-30 15:36:50 +0000612 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
613
Nick Lewyckya35462d2010-09-06 23:52:49 +0000614 if (isFullSet() || isSignWrappedSet()) {
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000615 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
Nick Lewycky5edc4592009-07-13 04:17:23 +0000616 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000617 }
618
Jay Foad583abbc2010-12-07 08:25:19 +0000619 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000620}
621
Chris Lattner55481f72004-03-30 00:20:08 +0000622/// truncate - Return a new range in the specified integer type, which must be
623/// strictly smaller than the current type. The returned range will
Reid Spencer266e42b2006-12-23 06:05:41 +0000624/// correspond to the possible range of values as if the source range had been
Chris Lattner55481f72004-03-30 00:20:08 +0000625/// truncated to the specified type.
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000626ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
Benjamin Kramer6709e052011-11-24 17:24:33 +0000627 assert(getBitWidth() > DstTySize && "Not a value truncation");
Nuno Lopesc14776d2012-07-19 16:27:45 +0000628 if (isEmptySet())
629 return ConstantRange(DstTySize, /*isFullSet=*/false);
630 if (isFullSet())
Nick Lewyckyd385c222010-08-11 22:04:36 +0000631 return ConstantRange(DstTySize, /*isFullSet=*/true);
Chris Lattner55481f72004-03-30 00:20:08 +0000632
Nuno Lopesc14776d2012-07-19 16:27:45 +0000633 APInt MaxValue = APInt::getMaxValue(DstTySize).zext(getBitWidth());
634 APInt MaxBitValue(getBitWidth(), 0);
635 MaxBitValue.setBit(DstTySize);
636
637 APInt LowerDiv(Lower), UpperDiv(Upper);
638 ConstantRange Union(DstTySize, /*isFullSet=*/false);
639
640 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
641 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
642 // then we do the union with [MaxValue, Upper)
643 if (isWrappedSet()) {
Nick Lewyckybfad0152016-06-06 01:51:23 +0000644 // If Upper is greater than Max Value, it covers the whole truncated range.
Nuno Lopesc14776d2012-07-19 16:27:45 +0000645 if (Upper.uge(MaxValue))
646 return ConstantRange(DstTySize, /*isFullSet=*/true);
647
648 Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
649 UpperDiv = APInt::getMaxValue(getBitWidth());
650
651 // Union covers the MaxValue case, so return if the remaining range is just
652 // MaxValue.
653 if (LowerDiv == UpperDiv)
654 return Union;
655 }
656
657 // Chop off the most significant bits that are past the destination bitwidth.
658 if (LowerDiv.uge(MaxValue)) {
659 APInt Div(getBitWidth(), 0);
660 APInt::udivrem(LowerDiv, MaxBitValue, Div, LowerDiv);
661 UpperDiv = UpperDiv - MaxBitValue * Div;
662 }
663
664 if (UpperDiv.ule(MaxValue))
665 return ConstantRange(LowerDiv.trunc(DstTySize),
666 UpperDiv.trunc(DstTySize)).unionWith(Union);
667
Nick Lewyckybfad0152016-06-06 01:51:23 +0000668 // The truncated value wraps around. Check if we can do better than fullset.
Nuno Lopesc14776d2012-07-19 16:27:45 +0000669 APInt UpperModulo = UpperDiv - MaxBitValue;
670 if (UpperModulo.ult(LowerDiv))
671 return ConstantRange(LowerDiv.trunc(DstTySize),
672 UpperModulo.trunc(DstTySize)).unionWith(Union);
673
674 return ConstantRange(DstTySize, /*isFullSet=*/true);
Chris Lattner55481f72004-03-30 00:20:08 +0000675}
676
Nuno Lopes640eb702009-11-09 15:36:28 +0000677/// zextOrTrunc - make this range have the bit width given by \p DstTySize. The
678/// value is zero extended, truncated, or left alone to make it that width.
679ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
680 unsigned SrcTySize = getBitWidth();
681 if (SrcTySize > DstTySize)
682 return truncate(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000683 if (SrcTySize < DstTySize)
Nuno Lopes640eb702009-11-09 15:36:28 +0000684 return zeroExtend(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000685 return *this;
Nuno Lopes640eb702009-11-09 15:36:28 +0000686}
687
688/// sextOrTrunc - make this range have the bit width given by \p DstTySize. The
689/// value is sign extended, truncated, or left alone to make it that width.
690ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
691 unsigned SrcTySize = getBitWidth();
692 if (SrcTySize > DstTySize)
693 return truncate(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000694 if (SrcTySize < DstTySize)
Nuno Lopes640eb702009-11-09 15:36:28 +0000695 return signExtend(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000696 return *this;
Nuno Lopes640eb702009-11-09 15:36:28 +0000697}
698
Philip Reames4d00af12016-12-01 20:08:47 +0000699ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
700 const ConstantRange &Other) const {
701 assert(BinOp >= Instruction::BinaryOpsBegin &&
702 BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
703
704 switch (BinOp) {
705 case Instruction::Add:
706 return add(Other);
707 case Instruction::Sub:
708 return sub(Other);
709 case Instruction::Mul:
710 return multiply(Other);
711 case Instruction::UDiv:
712 return udiv(Other);
713 case Instruction::Shl:
714 return shl(Other);
715 case Instruction::LShr:
716 return lshr(Other);
717 case Instruction::And:
718 return binaryAnd(Other);
719 case Instruction::Or:
720 return binaryOr(Other);
721 // Note: floating point operations applied to abstract ranges are just
722 // ideal integer operations with a lossy representation
723 case Instruction::FAdd:
724 return add(Other);
725 case Instruction::FSub:
726 return sub(Other);
727 case Instruction::FMul:
728 return multiply(Other);
729 default:
730 // Conservatively return full set.
731 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
732 }
733}
734
Dan Gohman5035fbf2009-07-09 22:07:27 +0000735ConstantRange
736ConstantRange::add(const ConstantRange &Other) const {
737 if (isEmptySet() || Other.isEmptySet())
738 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nick Lewycky73b704d2009-07-13 02:49:08 +0000739 if (isFullSet() || Other.isFullSet())
740 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000741
742 APInt Spread_X = getSetSize(), Spread_Y = Other.getSetSize();
743 APInt NewLower = getLower() + Other.getLower();
744 APInt NewUpper = getUpper() + Other.getUpper() - 1;
745 if (NewLower == NewUpper)
746 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
747
748 ConstantRange X = ConstantRange(NewLower, NewUpper);
749 if (X.getSetSize().ult(Spread_X) || X.getSetSize().ult(Spread_Y))
750 // We've wrapped, therefore, full set.
751 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
752
753 return X;
Chris Lattnere0bb9eb2002-09-02 00:18:22 +0000754}
755
Artur Pilipenkoed841032016-10-19 14:44:23 +0000756ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
757 // Calculate the subset of this range such that "X + Other" is
758 // guaranteed not to wrap (overflow) for all X in this subset.
759 // makeGuaranteedNoWrapRegion will produce an exact NSW range since we are
760 // passing a single element range.
761 auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(BinaryOperator::Add,
762 ConstantRange(Other),
763 OverflowingBinaryOperator::NoSignedWrap);
764 auto NSWConstrainedRange = intersectWith(NSWRange);
765
766 return NSWConstrainedRange.add(ConstantRange(Other));
767}
768
Dan Gohman5035fbf2009-07-09 22:07:27 +0000769ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000770ConstantRange::sub(const ConstantRange &Other) const {
771 if (isEmptySet() || Other.isEmptySet())
772 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
773 if (isFullSet() || Other.isFullSet())
774 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
775
776 APInt Spread_X = getSetSize(), Spread_Y = Other.getSetSize();
Nick Lewycky5dc6b792011-06-22 21:13:46 +0000777 APInt NewLower = getLower() - Other.getUpper() + 1;
778 APInt NewUpper = getUpper() - Other.getLower();
Nick Lewyckyd385c222010-08-11 22:04:36 +0000779 if (NewLower == NewUpper)
780 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
781
782 ConstantRange X = ConstantRange(NewLower, NewUpper);
783 if (X.getSetSize().ult(Spread_X) || X.getSetSize().ult(Spread_Y))
784 // We've wrapped, therefore, full set.
785 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
786
787 return X;
788}
789
790ConstantRange
Dan Gohman5035fbf2009-07-09 22:07:27 +0000791ConstantRange::multiply(const ConstantRange &Other) const {
Dan Gohman3f8ed9e2010-01-26 15:56:18 +0000792 // TODO: If either operand is a single element and the multiply is known to
793 // be non-wrapping, round the result min and max value to the appropriate
794 // multiple of that element. If wrapping is possible, at least adjust the
795 // range according to the greatest power-of-two factor of the single element.
Dan Gohman5325efc2010-01-26 04:13:15 +0000796
Nick Lewycky2951c992009-07-12 02:19:05 +0000797 if (isEmptySet() || Other.isEmptySet())
798 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nuno Lopes986cc182012-07-16 20:47:16 +0000799
James Molloydcc78ec2015-03-06 15:50:47 +0000800 // Multiplication is signedness-independent. However different ranges can be
801 // obtained depending on how the input ranges are treated. These different
802 // ranges are all conservatively correct, but one might be better than the
803 // other. We calculate two ranges; one treating the inputs as unsigned
804 // and the other signed, then return the smallest of these ranges.
805
806 // Unsigned range first.
Nick Lewycky53023892009-07-13 03:27:41 +0000807 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
808 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
809 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
810 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
Nick Lewycky2951c992009-07-12 02:19:05 +0000811
Nick Lewycky53023892009-07-13 03:27:41 +0000812 ConstantRange Result_zext = ConstantRange(this_min * Other_min,
813 this_max * Other_max + 1);
James Molloydcc78ec2015-03-06 15:50:47 +0000814 ConstantRange UR = Result_zext.truncate(getBitWidth());
815
Pete Cooper34a7a942016-05-27 17:06:50 +0000816 // If the unsigned range doesn't wrap, and isn't negative then it's a range
817 // from one positive number to another which is as good as we can generate.
818 // In this case, skip the extra work of generating signed ranges which aren't
819 // going to be better than this range.
820 if (!UR.isWrappedSet() && UR.getLower().isNonNegative())
821 return UR;
822
James Molloydcc78ec2015-03-06 15:50:47 +0000823 // Now the signed range. Because we could be dealing with negative numbers
824 // here, the lower bound is the smallest of the cartesian product of the
825 // lower and upper ranges; for example:
826 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
827 // Similarly for the upper bound, swapping min for max.
828
829 this_min = getSignedMin().sext(getBitWidth() * 2);
830 this_max = getSignedMax().sext(getBitWidth() * 2);
831 Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
832 Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
833
834 auto L = {this_min * Other_min, this_min * Other_max,
835 this_max * Other_min, this_max * Other_max};
836 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
837 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
838 ConstantRange SR = Result_sext.truncate(getBitWidth());
839
840 return UR.getSetSize().ult(SR.getSetSize()) ? UR : SR;
Dan Gohman5035fbf2009-07-09 22:07:27 +0000841}
842
843ConstantRange
844ConstantRange::smax(const ConstantRange &Other) const {
Dan Gohmandc33ae22009-07-09 23:16:10 +0000845 // X smax Y is: range(smax(X_smin, Y_smin),
846 // smax(X_smax, Y_smax))
847 if (isEmptySet() || Other.isEmptySet())
848 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Dan Gohmandc33ae22009-07-09 23:16:10 +0000849 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
850 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
851 if (NewU == NewL)
852 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
853 return ConstantRange(NewL, NewU);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000854}
855
856ConstantRange
857ConstantRange::umax(const ConstantRange &Other) const {
858 // X umax Y is: range(umax(X_umin, Y_umin),
859 // umax(X_umax, Y_umax))
860 if (isEmptySet() || Other.isEmptySet())
861 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000862 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
863 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
864 if (NewU == NewL)
865 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
866 return ConstantRange(NewL, NewU);
867}
868
869ConstantRange
Philip Reamesba313122016-02-26 22:08:18 +0000870ConstantRange::smin(const ConstantRange &Other) const {
871 // X smin Y is: range(smin(X_smin, Y_smin),
872 // smin(X_smax, Y_smax))
873 if (isEmptySet() || Other.isEmptySet())
874 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
875 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
876 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
877 if (NewU == NewL)
878 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
879 return ConstantRange(NewL, NewU);
880}
881
882ConstantRange
883ConstantRange::umin(const ConstantRange &Other) const {
884 // X umin Y is: range(umin(X_umin, Y_umin),
885 // umin(X_umax, Y_umax))
886 if (isEmptySet() || Other.isEmptySet())
887 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
888 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
889 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
890 if (NewU == NewL)
891 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
892 return ConstantRange(NewL, NewU);
893}
894
895ConstantRange
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000896ConstantRange::udiv(const ConstantRange &RHS) const {
897 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax() == 0)
898 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
899 if (RHS.isFullSet())
900 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
901
902 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
903
904 APInt RHS_umin = RHS.getUnsignedMin();
905 if (RHS_umin == 0) {
906 // We want the lowest value in RHS excluding zero. Usually that would be 1
907 // except for a range in the form of [X, 1) in which case it would be X.
908 if (RHS.getUpper() == 1)
909 RHS_umin = RHS.getLower();
910 else
911 RHS_umin = APInt(getBitWidth(), 1);
912 }
913
914 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
915
916 // If the LHS is Full and the RHS is a wrapped interval containing 1 then
917 // this could occur.
918 if (Lower == Upper)
919 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
920
921 return ConstantRange(Lower, Upper);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000922}
923
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000924ConstantRange
Nick Lewyckyad48e012010-09-07 05:39:02 +0000925ConstantRange::binaryAnd(const ConstantRange &Other) const {
926 if (isEmptySet() || Other.isEmptySet())
927 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
928
929 // TODO: replace this with something less conservative
930
931 APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
932 if (umin.isAllOnesValue())
933 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
934 return ConstantRange(APInt::getNullValue(getBitWidth()), umin + 1);
935}
936
937ConstantRange
938ConstantRange::binaryOr(const ConstantRange &Other) const {
939 if (isEmptySet() || Other.isEmptySet())
940 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
941
942 // TODO: replace this with something less conservative
943
944 APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
945 if (umax.isMinValue())
946 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
947 return ConstantRange(umax, APInt::getNullValue(getBitWidth()));
948}
949
950ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000951ConstantRange::shl(const ConstantRange &Other) const {
952 if (isEmptySet() || Other.isEmptySet())
953 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000954
Nick Lewyckyd385c222010-08-11 22:04:36 +0000955 APInt min = getUnsignedMin().shl(Other.getUnsignedMin());
956 APInt max = getUnsignedMax().shl(Other.getUnsignedMax());
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000957
958 // there's no overflow!
Nuno Lopesf8fcac72009-11-12 15:10:33 +0000959 APInt Zeros(getBitWidth(), getUnsignedMax().countLeadingZeros());
Nick Lewyckyd385c222010-08-11 22:04:36 +0000960 if (Zeros.ugt(Other.getUnsignedMax()))
961 return ConstantRange(min, max + 1);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000962
963 // FIXME: implement the other tricky cases
Nick Lewyckyd385c222010-08-11 22:04:36 +0000964 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000965}
966
967ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000968ConstantRange::lshr(const ConstantRange &Other) const {
969 if (isEmptySet() || Other.isEmptySet())
970 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000971
Nick Lewyckyd385c222010-08-11 22:04:36 +0000972 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin());
973 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
974 if (min == max + 1)
975 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
976
977 return ConstantRange(min, max + 1);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000978}
979
Owen Anderson1a9078b2010-08-07 05:47:46 +0000980ConstantRange ConstantRange::inverse() const {
Nick Lewycky228f5b42012-01-03 20:33:00 +0000981 if (isFullSet())
Nick Lewyckyd385c222010-08-11 22:04:36 +0000982 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000983 if (isEmptySet())
Nick Lewyckyd385c222010-08-11 22:04:36 +0000984 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Owen Anderson1a9078b2010-08-07 05:47:46 +0000985 return ConstantRange(Upper, Lower);
986}
987
Dan Gohmandc33ae22009-07-09 23:16:10 +0000988/// print - Print out the bounds to a stream...
Chris Lattnere0bb9eb2002-09-02 00:18:22 +0000989///
Dan Gohmandc33ae22009-07-09 23:16:10 +0000990void ConstantRange::print(raw_ostream &OS) const {
Dan Gohman837ada72010-01-26 04:12:55 +0000991 if (isFullSet())
992 OS << "full-set";
993 else if (isEmptySet())
994 OS << "empty-set";
995 else
996 OS << "[" << Lower << "," << Upper << ")";
Dan Gohman5035fbf2009-07-09 22:07:27 +0000997}
998
Dan Gohmandc33ae22009-07-09 23:16:10 +0000999/// dump - Allow printing from a debugger easily...
Dan Gohman5035fbf2009-07-09 22:07:27 +00001000///
Yaron Kereneb2a2542016-01-29 20:50:44 +00001001LLVM_DUMP_METHOD void ConstantRange::dump() const {
David Greenede7b3532010-01-05 01:28:32 +00001002 print(dbgs());
Dan Gohman5035fbf2009-07-09 22:07:27 +00001003}
Peter Collingbourneecdd58f2016-10-21 19:59:26 +00001004
1005ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1006 const unsigned NumRanges = Ranges.getNumOperands() / 2;
1007 assert(NumRanges >= 1 && "Must have at least one range!");
1008 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1009
1010 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1011 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1012
1013 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1014
1015 for (unsigned i = 1; i < NumRanges; ++i) {
1016 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1017 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1018
1019 // Note: unionWith will potentially create a range that contains values not
1020 // contained in any of the original N ranges.
1021 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1022 }
1023
1024 return CR;
1025}