blob: bab83fcddf736cda27cc79ef0d1424e62a8a03a3 [file] [log] [blame]
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001//===- ConstantRange.cpp - ConstantRange implementation -------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner113f2ae2002-09-01 23:53:36 +00008//
9// Represent a range of possible values that may occur when the program is run
10// for an integral value. This keeps track of a lower and upper bound for the
11// constant, which MAY wrap around the end of the numeric range. To do this, it
12// keeps track of a [lower, upper) bound, which specifies an interval just like
13// STL iterators. When used with boolean values, the following are important
14// ranges (other integral ranges use min/max values for special range values):
15//
16// [F, F) = {} = Empty set
17// [T, F) = {T}
18// [F, T) = {F}
19// [T, T) = {F, T} = Full set
20//
21//===----------------------------------------------------------------------===//
22
Eugene Zelenkode6cce22017-06-19 22:05:08 +000023#include "llvm/ADT/APInt.h"
Nico Weber432a3882018-04-30 14:59:11 +000024#include "llvm/Config/llvm-config.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000025#include "llvm/IR/ConstantRange.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000026#include "llvm/IR/Constants.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000029#include "llvm/IR/Metadata.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000030#include "llvm/IR/Operator.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000031#include "llvm/Support/Compiler.h"
David Greenede7b3532010-01-05 01:28:32 +000032#include "llvm/Support/Debug.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000034#include "llvm/Support/raw_ostream.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000035#include <algorithm>
36#include <cassert>
37#include <cstdint>
38
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000040
Craig Topperee4f22d2017-04-29 05:08:52 +000041ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
42 : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
43 Upper(Lower) {}
Chris Lattner113f2ae2002-09-01 23:53:36 +000044
Craig Topper37df0182017-04-13 00:20:31 +000045ConstantRange::ConstantRange(APInt V)
Chandler Carruth002da5d2014-03-02 04:08:41 +000046 : Lower(std::move(V)), Upper(Lower + 1) {}
Chris Lattner113f2ae2002-09-01 23:53:36 +000047
Craig Topper37df0182017-04-13 00:20:31 +000048ConstantRange::ConstantRange(APInt L, APInt U)
Chandler Carruth002da5d2014-03-02 04:08:41 +000049 : Lower(std::move(L)), Upper(std::move(U)) {
Benjamin Kramercce97be2013-07-11 15:37:27 +000050 assert(Lower.getBitWidth() == Upper.getBitWidth() &&
Dan Gohmandc33ae22009-07-09 23:16:10 +000051 "ConstantRange with unequal bit widths");
Benjamin Kramercce97be2013-07-11 15:37:27 +000052 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
Reid Spencere1f3f192007-02-28 17:36:23 +000053 "Lower == Upper, but they aren't min or max value!");
54}
55
Sanjoy Das7182d362015-03-18 00:41:24 +000056ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
57 const ConstantRange &CR) {
Nick Lewycky5154ee02010-09-28 18:18:36 +000058 if (CR.isEmptySet())
59 return CR;
60
Nick Lewyckydcfdce92009-07-11 06:15:39 +000061 uint32_t W = CR.getBitWidth();
62 switch (Pred) {
Sanjoy Das7182d362015-03-18 00:41:24 +000063 default:
64 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000065 case CmpInst::ICMP_EQ:
66 return CR;
67 case CmpInst::ICMP_NE:
68 if (CR.isSingleElement())
69 return ConstantRange(CR.getUpper(), CR.getLower());
70 return ConstantRange(W);
71 case CmpInst::ICMP_ULT: {
72 APInt UMax(CR.getUnsignedMax());
73 if (UMax.isMinValue())
74 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +000075 return ConstantRange(APInt::getMinValue(W), std::move(UMax));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000076 }
77 case CmpInst::ICMP_SLT: {
78 APInt SMax(CR.getSignedMax());
79 if (SMax.isMinSignedValue())
80 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +000081 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000082 }
83 case CmpInst::ICMP_ULE: {
84 APInt UMax(CR.getUnsignedMax());
85 if (UMax.isMaxValue())
Nick Lewyckydcfdce92009-07-11 06:15:39 +000086 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +000087 return ConstantRange(APInt::getMinValue(W), std::move(UMax) + 1);
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000088 }
89 case CmpInst::ICMP_SLE: {
90 APInt SMax(CR.getSignedMax());
91 if (SMax.isMaxSignedValue())
92 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +000093 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax) + 1);
Sanjay Patelf8ee0e02016-06-19 17:20:27 +000094 }
95 case CmpInst::ICMP_UGT: {
96 APInt UMin(CR.getUnsignedMin());
97 if (UMin.isMaxValue())
98 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +000099 return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000100 }
101 case CmpInst::ICMP_SGT: {
102 APInt SMin(CR.getSignedMin());
103 if (SMin.isMaxSignedValue())
104 return ConstantRange(W, /* empty */ false);
Craig Topperb7920252017-04-29 06:40:47 +0000105 return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000106 }
107 case CmpInst::ICMP_UGE: {
108 APInt UMin(CR.getUnsignedMin());
109 if (UMin.isMinValue())
110 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +0000111 return ConstantRange(std::move(UMin), APInt::getNullValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000112 }
113 case CmpInst::ICMP_SGE: {
114 APInt SMin(CR.getSignedMin());
115 if (SMin.isMinSignedValue())
116 return ConstantRange(W);
Craig Topperb7920252017-04-29 06:40:47 +0000117 return ConstantRange(std::move(SMin), APInt::getSignedMinValue(W));
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000118 }
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000119 }
120}
121
Sanjoy Das7182d362015-03-18 00:41:24 +0000122ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
123 const ConstantRange &CR) {
124 // Follows from De-Morgan's laws:
125 //
126 // ~(~A union ~B) == A intersect B.
127 //
128 return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
129 .inverse();
130}
131
Balaram Makam569eaec2016-05-04 21:32:14 +0000132ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
133 const APInt &C) {
134 // Computes the exact range that is equal to both the constant ranges returned
135 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
136 // when RHS is a singleton such as an APInt and so the assert is valid.
137 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
138 // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
139 //
140 assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
141 return makeAllowedICmpRegion(Pred, C);
142}
143
Sanjoy Das590614c2016-05-19 03:53:06 +0000144bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
145 APInt &RHS) const {
146 bool Success = false;
147
148 if (isFullSet() || isEmptySet()) {
149 Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
150 RHS = APInt(getBitWidth(), 0);
151 Success = true;
Sanjoy Dasc7d32912016-10-02 20:59:05 +0000152 } else if (auto *OnlyElt = getSingleElement()) {
153 Pred = CmpInst::ICMP_EQ;
154 RHS = *OnlyElt;
155 Success = true;
156 } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
157 Pred = CmpInst::ICMP_NE;
158 RHS = *OnlyMissingElt;
159 Success = true;
Sanjoy Das590614c2016-05-19 03:53:06 +0000160 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
161 Pred =
162 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
163 RHS = getUpper();
164 Success = true;
165 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
166 Pred =
167 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
168 RHS = getLower();
169 Success = true;
170 }
171
172 assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
173 "Bad result!");
174
175 return Success;
176}
177
Sanjoy Das5079f622016-02-22 16:13:02 +0000178ConstantRange
179ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000180 const ConstantRange &Other,
181 unsigned NoWrapKind) {
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000182 using OBO = OverflowingBinaryOperator;
Sanjoy Das6ed05302015-10-22 03:12:57 +0000183
184 // Computes the intersection of CR0 and CR1. It is different from
185 // intersectWith in that the ConstantRange returned will only contain elements
186 // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or
187 // not, of both X and Y).
188 auto SubsetIntersect =
189 [](const ConstantRange &CR0, const ConstantRange &CR1) {
190 return CR0.inverse().unionWith(CR1.inverse()).inverse();
191 };
192
Simon Pilgrime0a6eb12018-06-22 10:48:02 +0000193 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
Sanjoy Das6ed05302015-10-22 03:12:57 +0000194
195 assert((NoWrapKind == OBO::NoSignedWrap ||
196 NoWrapKind == OBO::NoUnsignedWrap ||
197 NoWrapKind == (OBO::NoUnsignedWrap | OBO::NoSignedWrap)) &&
198 "NoWrapKind invalid!");
199
Sanjoy Dasf3867e62016-03-03 18:31:16 +0000200 unsigned BitWidth = Other.getBitWidth();
Joel Galensonc32b0fc2017-12-05 18:14:23 +0000201 ConstantRange Result(BitWidth);
202
203 switch (BinOp) {
204 default:
Sanjoy Das6ed05302015-10-22 03:12:57 +0000205 // Conservative answer: empty set
206 return ConstantRange(BitWidth, false);
207
Joel Galensonc32b0fc2017-12-05 18:14:23 +0000208 case Instruction::Add:
209 if (auto *C = Other.getSingleElement())
210 if (C->isNullValue())
211 // Full set: nothing signed / unsigned wraps when added to 0.
212 return ConstantRange(BitWidth);
213 if (NoWrapKind & OBO::NoUnsignedWrap)
214 Result =
215 SubsetIntersect(Result, ConstantRange(APInt::getNullValue(BitWidth),
216 -Other.getUnsignedMax()));
217 if (NoWrapKind & OBO::NoSignedWrap) {
218 const APInt &SignedMin = Other.getSignedMin();
219 const APInt &SignedMax = Other.getSignedMax();
220 if (SignedMax.isStrictlyPositive())
221 Result = SubsetIntersect(
222 Result,
223 ConstantRange(APInt::getSignedMinValue(BitWidth),
224 APInt::getSignedMinValue(BitWidth) - SignedMax));
225 if (SignedMin.isNegative())
226 Result = SubsetIntersect(
227 Result,
228 ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin,
229 APInt::getSignedMinValue(BitWidth)));
230 }
231 return Result;
Sanjoy Das6ed05302015-10-22 03:12:57 +0000232
Joel Galensonc32b0fc2017-12-05 18:14:23 +0000233 case Instruction::Sub:
234 if (auto *C = Other.getSingleElement())
235 if (C->isNullValue())
236 // Full set: nothing signed / unsigned wraps when subtracting 0.
237 return ConstantRange(BitWidth);
238 if (NoWrapKind & OBO::NoUnsignedWrap)
239 Result =
240 SubsetIntersect(Result, ConstantRange(Other.getUnsignedMax(),
241 APInt::getMinValue(BitWidth)));
242 if (NoWrapKind & OBO::NoSignedWrap) {
243 const APInt &SignedMin = Other.getSignedMin();
244 const APInt &SignedMax = Other.getSignedMax();
245 if (SignedMax.isStrictlyPositive())
246 Result = SubsetIntersect(
247 Result,
248 ConstantRange(APInt::getSignedMinValue(BitWidth) + SignedMax,
249 APInt::getSignedMinValue(BitWidth)));
250 if (SignedMin.isNegative())
251 Result = SubsetIntersect(
252 Result,
253 ConstantRange(APInt::getSignedMinValue(BitWidth),
254 APInt::getSignedMinValue(BitWidth) + SignedMin));
255 }
256 return Result;
Tim Shenb32823c2018-06-26 18:54:10 +0000257 case Instruction::Mul: {
258 if (NoWrapKind == (OBO::NoSignedWrap | OBO::NoUnsignedWrap)) {
259 return SubsetIntersect(
260 makeGuaranteedNoWrapRegion(BinOp, Other, OBO::NoSignedWrap),
261 makeGuaranteedNoWrapRegion(BinOp, Other, OBO::NoUnsignedWrap));
262 }
263
264 // Equivalent to calling makeGuaranteedNoWrapRegion() on [V, V+1).
265 const bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
266 const auto makeSingleValueRegion = [Unsigned,
267 BitWidth](APInt V) -> ConstantRange {
268 // Handle special case for 0, -1 and 1. See the last for reason why we
269 // specialize -1 and 1.
270 if (V == 0 || V.isOneValue())
271 return ConstantRange(BitWidth, true);
272
273 APInt MinValue, MaxValue;
274 if (Unsigned) {
275 MinValue = APInt::getMinValue(BitWidth);
276 MaxValue = APInt::getMaxValue(BitWidth);
277 } else {
278 MinValue = APInt::getSignedMinValue(BitWidth);
279 MaxValue = APInt::getSignedMaxValue(BitWidth);
280 }
281 // e.g. Returning [-127, 127], represented as [-127, -128).
282 if (!Unsigned && V.isAllOnesValue())
283 return ConstantRange(-MaxValue, MinValue);
284
285 APInt Lower, Upper;
286 if (!Unsigned && V.isNegative()) {
287 Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
288 Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
289 } else if (Unsigned) {
290 Lower = APIntOps::RoundingUDiv(MinValue, V, APInt::Rounding::UP);
291 Upper = APIntOps::RoundingUDiv(MaxValue, V, APInt::Rounding::DOWN);
292 } else {
293 Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
294 Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
295 }
296 if (Unsigned) {
297 Lower = Lower.zextOrSelf(BitWidth);
298 Upper = Upper.zextOrSelf(BitWidth);
299 } else {
300 Lower = Lower.sextOrSelf(BitWidth);
301 Upper = Upper.sextOrSelf(BitWidth);
302 }
303 // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
304 // Upper + 1 is guanranteed not to overflow, because |divisor| > 1. 0, -1,
305 // and 1 are already handled as special cases.
306 return ConstantRange(Lower, Upper + 1);
307 };
308
309 if (Unsigned)
310 return makeSingleValueRegion(Other.getUnsignedMax());
311
312 return SubsetIntersect(makeSingleValueRegion(Other.getSignedMin()),
313 makeSingleValueRegion(Other.getSignedMax()));
314 }
Sanjoy Das6ed05302015-10-22 03:12:57 +0000315 }
Sanjoy Das6ed05302015-10-22 03:12:57 +0000316}
317
Chris Lattner113f2ae2002-09-01 23:53:36 +0000318bool ConstantRange::isFullSet() const {
Zhou Sheng31787362007-04-26 16:42:07 +0000319 return Lower == Upper && Lower.isMaxValue();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000320}
Misha Brukmanb1c93172005-04-21 23:48:37 +0000321
Chris Lattner113f2ae2002-09-01 23:53:36 +0000322bool ConstantRange::isEmptySet() const {
Zhou Sheng31787362007-04-26 16:42:07 +0000323 return Lower == Upper && Lower.isMinValue();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000324}
325
Reid Spencer6a440332007-03-01 07:54:15 +0000326bool ConstantRange::isWrappedSet() const {
Reid Spencere1f3f192007-02-28 17:36:23 +0000327 return Lower.ugt(Upper);
Chris Lattner113f2ae2002-09-01 23:53:36 +0000328}
329
Nick Lewyckya35462d2010-09-06 23:52:49 +0000330bool ConstantRange::isSignWrappedSet() const {
331 return contains(APInt::getSignedMaxValue(getBitWidth())) &&
332 contains(APInt::getSignedMinValue(getBitWidth()));
333}
334
Reid Spencere1f3f192007-02-28 17:36:23 +0000335APInt ConstantRange::getSetSize() const {
Craig Topper8c5c6fe2017-04-29 17:59:41 +0000336 if (isFullSet())
337 return APInt::getOneBitSet(getBitWidth()+1, getBitWidth());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000338
Nuno Lopes216d5712012-07-17 15:43:59 +0000339 // This is also correct for wrapped sets.
Nuno Lopes99504c52012-07-16 18:08:12 +0000340 return (Upper - Lower).zext(getBitWidth()+1);
Chris Lattner113f2ae2002-09-01 23:53:36 +0000341}
342
Michael Zolotukhinc69955c2017-03-20 06:33:07 +0000343bool
Craig Topperd29549e2017-05-07 21:48:08 +0000344ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
Michael Zolotukhinc69955c2017-03-20 06:33:07 +0000345 assert(getBitWidth() == Other.getBitWidth());
346 if (isFullSet())
347 return false;
348 if (Other.isFullSet())
349 return true;
350 return (Upper - Lower).ult(Other.Upper - Other.Lower);
351}
352
Craig Topper7e3e7af2017-05-07 22:22:11 +0000353bool
354ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
355 assert(MaxSize && "MaxSize can't be 0.");
356 // If this a full set, we need special handling to avoid needing an extra bit
357 // to represent the size.
358 if (isFullSet())
359 return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
360
361 return (Upper - Lower).ugt(MaxSize);
362}
363
Nick Lewyckye4559372007-03-10 15:54:12 +0000364APInt ConstantRange::getUnsignedMax() const {
365 if (isFullSet() || isWrappedSet())
366 return APInt::getMaxValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000367 return getUpper() - 1;
Nick Lewyckye4559372007-03-10 15:54:12 +0000368}
369
Nick Lewyckye4559372007-03-10 15:54:12 +0000370APInt ConstantRange::getUnsignedMin() const {
Craig Topper61729fd2017-05-09 05:01:29 +0000371 if (isFullSet() || (isWrappedSet() && !getUpper().isNullValue()))
Nick Lewyckye4559372007-03-10 15:54:12 +0000372 return APInt::getMinValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000373 return getLower();
Nick Lewyckye4559372007-03-10 15:54:12 +0000374}
375
Nick Lewyckye4559372007-03-10 15:54:12 +0000376APInt ConstantRange::getSignedMax() const {
Craig Topper61e684a2017-06-16 23:26:23 +0000377 if (isFullSet() || Lower.sgt(Upper))
Craig Topper88c64f32017-04-18 23:02:39 +0000378 return APInt::getSignedMaxValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000379 return getUpper() - 1;
Nick Lewyckye4559372007-03-10 15:54:12 +0000380}
381
Nick Lewyckye4559372007-03-10 15:54:12 +0000382APInt ConstantRange::getSignedMin() const {
Craig Topper61e684a2017-06-16 23:26:23 +0000383 if (isFullSet() || (Lower.sgt(Upper) && !getUpper().isMinSignedValue()))
Craig Topper88c64f32017-04-18 23:02:39 +0000384 return APInt::getSignedMinValue(getBitWidth());
Nick Lewycky228f5b42012-01-03 20:33:00 +0000385 return getLower();
Nick Lewyckye4559372007-03-10 15:54:12 +0000386}
387
Reid Spencer6a440332007-03-01 07:54:15 +0000388bool ConstantRange::contains(const APInt &V) const {
389 if (Lower == Upper)
390 return isFullSet();
Chris Lattner113f2ae2002-09-01 23:53:36 +0000391
Reid Spencer6a440332007-03-01 07:54:15 +0000392 if (!isWrappedSet())
393 return Lower.ule(V) && V.ult(Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000394 return Lower.ule(V) || V.ult(Upper);
Chris Lattner55481f72004-03-30 00:20:08 +0000395}
396
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000397bool ConstantRange::contains(const ConstantRange &Other) const {
Nick Lewyckyd385c222010-08-11 22:04:36 +0000398 if (isFullSet() || Other.isEmptySet()) return true;
399 if (isEmptySet() || Other.isFullSet()) return false;
Nick Lewyckydcfdce92009-07-11 06:15:39 +0000400
401 if (!isWrappedSet()) {
402 if (Other.isWrappedSet())
403 return false;
404
405 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
406 }
407
408 if (!Other.isWrappedSet())
409 return Other.getUpper().ule(Upper) ||
410 Lower.ule(Other.getLower());
411
412 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
413}
414
Reid Spencer3a7e9d82007-02-28 19:57:34 +0000415ConstantRange ConstantRange::subtract(const APInt &Val) const {
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000416 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
Chris Lattner55481f72004-03-30 00:20:08 +0000417 // If the set is empty or full, don't modify the endpoints.
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000418 if (Lower == Upper)
Reid Spencere1f3f192007-02-28 17:36:23 +0000419 return *this;
Reid Spencere1f3f192007-02-28 17:36:23 +0000420 return ConstantRange(Lower - Val, Upper - Val);
Chris Lattner55481f72004-03-30 00:20:08 +0000421}
Chris Lattner113f2ae2002-09-01 23:53:36 +0000422
Nuno Lopes5020db22012-06-28 16:10:13 +0000423ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
424 return intersectWith(CR.inverse());
425}
426
Reid Spencer6a440332007-03-01 07:54:15 +0000427ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000428 assert(getBitWidth() == CR.getBitWidth() &&
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000429 "ConstantRange types don't agree!");
Nick Lewycky61b4a262007-07-14 02:51:34 +0000430
431 // Handle common cases.
432 if ( isEmptySet() || CR.isFullSet()) return *this;
433 if (CR.isEmptySet() || isFullSet()) return CR;
434
435 if (!isWrappedSet() && CR.isWrappedSet())
Nick Lewycky0d139032009-07-18 06:34:42 +0000436 return CR.intersectWith(*this);
Nick Lewycky61b4a262007-07-14 02:51:34 +0000437
438 if (!isWrappedSet() && !CR.isWrappedSet()) {
439 if (Lower.ult(CR.Lower)) {
440 if (Upper.ule(CR.Lower))
441 return ConstantRange(getBitWidth(), false);
442
443 if (Upper.ult(CR.Upper))
444 return ConstantRange(CR.Lower, Upper);
445
446 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000447 }
Nick Lewycky228f5b42012-01-03 20:33:00 +0000448 if (Upper.ult(CR.Upper))
449 return *this;
450
451 if (Lower.ult(CR.Upper))
452 return ConstantRange(Lower, CR.Upper);
453
454 return ConstantRange(getBitWidth(), false);
Nick Lewycky61b4a262007-07-14 02:51:34 +0000455 }
456
457 if (isWrappedSet() && !CR.isWrappedSet()) {
458 if (CR.Lower.ult(Upper)) {
459 if (CR.Upper.ult(Upper))
460 return CR;
461
Nuno Lopes63afc082012-05-18 00:14:36 +0000462 if (CR.Upper.ule(Lower))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000463 return ConstantRange(CR.Lower, Upper);
464
Craig Topperd29549e2017-05-07 21:48:08 +0000465 if (isSizeStrictlySmallerThan(CR))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000466 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000467 return CR;
468 }
469 if (CR.Lower.ult(Lower)) {
Nick Lewycky61b4a262007-07-14 02:51:34 +0000470 if (CR.Upper.ule(Lower))
471 return ConstantRange(getBitWidth(), false);
472
473 return ConstantRange(Lower, CR.Upper);
474 }
475 return CR;
476 }
477
478 if (CR.Upper.ult(Upper)) {
479 if (CR.Lower.ult(Upper)) {
Craig Topperd29549e2017-05-07 21:48:08 +0000480 if (isSizeStrictlySmallerThan(CR))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000481 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000482 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000483 }
484
485 if (CR.Lower.ult(Lower))
486 return ConstantRange(Lower, CR.Upper);
487
488 return CR;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000489 }
Nuno Lopesebb0c942012-06-28 00:59:33 +0000490 if (CR.Upper.ule(Lower)) {
Nick Lewycky61b4a262007-07-14 02:51:34 +0000491 if (CR.Lower.ult(Lower))
492 return *this;
493
494 return ConstantRange(CR.Lower, Upper);
495 }
Craig Topperd29549e2017-05-07 21:48:08 +0000496 if (isSizeStrictlySmallerThan(CR))
Nick Lewycky61b4a262007-07-14 02:51:34 +0000497 return *this;
Nick Lewycky228f5b42012-01-03 20:33:00 +0000498 return CR;
Nick Lewycky61b4a262007-07-14 02:51:34 +0000499}
500
Reid Spencer6a440332007-03-01 07:54:15 +0000501ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000502 assert(getBitWidth() == CR.getBitWidth() &&
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000503 "ConstantRange types don't agree!");
Chris Lattner113f2ae2002-09-01 23:53:36 +0000504
Nick Lewyckycf87f9e2007-03-02 03:33:05 +0000505 if ( isFullSet() || CR.isEmptySet()) return *this;
506 if (CR.isFullSet() || isEmptySet()) return CR;
Chris Lattner113f2ae2002-09-01 23:53:36 +0000507
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000508 if (!isWrappedSet() && CR.isWrappedSet()) return CR.unionWith(*this);
509
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000510 if (!isWrappedSet() && !CR.isWrappedSet()) {
Nick Lewycky567daf32009-07-19 03:44:35 +0000511 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) {
512 // If the two ranges are disjoint, find the smaller gap and bridge it.
513 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
514 if (d1.ult(d2))
515 return ConstantRange(Lower, CR.Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000516 return ConstantRange(CR.Lower, Upper);
Nick Lewycky567daf32009-07-19 03:44:35 +0000517 }
518
Craig Topper8fb5a142017-04-29 07:24:13 +0000519 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
520 APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
Nick Lewycky567daf32009-07-19 03:44:35 +0000521
Craig Topper61729fd2017-05-09 05:01:29 +0000522 if (L.isNullValue() && U.isNullValue())
Nick Lewycky567daf32009-07-19 03:44:35 +0000523 return ConstantRange(getBitWidth());
524
Craig Topperb7920252017-04-29 06:40:47 +0000525 return ConstantRange(std::move(L), std::move(U));
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000526 }
527
Nick Lewycky567daf32009-07-19 03:44:35 +0000528 if (!CR.isWrappedSet()) {
529 // ------U L----- and ------U L----- : this
530 // L--U L--U : CR
531 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000532 return *this;
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000533
Nick Lewycky567daf32009-07-19 03:44:35 +0000534 // ------U L----- : this
535 // L---------U : CR
536 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000537 return ConstantRange(getBitWidth());
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000538
Nick Lewycky567daf32009-07-19 03:44:35 +0000539 // ----U L---- : this
540 // L---U : CR
541 // <d1> <d2>
542 if (Upper.ule(CR.Lower) && CR.Upper.ule(Lower)) {
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000543 APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
Nick Lewycky567daf32009-07-19 03:44:35 +0000544 if (d1.ult(d2))
545 return ConstantRange(Lower, CR.Upper);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000546 return ConstantRange(CR.Lower, Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000547 }
548
Nick Lewycky567daf32009-07-19 03:44:35 +0000549 // ----U L----- : this
550 // L----U : CR
551 if (Upper.ult(CR.Lower) && Lower.ult(CR.Upper))
552 return ConstantRange(CR.Lower, Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000553
Nick Lewycky567daf32009-07-19 03:44:35 +0000554 // ------U L---- : this
555 // L-----U : CR
Nick Lewycky228f5b42012-01-03 20:33:00 +0000556 assert(CR.Lower.ult(Upper) && CR.Upper.ult(Lower) &&
557 "ConstantRange::unionWith missed a case with one range wrapped");
558 return ConstantRange(Lower, CR.Upper);
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000559 }
560
Nick Lewycky567daf32009-07-19 03:44:35 +0000561 // ------U L---- and ------U L---- : this
562 // -U L----------- and ------------U L : CR
563 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
564 return ConstantRange(getBitWidth());
Nick Lewyckyf22938a2007-04-01 03:47:44 +0000565
Craig Topper8fb5a142017-04-29 07:24:13 +0000566 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
567 APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
Nick Lewyckycf87f9e2007-03-02 03:33:05 +0000568
Craig Topperb7920252017-04-29 06:40:47 +0000569 return ConstantRange(std::move(L), std::move(U));
Chris Lattner113f2ae2002-09-01 23:53:36 +0000570}
Chris Lattnere0bb9eb2002-09-02 00:18:22 +0000571
Philip Reames4d00af12016-12-01 20:08:47 +0000572ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
573 uint32_t ResultBitWidth) const {
574 switch (CastOp) {
575 default:
576 llvm_unreachable("unsupported cast type");
577 case Instruction::Trunc:
578 return truncate(ResultBitWidth);
579 case Instruction::SExt:
580 return signExtend(ResultBitWidth);
581 case Instruction::ZExt:
582 return zeroExtend(ResultBitWidth);
583 case Instruction::BitCast:
584 return *this;
585 case Instruction::FPToUI:
586 case Instruction::FPToSI:
587 if (getBitWidth() == ResultBitWidth)
588 return *this;
589 else
590 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
591 case Instruction::UIToFP: {
592 // TODO: use input range if available
593 auto BW = getBitWidth();
594 APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
595 APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
Craig Topperb7920252017-04-29 06:40:47 +0000596 return ConstantRange(std::move(Min), std::move(Max));
Philip Reames4d00af12016-12-01 20:08:47 +0000597 }
598 case Instruction::SIToFP: {
599 // TODO: use input range if available
600 auto BW = getBitWidth();
601 APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
602 APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
Craig Topperb7920252017-04-29 06:40:47 +0000603 return ConstantRange(std::move(SMin), std::move(SMax));
Philip Reames4d00af12016-12-01 20:08:47 +0000604 }
605 case Instruction::FPTrunc:
606 case Instruction::FPExt:
607 case Instruction::IntToPtr:
608 case Instruction::PtrToInt:
609 case Instruction::AddrSpaceCast:
610 // Conservatively return full set.
611 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
612 };
613}
614
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000615ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000616 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
617
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000618 unsigned SrcTySize = getBitWidth();
Reid Spencere1f3f192007-02-28 17:36:23 +0000619 assert(SrcTySize < DstTySize && "Not a value extension");
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000620 if (isFullSet() || isWrappedSet()) {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000621 // Change into [0, 1 << src bit width)
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000622 APInt LowerExt(DstTySize, 0);
623 if (!Upper) // special case: [X, 0) -- not really wrapping around
624 LowerExt = Lower.zext(DstTySize);
Craig Topperb7920252017-04-29 06:40:47 +0000625 return ConstantRange(std::move(LowerExt),
626 APInt::getOneBitSet(DstTySize, SrcTySize));
Nuno Lopeseb9d2752012-07-23 20:33:29 +0000627 }
Chris Lattner55481f72004-03-30 00:20:08 +0000628
Jay Foad583abbc2010-12-07 08:25:19 +0000629 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
Chris Lattner55481f72004-03-30 00:20:08 +0000630}
631
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000632ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
Nick Lewyckya35462d2010-09-06 23:52:49 +0000633 if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
634
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000635 unsigned SrcTySize = getBitWidth();
636 assert(SrcTySize < DstTySize && "Not a value extension");
Nuno Lopes1112eca2013-10-30 15:36:50 +0000637
638 // special case: [X, INT_MIN) -- not really wrapping around
Nuno Lopes14d4b0c2013-10-31 19:53:53 +0000639 if (Upper.isMinSignedValue())
Nuno Lopes1112eca2013-10-30 15:36:50 +0000640 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
641
Nick Lewyckya35462d2010-09-06 23:52:49 +0000642 if (isFullSet() || isSignWrappedSet()) {
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000643 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
Nick Lewycky5edc4592009-07-13 04:17:23 +0000644 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000645 }
646
Jay Foad583abbc2010-12-07 08:25:19 +0000647 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
Nick Lewyckyb89804f2007-04-07 15:41:33 +0000648}
649
Reid Spencer9b3d6ec2007-02-28 22:02:48 +0000650ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
Benjamin Kramer6709e052011-11-24 17:24:33 +0000651 assert(getBitWidth() > DstTySize && "Not a value truncation");
Nuno Lopesc14776d2012-07-19 16:27:45 +0000652 if (isEmptySet())
653 return ConstantRange(DstTySize, /*isFullSet=*/false);
654 if (isFullSet())
Nick Lewyckyd385c222010-08-11 22:04:36 +0000655 return ConstantRange(DstTySize, /*isFullSet=*/true);
Chris Lattner55481f72004-03-30 00:20:08 +0000656
Nuno Lopesc14776d2012-07-19 16:27:45 +0000657 APInt LowerDiv(Lower), UpperDiv(Upper);
658 ConstantRange Union(DstTySize, /*isFullSet=*/false);
659
660 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
661 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
662 // then we do the union with [MaxValue, Upper)
663 if (isWrappedSet()) {
Craig Topperf6e138d2017-06-05 20:48:05 +0000664 // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
665 // truncated range.
666 if (Upper.getActiveBits() > DstTySize ||
667 Upper.countTrailingOnes() == DstTySize)
Nuno Lopesc14776d2012-07-19 16:27:45 +0000668 return ConstantRange(DstTySize, /*isFullSet=*/true);
669
670 Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
Craig Topper86616532017-04-30 00:44:05 +0000671 UpperDiv.setAllBits();
Nuno Lopesc14776d2012-07-19 16:27:45 +0000672
673 // Union covers the MaxValue case, so return if the remaining range is just
Craig Topperf6e138d2017-06-05 20:48:05 +0000674 // MaxValue(DstTy).
Nuno Lopesc14776d2012-07-19 16:27:45 +0000675 if (LowerDiv == UpperDiv)
676 return Union;
677 }
678
679 // Chop off the most significant bits that are past the destination bitwidth.
Craig Topperf6e138d2017-06-05 20:48:05 +0000680 if (LowerDiv.getActiveBits() > DstTySize) {
681 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
682 APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
683 LowerDiv -= Adjust;
684 UpperDiv -= Adjust;
Nuno Lopesc14776d2012-07-19 16:27:45 +0000685 }
686
Craig Topperf6e138d2017-06-05 20:48:05 +0000687 unsigned UpperDivWidth = UpperDiv.getActiveBits();
688 if (UpperDivWidth <= DstTySize)
Nuno Lopesc14776d2012-07-19 16:27:45 +0000689 return ConstantRange(LowerDiv.trunc(DstTySize),
690 UpperDiv.trunc(DstTySize)).unionWith(Union);
691
Nick Lewyckybfad0152016-06-06 01:51:23 +0000692 // The truncated value wraps around. Check if we can do better than fullset.
Craig Topperf6e138d2017-06-05 20:48:05 +0000693 if (UpperDivWidth == DstTySize + 1) {
694 // Clear the MSB so that UpperDiv wraps around.
695 UpperDiv.clearBit(DstTySize);
696 if (UpperDiv.ult(LowerDiv))
697 return ConstantRange(LowerDiv.trunc(DstTySize),
698 UpperDiv.trunc(DstTySize)).unionWith(Union);
699 }
Nuno Lopesc14776d2012-07-19 16:27:45 +0000700
701 return ConstantRange(DstTySize, /*isFullSet=*/true);
Chris Lattner55481f72004-03-30 00:20:08 +0000702}
703
Nuno Lopes640eb702009-11-09 15:36:28 +0000704ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
705 unsigned SrcTySize = getBitWidth();
706 if (SrcTySize > DstTySize)
707 return truncate(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000708 if (SrcTySize < DstTySize)
Nuno Lopes640eb702009-11-09 15:36:28 +0000709 return zeroExtend(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000710 return *this;
Nuno Lopes640eb702009-11-09 15:36:28 +0000711}
712
Nuno Lopes640eb702009-11-09 15:36:28 +0000713ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
714 unsigned SrcTySize = getBitWidth();
715 if (SrcTySize > DstTySize)
716 return truncate(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000717 if (SrcTySize < DstTySize)
Nuno Lopes640eb702009-11-09 15:36:28 +0000718 return signExtend(DstTySize);
Nick Lewycky228f5b42012-01-03 20:33:00 +0000719 return *this;
Nuno Lopes640eb702009-11-09 15:36:28 +0000720}
721
Philip Reames4d00af12016-12-01 20:08:47 +0000722ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
723 const ConstantRange &Other) const {
Simon Pilgrime0a6eb12018-06-22 10:48:02 +0000724 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
Philip Reames4d00af12016-12-01 20:08:47 +0000725
726 switch (BinOp) {
727 case Instruction::Add:
728 return add(Other);
729 case Instruction::Sub:
730 return sub(Other);
731 case Instruction::Mul:
732 return multiply(Other);
733 case Instruction::UDiv:
734 return udiv(Other);
735 case Instruction::Shl:
736 return shl(Other);
737 case Instruction::LShr:
738 return lshr(Other);
Max Kazantsevd7921712017-12-18 13:01:32 +0000739 case Instruction::AShr:
740 return ashr(Other);
Philip Reames4d00af12016-12-01 20:08:47 +0000741 case Instruction::And:
742 return binaryAnd(Other);
743 case Instruction::Or:
744 return binaryOr(Other);
745 // Note: floating point operations applied to abstract ranges are just
746 // ideal integer operations with a lossy representation
747 case Instruction::FAdd:
748 return add(Other);
749 case Instruction::FSub:
750 return sub(Other);
751 case Instruction::FMul:
752 return multiply(Other);
753 default:
754 // Conservatively return full set.
755 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
756 }
757}
758
Dan Gohman5035fbf2009-07-09 22:07:27 +0000759ConstantRange
760ConstantRange::add(const ConstantRange &Other) const {
761 if (isEmptySet() || Other.isEmptySet())
762 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nick Lewycky73b704d2009-07-13 02:49:08 +0000763 if (isFullSet() || Other.isFullSet())
764 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000765
Dan Gohman5035fbf2009-07-09 22:07:27 +0000766 APInt NewLower = getLower() + Other.getLower();
767 APInt NewUpper = getUpper() + Other.getUpper() - 1;
768 if (NewLower == NewUpper)
769 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
770
Craig Topperb7920252017-04-29 06:40:47 +0000771 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
Craig Topperd29549e2017-05-07 21:48:08 +0000772 if (X.isSizeStrictlySmallerThan(*this) ||
773 X.isSizeStrictlySmallerThan(Other))
Dan Gohman5035fbf2009-07-09 22:07:27 +0000774 // We've wrapped, therefore, full set.
775 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000776 return X;
Chris Lattnere0bb9eb2002-09-02 00:18:22 +0000777}
778
Artur Pilipenkoed841032016-10-19 14:44:23 +0000779ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
780 // Calculate the subset of this range such that "X + Other" is
781 // guaranteed not to wrap (overflow) for all X in this subset.
782 // makeGuaranteedNoWrapRegion will produce an exact NSW range since we are
783 // passing a single element range.
784 auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(BinaryOperator::Add,
785 ConstantRange(Other),
786 OverflowingBinaryOperator::NoSignedWrap);
787 auto NSWConstrainedRange = intersectWith(NSWRange);
788
789 return NSWConstrainedRange.add(ConstantRange(Other));
790}
791
Dan Gohman5035fbf2009-07-09 22:07:27 +0000792ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000793ConstantRange::sub(const ConstantRange &Other) const {
794 if (isEmptySet() || Other.isEmptySet())
795 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
796 if (isFullSet() || Other.isFullSet())
797 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
798
Nick Lewycky5dc6b792011-06-22 21:13:46 +0000799 APInt NewLower = getLower() - Other.getUpper() + 1;
800 APInt NewUpper = getUpper() - Other.getLower();
Nick Lewyckyd385c222010-08-11 22:04:36 +0000801 if (NewLower == NewUpper)
802 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
803
Craig Topperb7920252017-04-29 06:40:47 +0000804 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
Craig Topperd29549e2017-05-07 21:48:08 +0000805 if (X.isSizeStrictlySmallerThan(*this) ||
806 X.isSizeStrictlySmallerThan(Other))
Nick Lewyckyd385c222010-08-11 22:04:36 +0000807 // We've wrapped, therefore, full set.
808 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Nick Lewyckyd385c222010-08-11 22:04:36 +0000809 return X;
810}
811
812ConstantRange
Dan Gohman5035fbf2009-07-09 22:07:27 +0000813ConstantRange::multiply(const ConstantRange &Other) const {
Dan Gohman3f8ed9e2010-01-26 15:56:18 +0000814 // TODO: If either operand is a single element and the multiply is known to
815 // be non-wrapping, round the result min and max value to the appropriate
816 // multiple of that element. If wrapping is possible, at least adjust the
817 // range according to the greatest power-of-two factor of the single element.
Dan Gohman5325efc2010-01-26 04:13:15 +0000818
Nick Lewycky2951c992009-07-12 02:19:05 +0000819 if (isEmptySet() || Other.isEmptySet())
820 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nuno Lopes986cc182012-07-16 20:47:16 +0000821
James Molloydcc78ec2015-03-06 15:50:47 +0000822 // Multiplication is signedness-independent. However different ranges can be
823 // obtained depending on how the input ranges are treated. These different
824 // ranges are all conservatively correct, but one might be better than the
825 // other. We calculate two ranges; one treating the inputs as unsigned
826 // and the other signed, then return the smallest of these ranges.
827
828 // Unsigned range first.
Nick Lewycky53023892009-07-13 03:27:41 +0000829 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
830 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
831 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
832 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
Nick Lewycky2951c992009-07-12 02:19:05 +0000833
Nick Lewycky53023892009-07-13 03:27:41 +0000834 ConstantRange Result_zext = ConstantRange(this_min * Other_min,
835 this_max * Other_max + 1);
James Molloydcc78ec2015-03-06 15:50:47 +0000836 ConstantRange UR = Result_zext.truncate(getBitWidth());
837
Pete Cooper34a7a942016-05-27 17:06:50 +0000838 // If the unsigned range doesn't wrap, and isn't negative then it's a range
839 // from one positive number to another which is as good as we can generate.
840 // In this case, skip the extra work of generating signed ranges which aren't
841 // going to be better than this range.
Craig Topperc51d0532017-05-10 20:01:48 +0000842 if (!UR.isWrappedSet() &&
843 (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
Pete Cooper34a7a942016-05-27 17:06:50 +0000844 return UR;
845
James Molloydcc78ec2015-03-06 15:50:47 +0000846 // Now the signed range. Because we could be dealing with negative numbers
847 // here, the lower bound is the smallest of the cartesian product of the
848 // lower and upper ranges; for example:
849 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
850 // Similarly for the upper bound, swapping min for max.
851
852 this_min = getSignedMin().sext(getBitWidth() * 2);
853 this_max = getSignedMax().sext(getBitWidth() * 2);
854 Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
855 Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000856
James Molloydcc78ec2015-03-06 15:50:47 +0000857 auto L = {this_min * Other_min, this_min * Other_max,
858 this_max * Other_min, this_max * Other_max};
859 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
860 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
861 ConstantRange SR = Result_sext.truncate(getBitWidth());
862
Craig Topperd29549e2017-05-07 21:48:08 +0000863 return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
Dan Gohman5035fbf2009-07-09 22:07:27 +0000864}
865
866ConstantRange
867ConstantRange::smax(const ConstantRange &Other) const {
Dan Gohmandc33ae22009-07-09 23:16:10 +0000868 // X smax Y is: range(smax(X_smin, Y_smin),
869 // smax(X_smax, Y_smax))
870 if (isEmptySet() || Other.isEmptySet())
871 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Dan Gohmandc33ae22009-07-09 23:16:10 +0000872 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
873 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
874 if (NewU == NewL)
875 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000876 return ConstantRange(std::move(NewL), std::move(NewU));
Dan Gohman5035fbf2009-07-09 22:07:27 +0000877}
878
879ConstantRange
880ConstantRange::umax(const ConstantRange &Other) const {
881 // X umax Y is: range(umax(X_umin, Y_umin),
882 // umax(X_umax, Y_umax))
883 if (isEmptySet() || Other.isEmptySet())
884 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Dan Gohman5035fbf2009-07-09 22:07:27 +0000885 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
886 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
887 if (NewU == NewL)
888 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000889 return ConstantRange(std::move(NewL), std::move(NewU));
Dan Gohman5035fbf2009-07-09 22:07:27 +0000890}
891
892ConstantRange
Philip Reamesba313122016-02-26 22:08:18 +0000893ConstantRange::smin(const ConstantRange &Other) const {
894 // X smin Y is: range(smin(X_smin, Y_smin),
895 // smin(X_smax, Y_smax))
896 if (isEmptySet() || Other.isEmptySet())
897 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
898 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
899 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
900 if (NewU == NewL)
901 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000902 return ConstantRange(std::move(NewL), std::move(NewU));
Philip Reamesba313122016-02-26 22:08:18 +0000903}
904
905ConstantRange
906ConstantRange::umin(const ConstantRange &Other) const {
907 // X umin Y is: range(umin(X_umin, Y_umin),
908 // umin(X_umax, Y_umax))
909 if (isEmptySet() || Other.isEmptySet())
910 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
911 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
912 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
913 if (NewU == NewL)
914 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000915 return ConstantRange(std::move(NewL), std::move(NewU));
Philip Reamesba313122016-02-26 22:08:18 +0000916}
917
918ConstantRange
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000919ConstantRange::udiv(const ConstantRange &RHS) const {
Craig Topper61729fd2017-05-09 05:01:29 +0000920 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000921 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
922 if (RHS.isFullSet())
923 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
924
925 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
926
927 APInt RHS_umin = RHS.getUnsignedMin();
Craig Topper61729fd2017-05-09 05:01:29 +0000928 if (RHS_umin.isNullValue()) {
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000929 // We want the lowest value in RHS excluding zero. Usually that would be 1
930 // except for a range in the form of [X, 1) in which case it would be X.
931 if (RHS.getUpper() == 1)
932 RHS_umin = RHS.getLower();
933 else
Craig Topper86616532017-04-30 00:44:05 +0000934 RHS_umin = 1;
Nick Lewyckyf1b8cb32009-07-12 05:18:18 +0000935 }
936
937 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
938
939 // If the LHS is Full and the RHS is a wrapped interval containing 1 then
940 // this could occur.
941 if (Lower == Upper)
942 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
943
Craig Topperb7920252017-04-29 06:40:47 +0000944 return ConstantRange(std::move(Lower), std::move(Upper));
Dan Gohman5035fbf2009-07-09 22:07:27 +0000945}
946
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000947ConstantRange
Nick Lewyckyad48e012010-09-07 05:39:02 +0000948ConstantRange::binaryAnd(const ConstantRange &Other) const {
949 if (isEmptySet() || Other.isEmptySet())
950 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
951
952 // TODO: replace this with something less conservative
953
954 APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
955 if (umin.isAllOnesValue())
956 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000957 return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
Nick Lewyckyad48e012010-09-07 05:39:02 +0000958}
959
960ConstantRange
961ConstantRange::binaryOr(const ConstantRange &Other) const {
962 if (isEmptySet() || Other.isEmptySet())
963 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
964
965 // TODO: replace this with something less conservative
966
967 APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
Craig Toppere8dea1b2017-04-28 21:48:09 +0000968 if (umax.isNullValue())
Nick Lewyckyad48e012010-09-07 05:39:02 +0000969 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Craig Topperb7920252017-04-29 06:40:47 +0000970 return ConstantRange(std::move(umax), APInt::getNullValue(getBitWidth()));
Nick Lewyckyad48e012010-09-07 05:39:02 +0000971}
972
973ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000974ConstantRange::shl(const ConstantRange &Other) const {
975 if (isEmptySet() || Other.isEmptySet())
976 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000977
Craig Topperef028032017-05-09 07:04:04 +0000978 APInt max = getUnsignedMax();
979 APInt Other_umax = Other.getUnsignedMax();
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000980
Craig Topperef028032017-05-09 07:04:04 +0000981 // there's overflow!
982 if (Other_umax.uge(max.countLeadingZeros()))
983 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000984
985 // FIXME: implement the other tricky cases
Craig Topperef028032017-05-09 07:04:04 +0000986
987 APInt min = getUnsignedMin();
988 min <<= Other.getUnsignedMin();
989 max <<= Other_umax;
990
991 return ConstantRange(std::move(min), std::move(max) + 1);
Nuno Lopes60d5b1c2009-11-12 14:53:53 +0000992}
993
994ConstantRange
Nick Lewyckyd385c222010-08-11 22:04:36 +0000995ConstantRange::lshr(const ConstantRange &Other) const {
996 if (isEmptySet() || Other.isEmptySet())
997 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Craig Topper79b76662017-05-09 07:04:02 +0000998
999 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
Nick Lewyckyd385c222010-08-11 22:04:36 +00001000 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
Craig Topper79b76662017-05-09 07:04:02 +00001001 if (min == max)
Nick Lewyckyd385c222010-08-11 22:04:36 +00001002 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
1003
Craig Topper79b76662017-05-09 07:04:02 +00001004 return ConstantRange(std::move(min), std::move(max));
Nuno Lopes60d5b1c2009-11-12 14:53:53 +00001005}
1006
Max Kazantsevd7921712017-12-18 13:01:32 +00001007ConstantRange
1008ConstantRange::ashr(const ConstantRange &Other) const {
1009 if (isEmptySet() || Other.isEmptySet())
1010 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
1011
1012 // May straddle zero, so handle both positive and negative cases.
1013 // 'PosMax' is the upper bound of the result of the ashr
1014 // operation, when Upper of the LHS of ashr is a non-negative.
1015 // number. Since ashr of a non-negative number will result in a
1016 // smaller number, the Upper value of LHS is shifted right with
1017 // the minimum value of 'Other' instead of the maximum value.
1018 APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1019
1020 // 'PosMin' is the lower bound of the result of the ashr
1021 // operation, when Lower of the LHS is a non-negative number.
1022 // Since ashr of a non-negative number will result in a smaller
1023 // number, the Lower value of LHS is shifted right with the
1024 // maximum value of 'Other'.
1025 APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1026
1027 // 'NegMax' is the upper bound of the result of the ashr
1028 // operation, when Upper of the LHS of ashr is a negative number.
1029 // Since 'ashr' of a negative number will result in a bigger
1030 // number, the Upper value of LHS is shifted right with the
1031 // maximum value of 'Other'.
1032 APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1033
1034 // 'NegMin' is the lower bound of the result of the ashr
1035 // operation, when Lower of the LHS of ashr is a negative number.
1036 // Since 'ashr' of a negative number will result in a bigger
1037 // number, the Lower value of LHS is shifted right with the
1038 // minimum value of 'Other'.
1039 APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1040
1041 APInt max, min;
1042 if (getSignedMin().isNonNegative()) {
1043 // Upper and Lower of LHS are non-negative.
1044 min = PosMin;
1045 max = PosMax;
1046 } else if (getSignedMax().isNegative()) {
1047 // Upper and Lower of LHS are negative.
1048 min = NegMin;
1049 max = NegMax;
1050 } else {
1051 // Upper is non-negative and Lower is negative.
1052 min = NegMin;
1053 max = PosMax;
1054 }
1055 if (min == max)
1056 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
1057
1058 return ConstantRange(std::move(min), std::move(max));
1059}
1060
Owen Anderson1a9078b2010-08-07 05:47:46 +00001061ConstantRange ConstantRange::inverse() const {
Nick Lewycky228f5b42012-01-03 20:33:00 +00001062 if (isFullSet())
Nick Lewyckyd385c222010-08-11 22:04:36 +00001063 return ConstantRange(getBitWidth(), /*isFullSet=*/false);
Nick Lewycky228f5b42012-01-03 20:33:00 +00001064 if (isEmptySet())
Nick Lewyckyd385c222010-08-11 22:04:36 +00001065 return ConstantRange(getBitWidth(), /*isFullSet=*/true);
Owen Anderson1a9078b2010-08-07 05:47:46 +00001066 return ConstantRange(Upper, Lower);
1067}
1068
Dan Gohmandc33ae22009-07-09 23:16:10 +00001069void ConstantRange::print(raw_ostream &OS) const {
Dan Gohman837ada72010-01-26 04:12:55 +00001070 if (isFullSet())
1071 OS << "full-set";
1072 else if (isEmptySet())
1073 OS << "empty-set";
1074 else
1075 OS << "[" << Lower << "," << Upper << ")";
Dan Gohman5035fbf2009-07-09 22:07:27 +00001076}
1077
Aaron Ballman615eb472017-10-15 14:32:27 +00001078#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00001079LLVM_DUMP_METHOD void ConstantRange::dump() const {
David Greenede7b3532010-01-05 01:28:32 +00001080 print(dbgs());
Dan Gohman5035fbf2009-07-09 22:07:27 +00001081}
Matthias Braun8c209aa2017-01-28 02:02:38 +00001082#endif
Peter Collingbourneecdd58f2016-10-21 19:59:26 +00001083
1084ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1085 const unsigned NumRanges = Ranges.getNumOperands() / 2;
1086 assert(NumRanges >= 1 && "Must have at least one range!");
1087 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1088
1089 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1090 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1091
1092 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1093
1094 for (unsigned i = 1; i < NumRanges; ++i) {
1095 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1096 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1097
1098 // Note: unionWith will potentially create a range that contains values not
1099 // contained in any of the original N ranges.
1100 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1101 }
1102
1103 return CR;
1104}