ConstantRange.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. //===- ConstantRange.h - Represent a range ----------------------*- C++ -*-===//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  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: :
  15. //
  16. // [F, F) = {} = Empty set
  17. // [T, F) = {T}
  18. // [F, T) = {F}
  19. // [T, T) = {F, T} = Full set
  20. //
  21. // The other integral ranges use min/max values for special range values. For
  22. // example, for 8-bit types, it uses:
  23. // [0, 0) = {} = Empty set
  24. // [255, 255) = {0..255} = Full Set
  25. //
  26. // Note that ConstantRange can be used to represent either signed or
  27. // unsigned ranges.
  28. //
  29. //===----------------------------------------------------------------------===//
  30. #ifndef LLVM_IR_CONSTANTRANGE_H
  31. #define LLVM_IR_CONSTANTRANGE_H
  32. #include "llvm/ADT/APInt.h"
  33. #include "llvm/IR/InstrTypes.h"
  34. #include "llvm/IR/Instruction.h"
  35. #include "llvm/Support/Compiler.h"
  36. #include <cstdint>
  37. namespace llvm {
  38. class MDNode;
  39. class raw_ostream;
  40. struct KnownBits;
  41. /// This class represents a range of values.
  42. class LLVM_NODISCARD ConstantRange {
  43. APInt Lower, Upper;
  44. /// Create empty constant range with same bitwidth.
  45. ConstantRange getEmpty() const {
  46. return ConstantRange(getBitWidth(), false);
  47. }
  48. /// Create full constant range with same bitwidth.
  49. ConstantRange getFull() const {
  50. return ConstantRange(getBitWidth(), true);
  51. }
  52. public:
  53. /// Initialize a full or empty set for the specified bit width.
  54. explicit ConstantRange(uint32_t BitWidth, bool isFullSet);
  55. /// Initialize a range to hold the single specified value.
  56. ConstantRange(APInt Value);
  57. /// Initialize a range of values explicitly. This will assert out if
  58. /// Lower==Upper and Lower != Min or Max value for its type. It will also
  59. /// assert out if the two APInt's are not the same bit width.
  60. ConstantRange(APInt Lower, APInt Upper);
  61. /// Create empty constant range with the given bit width.
  62. static ConstantRange getEmpty(uint32_t BitWidth) {
  63. return ConstantRange(BitWidth, false);
  64. }
  65. /// Create full constant range with the given bit width.
  66. static ConstantRange getFull(uint32_t BitWidth) {
  67. return ConstantRange(BitWidth, true);
  68. }
  69. /// Create non-empty constant range with the given bounds. If Lower and
  70. /// Upper are the same, a full range is returned.
  71. static ConstantRange getNonEmpty(APInt Lower, APInt Upper) {
  72. if (Lower == Upper)
  73. return getFull(Lower.getBitWidth());
  74. return ConstantRange(std::move(Lower), std::move(Upper));
  75. }
  76. /// Initialize a range based on a known bits constraint. The IsSigned flag
  77. /// indicates whether the constant range should not wrap in the signed or
  78. /// unsigned domain.
  79. static ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned);
  80. /// Produce the smallest range such that all values that may satisfy the given
  81. /// predicate with any value contained within Other is contained in the
  82. /// returned range. Formally, this returns a superset of
  83. /// 'union over all y in Other . { x : icmp op x y is true }'. If the exact
  84. /// answer is not representable as a ConstantRange, the return value will be a
  85. /// proper superset of the above.
  86. ///
  87. /// Example: Pred = ult and Other = i8 [2, 5) returns Result = [0, 4)
  88. static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred,
  89. const ConstantRange &Other);
  90. /// Produce the largest range such that all values in the returned range
  91. /// satisfy the given predicate with all values contained within Other.
  92. /// Formally, this returns a subset of
  93. /// 'intersection over all y in Other . { x : icmp op x y is true }'. If the
  94. /// exact answer is not representable as a ConstantRange, the return value
  95. /// will be a proper subset of the above.
  96. ///
  97. /// Example: Pred = ult and Other = i8 [2, 5) returns [0, 2)
  98. static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
  99. const ConstantRange &Other);
  100. /// Produce the exact range such that all values in the returned range satisfy
  101. /// the given predicate with any value contained within Other. Formally, this
  102. /// returns the exact answer when the superset of 'union over all y in Other
  103. /// is exactly same as the subset of intersection over all y in Other.
  104. /// { x : icmp op x y is true}'.
  105. ///
  106. /// Example: Pred = ult and Other = i8 3 returns [0, 3)
  107. static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred,
  108. const APInt &Other);
  109. /// Does the predicate \p Pred hold between ranges this and \p Other?
  110. /// NOTE: false does not mean that inverse predicate holds!
  111. bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const;
  112. /// Produce the largest range containing all X such that "X BinOp Y" is
  113. /// guaranteed not to wrap (overflow) for *all* Y in Other. However, there may
  114. /// be *some* Y in Other for which additional X not contained in the result
  115. /// also do not overflow.
  116. ///
  117. /// NoWrapKind must be one of OBO::NoUnsignedWrap or OBO::NoSignedWrap.
  118. ///
  119. /// Examples:
  120. /// typedef OverflowingBinaryOperator OBO;
  121. /// #define MGNR makeGuaranteedNoWrapRegion
  122. /// MGNR(Add, [i8 1, 2), OBO::NoSignedWrap) == [-128, 127)
  123. /// MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap) == [0, -1)
  124. /// MGNR(Add, [i8 0, 1), OBO::NoUnsignedWrap) == Full Set
  125. /// MGNR(Add, [i8 -1, 6), OBO::NoSignedWrap) == [INT_MIN+1, INT_MAX-4)
  126. /// MGNR(Sub, [i8 1, 2), OBO::NoSignedWrap) == [-127, 128)
  127. /// MGNR(Sub, [i8 1, 2), OBO::NoUnsignedWrap) == [1, 0)
  128. static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
  129. const ConstantRange &Other,
  130. unsigned NoWrapKind);
  131. /// Produce the range that contains X if and only if "X BinOp Other" does
  132. /// not wrap.
  133. static ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
  134. const APInt &Other,
  135. unsigned NoWrapKind);
  136. /// Returns true if ConstantRange calculations are supported for intrinsic
  137. /// with \p IntrinsicID.
  138. static bool isIntrinsicSupported(Intrinsic::ID IntrinsicID);
  139. /// Compute range of intrinsic result for the given operand ranges.
  140. static ConstantRange intrinsic(Intrinsic::ID IntrinsicID,
  141. ArrayRef<ConstantRange> Ops);
  142. /// Set up \p Pred and \p RHS such that
  143. /// ConstantRange::makeExactICmpRegion(Pred, RHS) == *this. Return true if
  144. /// successful.
  145. bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const;
  146. /// Return the lower value for this range.
  147. const APInt &getLower() const { return Lower; }
  148. /// Return the upper value for this range.
  149. const APInt &getUpper() const { return Upper; }
  150. /// Get the bit width of this ConstantRange.
  151. uint32_t getBitWidth() const { return Lower.getBitWidth(); }
  152. /// Return true if this set contains all of the elements possible
  153. /// for this data-type.
  154. bool isFullSet() const;
  155. /// Return true if this set contains no members.
  156. bool isEmptySet() const;
  157. /// Return true if this set wraps around the unsigned domain. Special cases:
  158. /// * Empty set: Not wrapped.
  159. /// * Full set: Not wrapped.
  160. /// * [X, 0) == [X, Max]: Not wrapped.
  161. bool isWrappedSet() const;
  162. /// Return true if the exclusive upper bound wraps around the unsigned
  163. /// domain. Special cases:
  164. /// * Empty set: Not wrapped.
  165. /// * Full set: Not wrapped.
  166. /// * [X, 0): Wrapped.
  167. bool isUpperWrapped() const;
  168. /// Return true if this set wraps around the signed domain. Special cases:
  169. /// * Empty set: Not wrapped.
  170. /// * Full set: Not wrapped.
  171. /// * [X, SignedMin) == [X, SignedMax]: Not wrapped.
  172. bool isSignWrappedSet() const;
  173. /// Return true if the (exclusive) upper bound wraps around the signed
  174. /// domain. Special cases:
  175. /// * Empty set: Not wrapped.
  176. /// * Full set: Not wrapped.
  177. /// * [X, SignedMin): Wrapped.
  178. bool isUpperSignWrapped() const;
  179. /// Return true if the specified value is in the set.
  180. bool contains(const APInt &Val) const;
  181. /// Return true if the other range is a subset of this one.
  182. bool contains(const ConstantRange &CR) const;
  183. /// If this set contains a single element, return it, otherwise return null.
  184. const APInt *getSingleElement() const {
  185. if (Upper == Lower + 1)
  186. return &Lower;
  187. return nullptr;
  188. }
  189. /// If this set contains all but a single element, return it, otherwise return
  190. /// null.
  191. const APInt *getSingleMissingElement() const {
  192. if (Lower == Upper + 1)
  193. return &Upper;
  194. return nullptr;
  195. }
  196. /// Return true if this set contains exactly one member.
  197. bool isSingleElement() const { return getSingleElement() != nullptr; }
  198. /// Compare set size of this range with the range CR.
  199. bool isSizeStrictlySmallerThan(const ConstantRange &CR) const;
  200. /// Compare set size of this range with Value.
  201. bool isSizeLargerThan(uint64_t MaxSize) const;
  202. /// Return true if all values in this range are negative.
  203. bool isAllNegative() const;
  204. /// Return true if all values in this range are non-negative.
  205. bool isAllNonNegative() const;
  206. /// Return the largest unsigned value contained in the ConstantRange.
  207. APInt getUnsignedMax() const;
  208. /// Return the smallest unsigned value contained in the ConstantRange.
  209. APInt getUnsignedMin() const;
  210. /// Return the largest signed value contained in the ConstantRange.
  211. APInt getSignedMax() const;
  212. /// Return the smallest signed value contained in the ConstantRange.
  213. APInt getSignedMin() const;
  214. /// Return true if this range is equal to another range.
  215. bool operator==(const ConstantRange &CR) const {
  216. return Lower == CR.Lower && Upper == CR.Upper;
  217. }
  218. bool operator!=(const ConstantRange &CR) const {
  219. return !operator==(CR);
  220. }
  221. /// Compute the maximal number of active bits needed to represent every value
  222. /// in this range.
  223. unsigned getActiveBits() const;
  224. /// Compute the maximal number of bits needed to represent every value
  225. /// in this signed range.
  226. unsigned getMinSignedBits() const;
  227. /// Subtract the specified constant from the endpoints of this constant range.
  228. ConstantRange subtract(const APInt &CI) const;
  229. /// Subtract the specified range from this range (aka relative complement of
  230. /// the sets).
  231. ConstantRange difference(const ConstantRange &CR) const;
  232. /// If represented precisely, the result of some range operations may consist
  233. /// of multiple disjoint ranges. As only a single range may be returned, any
  234. /// range covering these disjoint ranges constitutes a valid result, but some
  235. /// may be more useful than others depending on context. The preferred range
  236. /// type specifies whether a range that is non-wrapping in the unsigned or
  237. /// signed domain, or has the smallest size, is preferred. If a signedness is
  238. /// preferred but all ranges are non-wrapping or all wrapping, then the
  239. /// smallest set size is preferred. If there are multiple smallest sets, any
  240. /// one of them may be returned.
  241. enum PreferredRangeType { Smallest, Unsigned, Signed };
  242. /// Return the range that results from the intersection of this range with
  243. /// another range. If the intersection is disjoint, such that two results
  244. /// are possible, the preferred range is determined by the PreferredRangeType.
  245. ConstantRange intersectWith(const ConstantRange &CR,
  246. PreferredRangeType Type = Smallest) const;
  247. /// Return the range that results from the union of this range
  248. /// with another range. The resultant range is guaranteed to include the
  249. /// elements of both sets, but may contain more. For example, [3, 9) union
  250. /// [12,15) is [3, 15), which includes 9, 10, and 11, which were not included
  251. /// in either set before.
  252. ConstantRange unionWith(const ConstantRange &CR,
  253. PreferredRangeType Type = Smallest) const;
  254. /// Return a new range representing the possible values resulting
  255. /// from an application of the specified cast operator to this range. \p
  256. /// BitWidth is the target bitwidth of the cast. For casts which don't
  257. /// change bitwidth, it must be the same as the source bitwidth. For casts
  258. /// which do change bitwidth, the bitwidth must be consistent with the
  259. /// requested cast and source bitwidth.
  260. ConstantRange castOp(Instruction::CastOps CastOp,
  261. uint32_t BitWidth) const;
  262. /// Return a new range in the specified integer type, which must
  263. /// be strictly larger than the current type. The returned range will
  264. /// correspond to the possible range of values if the source range had been
  265. /// zero extended to BitWidth.
  266. ConstantRange zeroExtend(uint32_t BitWidth) const;
  267. /// Return a new range in the specified integer type, which must
  268. /// be strictly larger than the current type. The returned range will
  269. /// correspond to the possible range of values if the source range had been
  270. /// sign extended to BitWidth.
  271. ConstantRange signExtend(uint32_t BitWidth) const;
  272. /// Return a new range in the specified integer type, which must be
  273. /// strictly smaller than the current type. The returned range will
  274. /// correspond to the possible range of values if the source range had been
  275. /// truncated to the specified type.
  276. ConstantRange truncate(uint32_t BitWidth) const;
  277. /// Make this range have the bit width given by \p BitWidth. The
  278. /// value is zero extended, truncated, or left alone to make it that width.
  279. ConstantRange zextOrTrunc(uint32_t BitWidth) const;
  280. /// Make this range have the bit width given by \p BitWidth. The
  281. /// value is sign extended, truncated, or left alone to make it that width.
  282. ConstantRange sextOrTrunc(uint32_t BitWidth) const;
  283. /// Return a new range representing the possible values resulting
  284. /// from an application of the specified binary operator to an left hand side
  285. /// of this range and a right hand side of \p Other.
  286. ConstantRange binaryOp(Instruction::BinaryOps BinOp,
  287. const ConstantRange &Other) const;
  288. /// Return a new range representing the possible values resulting
  289. /// from an application of the specified overflowing binary operator to a
  290. /// left hand side of this range and a right hand side of \p Other given
  291. /// the provided knowledge about lack of wrapping \p NoWrapKind.
  292. ConstantRange overflowingBinaryOp(Instruction::BinaryOps BinOp,
  293. const ConstantRange &Other,
  294. unsigned NoWrapKind) const;
  295. /// Return a new range representing the possible values resulting
  296. /// from an addition of a value in this range and a value in \p Other.
  297. ConstantRange add(const ConstantRange &Other) const;
  298. /// Return a new range representing the possible values resulting
  299. /// from an addition with wrap type \p NoWrapKind of a value in this
  300. /// range and a value in \p Other.
  301. /// If the result range is disjoint, the preferred range is determined by the
  302. /// \p PreferredRangeType.
  303. ConstantRange addWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind,
  304. PreferredRangeType RangeType = Smallest) const;
  305. /// Return a new range representing the possible values resulting
  306. /// from a subtraction of a value in this range and a value in \p Other.
  307. ConstantRange sub(const ConstantRange &Other) const;
  308. /// Return a new range representing the possible values resulting
  309. /// from an subtraction with wrap type \p NoWrapKind of a value in this
  310. /// range and a value in \p Other.
  311. /// If the result range is disjoint, the preferred range is determined by the
  312. /// \p PreferredRangeType.
  313. ConstantRange subWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind,
  314. PreferredRangeType RangeType = Smallest) const;
  315. /// Return a new range representing the possible values resulting
  316. /// from a multiplication of a value in this range and a value in \p Other,
  317. /// treating both this and \p Other as unsigned ranges.
  318. ConstantRange multiply(const ConstantRange &Other) const;
  319. /// Return a new range representing the possible values resulting
  320. /// from a signed maximum of a value in this range and a value in \p Other.
  321. ConstantRange smax(const ConstantRange &Other) const;
  322. /// Return a new range representing the possible values resulting
  323. /// from an unsigned maximum of a value in this range and a value in \p Other.
  324. ConstantRange umax(const ConstantRange &Other) const;
  325. /// Return a new range representing the possible values resulting
  326. /// from a signed minimum of a value in this range and a value in \p Other.
  327. ConstantRange smin(const ConstantRange &Other) const;
  328. /// Return a new range representing the possible values resulting
  329. /// from an unsigned minimum of a value in this range and a value in \p Other.
  330. ConstantRange umin(const ConstantRange &Other) const;
  331. /// Return a new range representing the possible values resulting
  332. /// from an unsigned division of a value in this range and a value in
  333. /// \p Other.
  334. ConstantRange udiv(const ConstantRange &Other) const;
  335. /// Return a new range representing the possible values resulting
  336. /// from a signed division of a value in this range and a value in
  337. /// \p Other. Division by zero and division of SignedMin by -1 are considered
  338. /// undefined behavior, in line with IR, and do not contribute towards the
  339. /// result.
  340. ConstantRange sdiv(const ConstantRange &Other) const;
  341. /// Return a new range representing the possible values resulting
  342. /// from an unsigned remainder operation of a value in this range and a
  343. /// value in \p Other.
  344. ConstantRange urem(const ConstantRange &Other) const;
  345. /// Return a new range representing the possible values resulting
  346. /// from a signed remainder operation of a value in this range and a
  347. /// value in \p Other.
  348. ConstantRange srem(const ConstantRange &Other) const;
  349. /// Return a new range representing the possible values resulting from
  350. /// a binary-xor of a value in this range by an all-one value,
  351. /// aka bitwise complement operation.
  352. ConstantRange binaryNot() const;
  353. /// Return a new range representing the possible values resulting
  354. /// from a binary-and of a value in this range by a value in \p Other.
  355. ConstantRange binaryAnd(const ConstantRange &Other) const;
  356. /// Return a new range representing the possible values resulting
  357. /// from a binary-or of a value in this range by a value in \p Other.
  358. ConstantRange binaryOr(const ConstantRange &Other) const;
  359. /// Return a new range representing the possible values resulting
  360. /// from a binary-xor of a value in this range by a value in \p Other.
  361. ConstantRange binaryXor(const ConstantRange &Other) const;
  362. /// Return a new range representing the possible values resulting
  363. /// from a left shift of a value in this range by a value in \p Other.
  364. /// TODO: This isn't fully implemented yet.
  365. ConstantRange shl(const ConstantRange &Other) const;
  366. /// Return a new range representing the possible values resulting from a
  367. /// logical right shift of a value in this range and a value in \p Other.
  368. ConstantRange lshr(const ConstantRange &Other) const;
  369. /// Return a new range representing the possible values resulting from a
  370. /// arithmetic right shift of a value in this range and a value in \p Other.
  371. ConstantRange ashr(const ConstantRange &Other) const;
  372. /// Perform an unsigned saturating addition of two constant ranges.
  373. ConstantRange uadd_sat(const ConstantRange &Other) const;
  374. /// Perform a signed saturating addition of two constant ranges.
  375. ConstantRange sadd_sat(const ConstantRange &Other) const;
  376. /// Perform an unsigned saturating subtraction of two constant ranges.
  377. ConstantRange usub_sat(const ConstantRange &Other) const;
  378. /// Perform a signed saturating subtraction of two constant ranges.
  379. ConstantRange ssub_sat(const ConstantRange &Other) const;
  380. /// Perform an unsigned saturating multiplication of two constant ranges.
  381. ConstantRange umul_sat(const ConstantRange &Other) const;
  382. /// Perform a signed saturating multiplication of two constant ranges.
  383. ConstantRange smul_sat(const ConstantRange &Other) const;
  384. /// Perform an unsigned saturating left shift of this constant range by a
  385. /// value in \p Other.
  386. ConstantRange ushl_sat(const ConstantRange &Other) const;
  387. /// Perform a signed saturating left shift of this constant range by a
  388. /// value in \p Other.
  389. ConstantRange sshl_sat(const ConstantRange &Other) const;
  390. /// Return a new range that is the logical not of the current set.
  391. ConstantRange inverse() const;
  392. /// Calculate absolute value range. If the original range contains signed
  393. /// min, then the resulting range will contain signed min if and only if
  394. /// \p IntMinIsPoison is false.
  395. ConstantRange abs(bool IntMinIsPoison = false) const;
  396. /// Represents whether an operation on the given constant range is known to
  397. /// always or never overflow.
  398. enum class OverflowResult {
  399. /// Always overflows in the direction of signed/unsigned min value.
  400. AlwaysOverflowsLow,
  401. /// Always overflows in the direction of signed/unsigned max value.
  402. AlwaysOverflowsHigh,
  403. /// May or may not overflow.
  404. MayOverflow,
  405. /// Never overflows.
  406. NeverOverflows,
  407. };
  408. /// Return whether unsigned add of the two ranges always/never overflows.
  409. OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const;
  410. /// Return whether signed add of the two ranges always/never overflows.
  411. OverflowResult signedAddMayOverflow(const ConstantRange &Other) const;
  412. /// Return whether unsigned sub of the two ranges always/never overflows.
  413. OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const;
  414. /// Return whether signed sub of the two ranges always/never overflows.
  415. OverflowResult signedSubMayOverflow(const ConstantRange &Other) const;
  416. /// Return whether unsigned mul of the two ranges always/never overflows.
  417. OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const;
  418. /// Print out the bounds to a stream.
  419. void print(raw_ostream &OS) const;
  420. /// Allow printing from a debugger easily.
  421. void dump() const;
  422. };
  423. inline raw_ostream &operator<<(raw_ostream &OS, const ConstantRange &CR) {
  424. CR.print(OS);
  425. return OS;
  426. }
  427. /// Parse out a conservative ConstantRange from !range metadata.
  428. ///
  429. /// E.g. if RangeMD is !{i32 0, i32 10, i32 15, i32 20} then return [0, 20).
  430. ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD);
  431. } // end namespace llvm
  432. #endif // LLVM_IR_CONSTANTRANGE_H