1//===- ConstantRange.h - Represent a range ----------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Represent a range of possible values that may occur when the program is run
11// for an integral value.  This keeps track of a lower and upper bound for the
12// constant, which MAY wrap around the end of the numeric range.  To do this, it
13// keeps track of a [lower, upper) bound, which specifies an interval just like
14// STL iterators.  When used with boolean values, the following are important
15// ranges: :
16//
17//  [F, F) = {}     = Empty set
18//  [T, F) = {T}
19//  [F, T) = {F}
20//  [T, T) = {F, T} = Full set
21//
22// The other integral ranges use min/max values for special range values. For
23// example, for 8-bit types, it uses:
24// [0, 0)     = {}       = Empty set
25// [255, 255) = {0..255} = Full Set
26//
27// Note that ConstantRange can be used to represent either signed or
28// unsigned ranges.
29//
30//===----------------------------------------------------------------------===//
31
32#ifndef LLVM_IR_CONSTANTRANGE_H
33#define LLVM_IR_CONSTANTRANGE_H
34
35#include "llvm/ADT/APInt.h"
36#include "llvm/IR/InstrTypes.h"
37#include "llvm/Support/DataTypes.h"
38
39namespace llvm {
40
41class MDNode;
42
43/// This class represents a range of values.
44class LLVM_NODISCARD ConstantRange {
45  APInt Lower, Upper;
46
47public:
48  /// Initialize a full (the default) or empty set for the specified bit width.
49  explicit ConstantRange(uint32_t BitWidth, bool isFullSet = true);
50
51  /// Initialize a range to hold the single specified value.
52  ConstantRange(APInt Value);
53
54  /// @brief Initialize a range of values explicitly. This will assert out if
55  /// Lower==Upper and Lower != Min or Max value for its type. It will also
56  /// assert out if the two APInt's are not the same bit width.
57  ConstantRange(APInt Lower, APInt Upper);
58
59  /// Produce the smallest range such that all values that may satisfy the given
60  /// predicate with any value contained within Other is contained in the
61  /// returned range.  Formally, this returns a superset of
62  /// 'union over all y in Other . { x : icmp op x y is true }'.  If the exact
63  /// answer is not representable as a ConstantRange, the return value will be a
64  /// proper superset of the above.
65  ///
66  /// Example: Pred = ult and Other = i8 [2, 5) returns Result = [0, 4)
67  static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred,
68                                             const ConstantRange &Other);
69
70  /// Produce the largest range such that all values in the returned range
71  /// satisfy the given predicate with all values contained within Other.
72  /// Formally, this returns a subset of
73  /// 'intersection over all y in Other . { x : icmp op x y is true }'.  If the
74  /// exact answer is not representable as a ConstantRange, the return value
75  /// will be a proper subset of the above.
76  ///
77  /// Example: Pred = ult and Other = i8 [2, 5) returns [0, 2)
78  static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
79                                                const ConstantRange &Other);
80
81  /// Produce the exact range such that all values in the returned range satisfy
82  /// the given predicate with any value contained within Other. Formally, this
83  /// returns the exact answer when the superset of 'union over all y in Other
84  /// is exactly same as the subset of intersection over all y in Other.
85  /// { x : icmp op x y is true}'.
86  ///
87  /// Example: Pred = ult and Other = i8 3 returns [0, 3)
88  static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred,
89                                           const APInt &Other);
90
91  /// Return the largest range containing all X such that "X BinOpC Y" is
92  /// guaranteed not to wrap (overflow) for all Y in Other.
93  ///
94  /// NB! The returned set does *not* contain **all** possible values of X for
95  /// which "X BinOpC Y" does not wrap -- some viable values of X may be
96  /// missing, so you cannot use this to constrain X's range.  E.g. in the last
97  /// example, "(-2) + 1" is both nsw and nuw (so the "X" could be -2), but (-2)
98  /// is not in the set returned.
99  ///
100  /// Examples:
101  ///  typedef OverflowingBinaryOperator OBO;
102  ///  #define MGNR makeGuaranteedNoWrapRegion
103  ///  MGNR(Add, [i8 1, 2), OBO::NoSignedWrap) == [-128, 127)
104  ///  MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap) == [0, -1)
105  ///  MGNR(Add, [i8 0, 1), OBO::NoUnsignedWrap) == Full Set
106  ///  MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap | OBO::NoSignedWrap)
107  ///    == [0,INT_MAX)
108  ///  MGNR(Add, [i8 -1, 6), OBO::NoSignedWrap) == [INT_MIN+1, INT_MAX-4)
109  static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
110                                                  const ConstantRange &Other,
111                                                  unsigned NoWrapKind);
112
113  /// Set up \p Pred and \p RHS such that
114  /// ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.  Return true if
115  /// successful.
116  bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const;
117
118  /// Return the lower value for this range.
119  const APInt &getLower() const { return Lower; }
120
121  /// Return the upper value for this range.
122  const APInt &getUpper() const { return Upper; }
123
124  /// Get the bit width of this ConstantRange.
125  uint32_t getBitWidth() const { return Lower.getBitWidth(); }
126
127  /// Return true if this set contains all of the elements possible
128  /// for this data-type.
129  bool isFullSet() const;
130
131  /// Return true if this set contains no members.
132  bool isEmptySet() const;
133
134  /// Return true if this set wraps around the top of the range.
135  /// For example: [100, 8).
136  bool isWrappedSet() const;
137
138  /// Return true if this set wraps around the INT_MIN of
139  /// its bitwidth. For example: i8 [120, 140).
140  bool isSignWrappedSet() const;
141
142  /// Return true if the specified value is in the set.
143  bool contains(const APInt &Val) const;
144
145  /// Return true if the other range is a subset of this one.
146  bool contains(const ConstantRange &CR) const;
147
148  /// If this set contains a single element, return it, otherwise return null.
149  const APInt *getSingleElement() const {
150    if (Upper == Lower + 1)
151      return &Lower;
152    return nullptr;
153  }
154
155  /// If this set contains all but a single element, return it, otherwise return
156  /// null.
157  const APInt *getSingleMissingElement() const {
158    if (Lower == Upper + 1)
159      return &Upper;
160    return nullptr;
161  }
162
163  /// Return true if this set contains exactly one member.
164  bool isSingleElement() const { return getSingleElement() != nullptr; }
165
166  /// Return the number of elements in this set.
167  APInt getSetSize() const;
168
169  /// Compare set size of this range with the range CR.
170  bool isSizeStrictlySmallerThan(const ConstantRange &CR) const;
171
172  // Compare set size of this range with Value.
173  bool isSizeLargerThan(uint64_t MaxSize) const;
174
175  /// Return the largest unsigned value contained in the ConstantRange.
176  APInt getUnsignedMax() const;
177
178  /// Return the smallest unsigned value contained in the ConstantRange.
179  APInt getUnsignedMin() const;
180
181  /// Return the largest signed value contained in the ConstantRange.
182  APInt getSignedMax() const;
183
184  /// Return the smallest signed value contained in the ConstantRange.
185  APInt getSignedMin() const;
186
187  /// Return true if this range is equal to another range.
188  bool operator==(const ConstantRange &CR) const {
189    return Lower == CR.Lower && Upper == CR.Upper;
190  }
191  bool operator!=(const ConstantRange &CR) const {
192    return !operator==(CR);
193  }
194
195  /// Subtract the specified constant from the endpoints of this constant range.
196  ConstantRange subtract(const APInt &CI) const;
197
198  /// Subtract the specified range from this range (aka relative complement of
199  /// the sets).
200  ConstantRange difference(const ConstantRange &CR) const;
201
202  /// Return the range that results from the intersection of
203  /// this range with another range.  The resultant range is guaranteed to
204  /// include all elements contained in both input ranges, and to have the
205  /// smallest possible set size that does so.  Because there may be two
206  /// intersections with the same set size, A.intersectWith(B) might not
207  /// be equal to B.intersectWith(A).
208  ConstantRange intersectWith(const ConstantRange &CR) const;
209
210  /// Return the range that results from the union of this range
211  /// with another range.  The resultant range is guaranteed to include the
212  /// elements of both sets, but may contain more.  For example, [3, 9) union
213  /// [12,15) is [3, 15), which includes 9, 10, and 11, which were not included
214  /// in either set before.
215  ConstantRange unionWith(const ConstantRange &CR) const;
216
217  /// Return a new range representing the possible values resulting
218  /// from an application of the specified cast operator to this range. \p
219  /// BitWidth is the target bitwidth of the cast.  For casts which don't
220  /// change bitwidth, it must be the same as the source bitwidth.  For casts
221  /// which do change bitwidth, the bitwidth must be consistent with the
222  /// requested cast and source bitwidth.
223  ConstantRange castOp(Instruction::CastOps CastOp,
224                       uint32_t BitWidth) const;
225
226  /// Return a new range in the specified integer type, which must
227  /// be strictly larger than the current type.  The returned range will
228  /// correspond to the possible range of values if the source range had been
229  /// zero extended to BitWidth.
230  ConstantRange zeroExtend(uint32_t BitWidth) const;
231
232  /// Return a new range in the specified integer type, which must
233  /// be strictly larger than the current type.  The returned range will
234  /// correspond to the possible range of values if the source range had been
235  /// sign extended to BitWidth.
236  ConstantRange signExtend(uint32_t BitWidth) const;
237
238  /// Return a new range in the specified integer type, which must be
239  /// strictly smaller than the current type.  The returned range will
240  /// correspond to the possible range of values if the source range had been
241  /// truncated to the specified type.
242  ConstantRange truncate(uint32_t BitWidth) const;
243
244  /// Make this range have the bit width given by \p BitWidth. The
245  /// value is zero extended, truncated, or left alone to make it that width.
246  ConstantRange zextOrTrunc(uint32_t BitWidth) const;
247
248  /// Make this range have the bit width given by \p BitWidth. The
249  /// value is sign extended, truncated, or left alone to make it that width.
250  ConstantRange sextOrTrunc(uint32_t BitWidth) const;
251
252  /// Return a new range representing the possible values resulting
253  /// from an application of the specified binary operator to an left hand side
254  /// of this range and a right hand side of \p Other.
255  ConstantRange binaryOp(Instruction::BinaryOps BinOp,
256                         const ConstantRange &Other) const;
257
258  /// Return a new range representing the possible values resulting
259  /// from an addition of a value in this range and a value in \p Other.
260  ConstantRange add(const ConstantRange &Other) const;
261
262  /// Return a new range representing the possible values resulting from a
263  /// known NSW addition of a value in this range and \p Other constant.
264  ConstantRange addWithNoSignedWrap(const APInt &Other) const;
265
266  /// Return a new range representing the possible values resulting
267  /// from a subtraction of a value in this range and a value in \p Other.
268  ConstantRange sub(const ConstantRange &Other) const;
269
270  /// Return a new range representing the possible values resulting
271  /// from a multiplication of a value in this range and a value in \p Other,
272  /// treating both this and \p Other as unsigned ranges.
273  ConstantRange multiply(const ConstantRange &Other) const;
274
275  /// Return a new range representing the possible values resulting
276  /// from a signed maximum of a value in this range and a value in \p Other.
277  ConstantRange smax(const ConstantRange &Other) const;
278
279  /// Return a new range representing the possible values resulting
280  /// from an unsigned maximum of a value in this range and a value in \p Other.
281  ConstantRange umax(const ConstantRange &Other) const;
282
283  /// Return a new range representing the possible values resulting
284  /// from a signed minimum of a value in this range and a value in \p Other.
285  ConstantRange smin(const ConstantRange &Other) const;
286
287  /// Return a new range representing the possible values resulting
288  /// from an unsigned minimum of a value in this range and a value in \p Other.
289  ConstantRange umin(const ConstantRange &Other) const;
290
291  /// Return a new range representing the possible values resulting
292  /// from an unsigned division of a value in this range and a value in
293  /// \p Other.
294  ConstantRange udiv(const ConstantRange &Other) const;
295
296  /// Return a new range representing the possible values resulting
297  /// from a binary-and of a value in this range by a value in \p Other.
298  ConstantRange binaryAnd(const ConstantRange &Other) const;
299
300  /// Return a new range representing the possible values resulting
301  /// from a binary-or of a value in this range by a value in \p Other.
302  ConstantRange binaryOr(const ConstantRange &Other) const;
303
304  /// Return a new range representing the possible values resulting
305  /// from a left shift of a value in this range by a value in \p Other.
306  /// TODO: This isn't fully implemented yet.
307  ConstantRange shl(const ConstantRange &Other) const;
308
309  /// Return a new range representing the possible values resulting from a
310  /// logical right shift of a value in this range and a value in \p Other.
311  ConstantRange lshr(const ConstantRange &Other) const;
312
313  /// Return a new range that is the logical not of the current set.
314  ConstantRange inverse() const;
315
316  /// Print out the bounds to a stream.
317  void print(raw_ostream &OS) const;
318
319  /// Allow printing from a debugger easily.
320  void dump() const;
321};
322
323inline raw_ostream &operator<<(raw_ostream &OS, const ConstantRange &CR) {
324  CR.print(OS);
325  return OS;
326}
327
328/// Parse out a conservative ConstantRange from !range metadata.
329///
330/// E.g. if RangeMD is !{i32 0, i32 10, i32 15, i32 20} then return [0, 20).
331ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD);
332
333} // End llvm namespace
334
335#endif
336