ConstantRange.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  1. //===- ConstantRange.cpp - ConstantRange implementation -------------------===//
  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 (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. #include "llvm/ADT/APInt.h"
  23. #include "llvm/Config/llvm-config.h"
  24. #include "llvm/IR/ConstantRange.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/InstrTypes.h"
  27. #include "llvm/IR/Instruction.h"
  28. #include "llvm/IR/Intrinsics.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/Operator.h"
  31. #include "llvm/Support/Compiler.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/KnownBits.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <algorithm>
  37. #include <cassert>
  38. #include <cstdint>
  39. using namespace llvm;
  40. ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
  41. : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
  42. Upper(Lower) {}
  43. ConstantRange::ConstantRange(APInt V)
  44. : Lower(std::move(V)), Upper(Lower + 1) {}
  45. ConstantRange::ConstantRange(APInt L, APInt U)
  46. : Lower(std::move(L)), Upper(std::move(U)) {
  47. assert(Lower.getBitWidth() == Upper.getBitWidth() &&
  48. "ConstantRange with unequal bit widths");
  49. assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
  50. "Lower == Upper, but they aren't min or max value!");
  51. }
  52. ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
  53. bool IsSigned) {
  54. assert(!Known.hasConflict() && "Expected valid KnownBits");
  55. if (Known.isUnknown())
  56. return getFull(Known.getBitWidth());
  57. // For unsigned ranges, or signed ranges with known sign bit, create a simple
  58. // range between the smallest and largest possible value.
  59. if (!IsSigned || Known.isNegative() || Known.isNonNegative())
  60. return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);
  61. // If we don't know the sign bit, pick the lower bound as a negative number
  62. // and the upper bound as a non-negative one.
  63. APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();
  64. Lower.setSignBit();
  65. Upper.clearSignBit();
  66. return ConstantRange(Lower, Upper + 1);
  67. }
  68. ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
  69. const ConstantRange &CR) {
  70. if (CR.isEmptySet())
  71. return CR;
  72. uint32_t W = CR.getBitWidth();
  73. switch (Pred) {
  74. default:
  75. llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
  76. case CmpInst::ICMP_EQ:
  77. return CR;
  78. case CmpInst::ICMP_NE:
  79. if (CR.isSingleElement())
  80. return ConstantRange(CR.getUpper(), CR.getLower());
  81. return getFull(W);
  82. case CmpInst::ICMP_ULT: {
  83. APInt UMax(CR.getUnsignedMax());
  84. if (UMax.isMinValue())
  85. return getEmpty(W);
  86. return ConstantRange(APInt::getMinValue(W), std::move(UMax));
  87. }
  88. case CmpInst::ICMP_SLT: {
  89. APInt SMax(CR.getSignedMax());
  90. if (SMax.isMinSignedValue())
  91. return getEmpty(W);
  92. return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
  93. }
  94. case CmpInst::ICMP_ULE:
  95. return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
  96. case CmpInst::ICMP_SLE:
  97. return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
  98. case CmpInst::ICMP_UGT: {
  99. APInt UMin(CR.getUnsignedMin());
  100. if (UMin.isMaxValue())
  101. return getEmpty(W);
  102. return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W));
  103. }
  104. case CmpInst::ICMP_SGT: {
  105. APInt SMin(CR.getSignedMin());
  106. if (SMin.isMaxSignedValue())
  107. return getEmpty(W);
  108. return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
  109. }
  110. case CmpInst::ICMP_UGE:
  111. return getNonEmpty(CR.getUnsignedMin(), APInt::getNullValue(W));
  112. case CmpInst::ICMP_SGE:
  113. return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
  114. }
  115. }
  116. ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
  117. const ConstantRange &CR) {
  118. // Follows from De-Morgan's laws:
  119. //
  120. // ~(~A union ~B) == A intersect B.
  121. //
  122. return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
  123. .inverse();
  124. }
  125. ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
  126. const APInt &C) {
  127. // Computes the exact range that is equal to both the constant ranges returned
  128. // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
  129. // when RHS is a singleton such as an APInt and so the assert is valid.
  130. // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
  131. // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
  132. //
  133. assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
  134. return makeAllowedICmpRegion(Pred, C);
  135. }
  136. bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
  137. APInt &RHS) const {
  138. bool Success = false;
  139. if (isFullSet() || isEmptySet()) {
  140. Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
  141. RHS = APInt(getBitWidth(), 0);
  142. Success = true;
  143. } else if (auto *OnlyElt = getSingleElement()) {
  144. Pred = CmpInst::ICMP_EQ;
  145. RHS = *OnlyElt;
  146. Success = true;
  147. } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
  148. Pred = CmpInst::ICMP_NE;
  149. RHS = *OnlyMissingElt;
  150. Success = true;
  151. } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
  152. Pred =
  153. getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
  154. RHS = getUpper();
  155. Success = true;
  156. } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
  157. Pred =
  158. getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
  159. RHS = getLower();
  160. Success = true;
  161. }
  162. assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
  163. "Bad result!");
  164. return Success;
  165. }
  166. /// Exact mul nuw region for single element RHS.
  167. static ConstantRange makeExactMulNUWRegion(const APInt &V) {
  168. unsigned BitWidth = V.getBitWidth();
  169. if (V == 0)
  170. return ConstantRange::getFull(V.getBitWidth());
  171. return ConstantRange::getNonEmpty(
  172. APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,
  173. APInt::Rounding::UP),
  174. APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,
  175. APInt::Rounding::DOWN) + 1);
  176. }
  177. /// Exact mul nsw region for single element RHS.
  178. static ConstantRange makeExactMulNSWRegion(const APInt &V) {
  179. // Handle special case for 0, -1 and 1. See the last for reason why we
  180. // specialize -1 and 1.
  181. unsigned BitWidth = V.getBitWidth();
  182. if (V == 0 || V.isOneValue())
  183. return ConstantRange::getFull(BitWidth);
  184. APInt MinValue = APInt::getSignedMinValue(BitWidth);
  185. APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
  186. // e.g. Returning [-127, 127], represented as [-127, -128).
  187. if (V.isAllOnesValue())
  188. return ConstantRange(-MaxValue, MinValue);
  189. APInt Lower, Upper;
  190. if (V.isNegative()) {
  191. Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
  192. Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
  193. } else {
  194. Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
  195. Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
  196. }
  197. // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
  198. // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1,
  199. // and 1 are already handled as special cases.
  200. return ConstantRange(Lower, Upper + 1);
  201. }
  202. ConstantRange
  203. ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
  204. const ConstantRange &Other,
  205. unsigned NoWrapKind) {
  206. using OBO = OverflowingBinaryOperator;
  207. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  208. assert((NoWrapKind == OBO::NoSignedWrap ||
  209. NoWrapKind == OBO::NoUnsignedWrap) &&
  210. "NoWrapKind invalid!");
  211. bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
  212. unsigned BitWidth = Other.getBitWidth();
  213. switch (BinOp) {
  214. default:
  215. llvm_unreachable("Unsupported binary op");
  216. case Instruction::Add: {
  217. if (Unsigned)
  218. return getNonEmpty(APInt::getNullValue(BitWidth),
  219. -Other.getUnsignedMax());
  220. APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
  221. APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
  222. return getNonEmpty(
  223. SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
  224. SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
  225. }
  226. case Instruction::Sub: {
  227. if (Unsigned)
  228. return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
  229. APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
  230. APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
  231. return getNonEmpty(
  232. SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
  233. SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
  234. }
  235. case Instruction::Mul:
  236. if (Unsigned)
  237. return makeExactMulNUWRegion(Other.getUnsignedMax());
  238. return makeExactMulNSWRegion(Other.getSignedMin())
  239. .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
  240. case Instruction::Shl: {
  241. // For given range of shift amounts, if we ignore all illegal shift amounts
  242. // (that always produce poison), what shift amount range is left?
  243. ConstantRange ShAmt = Other.intersectWith(
  244. ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1)));
  245. if (ShAmt.isEmptySet()) {
  246. // If the entire range of shift amounts is already poison-producing,
  247. // then we can freely add more poison-producing flags ontop of that.
  248. return getFull(BitWidth);
  249. }
  250. // There are some legal shift amounts, we can compute conservatively-correct
  251. // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax
  252. // to be at most bitwidth-1, which results in most conservative range.
  253. APInt ShAmtUMax = ShAmt.getUnsignedMax();
  254. if (Unsigned)
  255. return getNonEmpty(APInt::getNullValue(BitWidth),
  256. APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);
  257. return getNonEmpty(APInt::getSignedMinValue(BitWidth).ashr(ShAmtUMax),
  258. APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);
  259. }
  260. }
  261. }
  262. ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
  263. const APInt &Other,
  264. unsigned NoWrapKind) {
  265. // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
  266. // "for all" and "for any" coincide in this case.
  267. return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
  268. }
  269. bool ConstantRange::isFullSet() const {
  270. return Lower == Upper && Lower.isMaxValue();
  271. }
  272. bool ConstantRange::isEmptySet() const {
  273. return Lower == Upper && Lower.isMinValue();
  274. }
  275. bool ConstantRange::isWrappedSet() const {
  276. return Lower.ugt(Upper) && !Upper.isNullValue();
  277. }
  278. bool ConstantRange::isUpperWrapped() const {
  279. return Lower.ugt(Upper);
  280. }
  281. bool ConstantRange::isSignWrappedSet() const {
  282. return Lower.sgt(Upper) && !Upper.isMinSignedValue();
  283. }
  284. bool ConstantRange::isUpperSignWrapped() const {
  285. return Lower.sgt(Upper);
  286. }
  287. bool
  288. ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
  289. assert(getBitWidth() == Other.getBitWidth());
  290. if (isFullSet())
  291. return false;
  292. if (Other.isFullSet())
  293. return true;
  294. return (Upper - Lower).ult(Other.Upper - Other.Lower);
  295. }
  296. bool
  297. ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
  298. assert(MaxSize && "MaxSize can't be 0.");
  299. // If this a full set, we need special handling to avoid needing an extra bit
  300. // to represent the size.
  301. if (isFullSet())
  302. return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
  303. return (Upper - Lower).ugt(MaxSize);
  304. }
  305. bool ConstantRange::isAllNegative() const {
  306. // Empty set is all negative, full set is not.
  307. if (isEmptySet())
  308. return true;
  309. if (isFullSet())
  310. return false;
  311. return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
  312. }
  313. bool ConstantRange::isAllNonNegative() const {
  314. // Empty and full set are automatically treated correctly.
  315. return !isSignWrappedSet() && Lower.isNonNegative();
  316. }
  317. APInt ConstantRange::getUnsignedMax() const {
  318. if (isFullSet() || isUpperWrapped())
  319. return APInt::getMaxValue(getBitWidth());
  320. return getUpper() - 1;
  321. }
  322. APInt ConstantRange::getUnsignedMin() const {
  323. if (isFullSet() || isWrappedSet())
  324. return APInt::getMinValue(getBitWidth());
  325. return getLower();
  326. }
  327. APInt ConstantRange::getSignedMax() const {
  328. if (isFullSet() || isUpperSignWrapped())
  329. return APInt::getSignedMaxValue(getBitWidth());
  330. return getUpper() - 1;
  331. }
  332. APInt ConstantRange::getSignedMin() const {
  333. if (isFullSet() || isSignWrappedSet())
  334. return APInt::getSignedMinValue(getBitWidth());
  335. return getLower();
  336. }
  337. bool ConstantRange::contains(const APInt &V) const {
  338. if (Lower == Upper)
  339. return isFullSet();
  340. if (!isUpperWrapped())
  341. return Lower.ule(V) && V.ult(Upper);
  342. return Lower.ule(V) || V.ult(Upper);
  343. }
  344. bool ConstantRange::contains(const ConstantRange &Other) const {
  345. if (isFullSet() || Other.isEmptySet()) return true;
  346. if (isEmptySet() || Other.isFullSet()) return false;
  347. if (!isUpperWrapped()) {
  348. if (Other.isUpperWrapped())
  349. return false;
  350. return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
  351. }
  352. if (!Other.isUpperWrapped())
  353. return Other.getUpper().ule(Upper) ||
  354. Lower.ule(Other.getLower());
  355. return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
  356. }
  357. unsigned ConstantRange::getActiveBits() const {
  358. if (isEmptySet())
  359. return 0;
  360. return getUnsignedMax().getActiveBits();
  361. }
  362. unsigned ConstantRange::getMinSignedBits() const {
  363. if (isEmptySet())
  364. return 0;
  365. return std::max(getSignedMin().getMinSignedBits(),
  366. getSignedMax().getMinSignedBits());
  367. }
  368. ConstantRange ConstantRange::subtract(const APInt &Val) const {
  369. assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
  370. // If the set is empty or full, don't modify the endpoints.
  371. if (Lower == Upper)
  372. return *this;
  373. return ConstantRange(Lower - Val, Upper - Val);
  374. }
  375. ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
  376. return intersectWith(CR.inverse());
  377. }
  378. static ConstantRange getPreferredRange(
  379. const ConstantRange &CR1, const ConstantRange &CR2,
  380. ConstantRange::PreferredRangeType Type) {
  381. if (Type == ConstantRange::Unsigned) {
  382. if (!CR1.isWrappedSet() && CR2.isWrappedSet())
  383. return CR1;
  384. if (CR1.isWrappedSet() && !CR2.isWrappedSet())
  385. return CR2;
  386. } else if (Type == ConstantRange::Signed) {
  387. if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
  388. return CR1;
  389. if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
  390. return CR2;
  391. }
  392. if (CR1.isSizeStrictlySmallerThan(CR2))
  393. return CR1;
  394. return CR2;
  395. }
  396. ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
  397. PreferredRangeType Type) const {
  398. assert(getBitWidth() == CR.getBitWidth() &&
  399. "ConstantRange types don't agree!");
  400. // Handle common cases.
  401. if ( isEmptySet() || CR.isFullSet()) return *this;
  402. if (CR.isEmptySet() || isFullSet()) return CR;
  403. if (!isUpperWrapped() && CR.isUpperWrapped())
  404. return CR.intersectWith(*this, Type);
  405. if (!isUpperWrapped() && !CR.isUpperWrapped()) {
  406. if (Lower.ult(CR.Lower)) {
  407. // L---U : this
  408. // L---U : CR
  409. if (Upper.ule(CR.Lower))
  410. return getEmpty();
  411. // L---U : this
  412. // L---U : CR
  413. if (Upper.ult(CR.Upper))
  414. return ConstantRange(CR.Lower, Upper);
  415. // L-------U : this
  416. // L---U : CR
  417. return CR;
  418. }
  419. // L---U : this
  420. // L-------U : CR
  421. if (Upper.ult(CR.Upper))
  422. return *this;
  423. // L-----U : this
  424. // L-----U : CR
  425. if (Lower.ult(CR.Upper))
  426. return ConstantRange(Lower, CR.Upper);
  427. // L---U : this
  428. // L---U : CR
  429. return getEmpty();
  430. }
  431. if (isUpperWrapped() && !CR.isUpperWrapped()) {
  432. if (CR.Lower.ult(Upper)) {
  433. // ------U L--- : this
  434. // L--U : CR
  435. if (CR.Upper.ult(Upper))
  436. return CR;
  437. // ------U L--- : this
  438. // L------U : CR
  439. if (CR.Upper.ule(Lower))
  440. return ConstantRange(CR.Lower, Upper);
  441. // ------U L--- : this
  442. // L----------U : CR
  443. return getPreferredRange(*this, CR, Type);
  444. }
  445. if (CR.Lower.ult(Lower)) {
  446. // --U L---- : this
  447. // L--U : CR
  448. if (CR.Upper.ule(Lower))
  449. return getEmpty();
  450. // --U L---- : this
  451. // L------U : CR
  452. return ConstantRange(Lower, CR.Upper);
  453. }
  454. // --U L------ : this
  455. // L--U : CR
  456. return CR;
  457. }
  458. if (CR.Upper.ult(Upper)) {
  459. // ------U L-- : this
  460. // --U L------ : CR
  461. if (CR.Lower.ult(Upper))
  462. return getPreferredRange(*this, CR, Type);
  463. // ----U L-- : this
  464. // --U L---- : CR
  465. if (CR.Lower.ult(Lower))
  466. return ConstantRange(Lower, CR.Upper);
  467. // ----U L---- : this
  468. // --U L-- : CR
  469. return CR;
  470. }
  471. if (CR.Upper.ule(Lower)) {
  472. // --U L-- : this
  473. // ----U L---- : CR
  474. if (CR.Lower.ult(Lower))
  475. return *this;
  476. // --U L---- : this
  477. // ----U L-- : CR
  478. return ConstantRange(CR.Lower, Upper);
  479. }
  480. // --U L------ : this
  481. // ------U L-- : CR
  482. return getPreferredRange(*this, CR, Type);
  483. }
  484. ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
  485. PreferredRangeType Type) const {
  486. assert(getBitWidth() == CR.getBitWidth() &&
  487. "ConstantRange types don't agree!");
  488. if ( isFullSet() || CR.isEmptySet()) return *this;
  489. if (CR.isFullSet() || isEmptySet()) return CR;
  490. if (!isUpperWrapped() && CR.isUpperWrapped())
  491. return CR.unionWith(*this, Type);
  492. if (!isUpperWrapped() && !CR.isUpperWrapped()) {
  493. // L---U and L---U : this
  494. // L---U L---U : CR
  495. // result in one of
  496. // L---------U
  497. // -----U L-----
  498. if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
  499. return getPreferredRange(
  500. ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
  501. APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
  502. APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
  503. if (L.isNullValue() && U.isNullValue())
  504. return getFull();
  505. return ConstantRange(std::move(L), std::move(U));
  506. }
  507. if (!CR.isUpperWrapped()) {
  508. // ------U L----- and ------U L----- : this
  509. // L--U L--U : CR
  510. if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
  511. return *this;
  512. // ------U L----- : this
  513. // L---------U : CR
  514. if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
  515. return getFull();
  516. // ----U L---- : this
  517. // L---U : CR
  518. // results in one of
  519. // ----------U L----
  520. // ----U L----------
  521. if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
  522. return getPreferredRange(
  523. ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
  524. // ----U L----- : this
  525. // L----U : CR
  526. if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
  527. return ConstantRange(CR.Lower, Upper);
  528. // ------U L---- : this
  529. // L-----U : CR
  530. assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
  531. "ConstantRange::unionWith missed a case with one range wrapped");
  532. return ConstantRange(Lower, CR.Upper);
  533. }
  534. // ------U L---- and ------U L---- : this
  535. // -U L----------- and ------------U L : CR
  536. if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
  537. return getFull();
  538. APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
  539. APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
  540. return ConstantRange(std::move(L), std::move(U));
  541. }
  542. ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
  543. uint32_t ResultBitWidth) const {
  544. switch (CastOp) {
  545. default:
  546. llvm_unreachable("unsupported cast type");
  547. case Instruction::Trunc:
  548. return truncate(ResultBitWidth);
  549. case Instruction::SExt:
  550. return signExtend(ResultBitWidth);
  551. case Instruction::ZExt:
  552. return zeroExtend(ResultBitWidth);
  553. case Instruction::BitCast:
  554. return *this;
  555. case Instruction::FPToUI:
  556. case Instruction::FPToSI:
  557. if (getBitWidth() == ResultBitWidth)
  558. return *this;
  559. else
  560. return getFull(ResultBitWidth);
  561. case Instruction::UIToFP: {
  562. // TODO: use input range if available
  563. auto BW = getBitWidth();
  564. APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
  565. APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
  566. return ConstantRange(std::move(Min), std::move(Max));
  567. }
  568. case Instruction::SIToFP: {
  569. // TODO: use input range if available
  570. auto BW = getBitWidth();
  571. APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
  572. APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
  573. return ConstantRange(std::move(SMin), std::move(SMax));
  574. }
  575. case Instruction::FPTrunc:
  576. case Instruction::FPExt:
  577. case Instruction::IntToPtr:
  578. case Instruction::PtrToInt:
  579. case Instruction::AddrSpaceCast:
  580. // Conservatively return getFull set.
  581. return getFull(ResultBitWidth);
  582. };
  583. }
  584. ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
  585. if (isEmptySet()) return getEmpty(DstTySize);
  586. unsigned SrcTySize = getBitWidth();
  587. assert(SrcTySize < DstTySize && "Not a value extension");
  588. if (isFullSet() || isUpperWrapped()) {
  589. // Change into [0, 1 << src bit width)
  590. APInt LowerExt(DstTySize, 0);
  591. if (!Upper) // special case: [X, 0) -- not really wrapping around
  592. LowerExt = Lower.zext(DstTySize);
  593. return ConstantRange(std::move(LowerExt),
  594. APInt::getOneBitSet(DstTySize, SrcTySize));
  595. }
  596. return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
  597. }
  598. ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
  599. if (isEmptySet()) return getEmpty(DstTySize);
  600. unsigned SrcTySize = getBitWidth();
  601. assert(SrcTySize < DstTySize && "Not a value extension");
  602. // special case: [X, INT_MIN) -- not really wrapping around
  603. if (Upper.isMinSignedValue())
  604. return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
  605. if (isFullSet() || isSignWrappedSet()) {
  606. return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
  607. APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
  608. }
  609. return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
  610. }
  611. ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
  612. assert(getBitWidth() > DstTySize && "Not a value truncation");
  613. if (isEmptySet())
  614. return getEmpty(DstTySize);
  615. if (isFullSet())
  616. return getFull(DstTySize);
  617. APInt LowerDiv(Lower), UpperDiv(Upper);
  618. ConstantRange Union(DstTySize, /*isFullSet=*/false);
  619. // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
  620. // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
  621. // then we do the union with [MaxValue, Upper)
  622. if (isUpperWrapped()) {
  623. // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
  624. // truncated range.
  625. if (Upper.getActiveBits() > DstTySize ||
  626. Upper.countTrailingOnes() == DstTySize)
  627. return getFull(DstTySize);
  628. Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
  629. UpperDiv.setAllBits();
  630. // Union covers the MaxValue case, so return if the remaining range is just
  631. // MaxValue(DstTy).
  632. if (LowerDiv == UpperDiv)
  633. return Union;
  634. }
  635. // Chop off the most significant bits that are past the destination bitwidth.
  636. if (LowerDiv.getActiveBits() > DstTySize) {
  637. // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
  638. APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
  639. LowerDiv -= Adjust;
  640. UpperDiv -= Adjust;
  641. }
  642. unsigned UpperDivWidth = UpperDiv.getActiveBits();
  643. if (UpperDivWidth <= DstTySize)
  644. return ConstantRange(LowerDiv.trunc(DstTySize),
  645. UpperDiv.trunc(DstTySize)).unionWith(Union);
  646. // The truncated value wraps around. Check if we can do better than fullset.
  647. if (UpperDivWidth == DstTySize + 1) {
  648. // Clear the MSB so that UpperDiv wraps around.
  649. UpperDiv.clearBit(DstTySize);
  650. if (UpperDiv.ult(LowerDiv))
  651. return ConstantRange(LowerDiv.trunc(DstTySize),
  652. UpperDiv.trunc(DstTySize)).unionWith(Union);
  653. }
  654. return getFull(DstTySize);
  655. }
  656. ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
  657. unsigned SrcTySize = getBitWidth();
  658. if (SrcTySize > DstTySize)
  659. return truncate(DstTySize);
  660. if (SrcTySize < DstTySize)
  661. return zeroExtend(DstTySize);
  662. return *this;
  663. }
  664. ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
  665. unsigned SrcTySize = getBitWidth();
  666. if (SrcTySize > DstTySize)
  667. return truncate(DstTySize);
  668. if (SrcTySize < DstTySize)
  669. return signExtend(DstTySize);
  670. return *this;
  671. }
  672. ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
  673. const ConstantRange &Other) const {
  674. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  675. switch (BinOp) {
  676. case Instruction::Add:
  677. return add(Other);
  678. case Instruction::Sub:
  679. return sub(Other);
  680. case Instruction::Mul:
  681. return multiply(Other);
  682. case Instruction::UDiv:
  683. return udiv(Other);
  684. case Instruction::SDiv:
  685. return sdiv(Other);
  686. case Instruction::URem:
  687. return urem(Other);
  688. case Instruction::SRem:
  689. return srem(Other);
  690. case Instruction::Shl:
  691. return shl(Other);
  692. case Instruction::LShr:
  693. return lshr(Other);
  694. case Instruction::AShr:
  695. return ashr(Other);
  696. case Instruction::And:
  697. return binaryAnd(Other);
  698. case Instruction::Or:
  699. return binaryOr(Other);
  700. case Instruction::Xor:
  701. return binaryXor(Other);
  702. // Note: floating point operations applied to abstract ranges are just
  703. // ideal integer operations with a lossy representation
  704. case Instruction::FAdd:
  705. return add(Other);
  706. case Instruction::FSub:
  707. return sub(Other);
  708. case Instruction::FMul:
  709. return multiply(Other);
  710. default:
  711. // Conservatively return getFull set.
  712. return getFull();
  713. }
  714. }
  715. ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,
  716. const ConstantRange &Other,
  717. unsigned NoWrapKind) const {
  718. assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
  719. switch (BinOp) {
  720. case Instruction::Add:
  721. return addWithNoWrap(Other, NoWrapKind);
  722. case Instruction::Sub:
  723. return subWithNoWrap(Other, NoWrapKind);
  724. default:
  725. // Don't know about this Overflowing Binary Operation.
  726. // Conservatively fallback to plain binop handling.
  727. return binaryOp(BinOp, Other);
  728. }
  729. }
  730. bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {
  731. switch (IntrinsicID) {
  732. case Intrinsic::uadd_sat:
  733. case Intrinsic::usub_sat:
  734. case Intrinsic::sadd_sat:
  735. case Intrinsic::ssub_sat:
  736. case Intrinsic::umin:
  737. case Intrinsic::umax:
  738. case Intrinsic::smin:
  739. case Intrinsic::smax:
  740. case Intrinsic::abs:
  741. return true;
  742. default:
  743. return false;
  744. }
  745. }
  746. ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,
  747. ArrayRef<ConstantRange> Ops) {
  748. switch (IntrinsicID) {
  749. case Intrinsic::uadd_sat:
  750. return Ops[0].uadd_sat(Ops[1]);
  751. case Intrinsic::usub_sat:
  752. return Ops[0].usub_sat(Ops[1]);
  753. case Intrinsic::sadd_sat:
  754. return Ops[0].sadd_sat(Ops[1]);
  755. case Intrinsic::ssub_sat:
  756. return Ops[0].ssub_sat(Ops[1]);
  757. case Intrinsic::umin:
  758. return Ops[0].umin(Ops[1]);
  759. case Intrinsic::umax:
  760. return Ops[0].umax(Ops[1]);
  761. case Intrinsic::smin:
  762. return Ops[0].smin(Ops[1]);
  763. case Intrinsic::smax:
  764. return Ops[0].smax(Ops[1]);
  765. case Intrinsic::abs: {
  766. const APInt *IntMinIsPoison = Ops[1].getSingleElement();
  767. assert(IntMinIsPoison && "Must be known (immarg)");
  768. assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
  769. return Ops[0].abs(IntMinIsPoison->getBoolValue());
  770. }
  771. default:
  772. assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
  773. llvm_unreachable("Unsupported intrinsic");
  774. }
  775. }
  776. ConstantRange
  777. ConstantRange::add(const ConstantRange &Other) const {
  778. if (isEmptySet() || Other.isEmptySet())
  779. return getEmpty();
  780. if (isFullSet() || Other.isFullSet())
  781. return getFull();
  782. APInt NewLower = getLower() + Other.getLower();
  783. APInt NewUpper = getUpper() + Other.getUpper() - 1;
  784. if (NewLower == NewUpper)
  785. return getFull();
  786. ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
  787. if (X.isSizeStrictlySmallerThan(*this) ||
  788. X.isSizeStrictlySmallerThan(Other))
  789. // We've wrapped, therefore, full set.
  790. return getFull();
  791. return X;
  792. }
  793. ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,
  794. unsigned NoWrapKind,
  795. PreferredRangeType RangeType) const {
  796. // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
  797. // (X is from this, and Y is from Other)
  798. if (isEmptySet() || Other.isEmptySet())
  799. return getEmpty();
  800. if (isFullSet() && Other.isFullSet())
  801. return getFull();
  802. using OBO = OverflowingBinaryOperator;
  803. ConstantRange Result = add(Other);
  804. // If an overflow happens for every value pair in these two constant ranges,
  805. // we must return Empty set. In this case, we get that for free, because we
  806. // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
  807. // in an empty set.
  808. if (NoWrapKind & OBO::NoSignedWrap)
  809. Result = Result.intersectWith(sadd_sat(Other), RangeType);
  810. if (NoWrapKind & OBO::NoUnsignedWrap)
  811. Result = Result.intersectWith(uadd_sat(Other), RangeType);
  812. return Result;
  813. }
  814. ConstantRange
  815. ConstantRange::sub(const ConstantRange &Other) const {
  816. if (isEmptySet() || Other.isEmptySet())
  817. return getEmpty();
  818. if (isFullSet() || Other.isFullSet())
  819. return getFull();
  820. APInt NewLower = getLower() - Other.getUpper() + 1;
  821. APInt NewUpper = getUpper() - Other.getLower();
  822. if (NewLower == NewUpper)
  823. return getFull();
  824. ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
  825. if (X.isSizeStrictlySmallerThan(*this) ||
  826. X.isSizeStrictlySmallerThan(Other))
  827. // We've wrapped, therefore, full set.
  828. return getFull();
  829. return X;
  830. }
  831. ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,
  832. unsigned NoWrapKind,
  833. PreferredRangeType RangeType) const {
  834. // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
  835. // (X is from this, and Y is from Other)
  836. if (isEmptySet() || Other.isEmptySet())
  837. return getEmpty();
  838. if (isFullSet() && Other.isFullSet())
  839. return getFull();
  840. using OBO = OverflowingBinaryOperator;
  841. ConstantRange Result = sub(Other);
  842. // If an overflow happens for every value pair in these two constant ranges,
  843. // we must return Empty set. In signed case, we get that for free, because we
  844. // get lucky that intersection of sub() with ssub_sat() results in an
  845. // empty set. But for unsigned we must perform the overflow check manually.
  846. if (NoWrapKind & OBO::NoSignedWrap)
  847. Result = Result.intersectWith(ssub_sat(Other), RangeType);
  848. if (NoWrapKind & OBO::NoUnsignedWrap) {
  849. if (getUnsignedMax().ult(Other.getUnsignedMin()))
  850. return getEmpty(); // Always overflows.
  851. Result = Result.intersectWith(usub_sat(Other), RangeType);
  852. }
  853. return Result;
  854. }
  855. ConstantRange
  856. ConstantRange::multiply(const ConstantRange &Other) const {
  857. // TODO: If either operand is a single element and the multiply is known to
  858. // be non-wrapping, round the result min and max value to the appropriate
  859. // multiple of that element. If wrapping is possible, at least adjust the
  860. // range according to the greatest power-of-two factor of the single element.
  861. if (isEmptySet() || Other.isEmptySet())
  862. return getEmpty();
  863. // Multiplication is signedness-independent. However different ranges can be
  864. // obtained depending on how the input ranges are treated. These different
  865. // ranges are all conservatively correct, but one might be better than the
  866. // other. We calculate two ranges; one treating the inputs as unsigned
  867. // and the other signed, then return the smallest of these ranges.
  868. // Unsigned range first.
  869. APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
  870. APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
  871. APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
  872. APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
  873. ConstantRange Result_zext = ConstantRange(this_min * Other_min,
  874. this_max * Other_max + 1);
  875. ConstantRange UR = Result_zext.truncate(getBitWidth());
  876. // If the unsigned range doesn't wrap, and isn't negative then it's a range
  877. // from one positive number to another which is as good as we can generate.
  878. // In this case, skip the extra work of generating signed ranges which aren't
  879. // going to be better than this range.
  880. if (!UR.isUpperWrapped() &&
  881. (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
  882. return UR;
  883. // Now the signed range. Because we could be dealing with negative numbers
  884. // here, the lower bound is the smallest of the cartesian product of the
  885. // lower and upper ranges; for example:
  886. // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
  887. // Similarly for the upper bound, swapping min for max.
  888. this_min = getSignedMin().sext(getBitWidth() * 2);
  889. this_max = getSignedMax().sext(getBitWidth() * 2);
  890. Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
  891. Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
  892. auto L = {this_min * Other_min, this_min * Other_max,
  893. this_max * Other_min, this_max * Other_max};
  894. auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
  895. ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
  896. ConstantRange SR = Result_sext.truncate(getBitWidth());
  897. return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
  898. }
  899. ConstantRange
  900. ConstantRange::smax(const ConstantRange &Other) const {
  901. // X smax Y is: range(smax(X_smin, Y_smin),
  902. // smax(X_smax, Y_smax))
  903. if (isEmptySet() || Other.isEmptySet())
  904. return getEmpty();
  905. APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
  906. APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
  907. return getNonEmpty(std::move(NewL), std::move(NewU));
  908. }
  909. ConstantRange
  910. ConstantRange::umax(const ConstantRange &Other) const {
  911. // X umax Y is: range(umax(X_umin, Y_umin),
  912. // umax(X_umax, Y_umax))
  913. if (isEmptySet() || Other.isEmptySet())
  914. return getEmpty();
  915. APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
  916. APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
  917. return getNonEmpty(std::move(NewL), std::move(NewU));
  918. }
  919. ConstantRange
  920. ConstantRange::smin(const ConstantRange &Other) const {
  921. // X smin Y is: range(smin(X_smin, Y_smin),
  922. // smin(X_smax, Y_smax))
  923. if (isEmptySet() || Other.isEmptySet())
  924. return getEmpty();
  925. APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
  926. APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
  927. return getNonEmpty(std::move(NewL), std::move(NewU));
  928. }
  929. ConstantRange
  930. ConstantRange::umin(const ConstantRange &Other) const {
  931. // X umin Y is: range(umin(X_umin, Y_umin),
  932. // umin(X_umax, Y_umax))
  933. if (isEmptySet() || Other.isEmptySet())
  934. return getEmpty();
  935. APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
  936. APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
  937. return getNonEmpty(std::move(NewL), std::move(NewU));
  938. }
  939. ConstantRange
  940. ConstantRange::udiv(const ConstantRange &RHS) const {
  941. if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
  942. return getEmpty();
  943. APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
  944. APInt RHS_umin = RHS.getUnsignedMin();
  945. if (RHS_umin.isNullValue()) {
  946. // We want the lowest value in RHS excluding zero. Usually that would be 1
  947. // except for a range in the form of [X, 1) in which case it would be X.
  948. if (RHS.getUpper() == 1)
  949. RHS_umin = RHS.getLower();
  950. else
  951. RHS_umin = 1;
  952. }
  953. APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
  954. return getNonEmpty(std::move(Lower), std::move(Upper));
  955. }
  956. ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
  957. // We split up the LHS and RHS into positive and negative components
  958. // and then also compute the positive and negative components of the result
  959. // separately by combining division results with the appropriate signs.
  960. APInt Zero = APInt::getNullValue(getBitWidth());
  961. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  962. ConstantRange PosFilter(APInt(getBitWidth(), 1), SignedMin);
  963. ConstantRange NegFilter(SignedMin, Zero);
  964. ConstantRange PosL = intersectWith(PosFilter);
  965. ConstantRange NegL = intersectWith(NegFilter);
  966. ConstantRange PosR = RHS.intersectWith(PosFilter);
  967. ConstantRange NegR = RHS.intersectWith(NegFilter);
  968. ConstantRange PosRes = getEmpty();
  969. if (!PosL.isEmptySet() && !PosR.isEmptySet())
  970. // pos / pos = pos.
  971. PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
  972. (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
  973. if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
  974. // neg / neg = pos.
  975. //
  976. // We need to deal with one tricky case here: SignedMin / -1 is UB on the
  977. // IR level, so we'll want to exclude this case when calculating bounds.
  978. // (For APInts the operation is well-defined and yields SignedMin.) We
  979. // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
  980. APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
  981. if (NegL.Lower.isMinSignedValue() && NegR.Upper.isNullValue()) {
  982. // Remove -1 from the LHS. Skip if it's the only element, as this would
  983. // leave us with an empty set.
  984. if (!NegR.Lower.isAllOnesValue()) {
  985. APInt AdjNegRUpper;
  986. if (RHS.Lower.isAllOnesValue())
  987. // Negative part of [-1, X] without -1 is [SignedMin, X].
  988. AdjNegRUpper = RHS.Upper;
  989. else
  990. // [X, -1] without -1 is [X, -2].
  991. AdjNegRUpper = NegR.Upper - 1;
  992. PosRes = PosRes.unionWith(
  993. ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
  994. }
  995. // Remove SignedMin from the RHS. Skip if it's the only element, as this
  996. // would leave us with an empty set.
  997. if (NegL.Upper != SignedMin + 1) {
  998. APInt AdjNegLLower;
  999. if (Upper == SignedMin + 1)
  1000. // Negative part of [X, SignedMin] without SignedMin is [X, -1].
  1001. AdjNegLLower = Lower;
  1002. else
  1003. // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
  1004. AdjNegLLower = NegL.Lower + 1;
  1005. PosRes = PosRes.unionWith(
  1006. ConstantRange(std::move(Lo),
  1007. AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
  1008. }
  1009. } else {
  1010. PosRes = PosRes.unionWith(
  1011. ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
  1012. }
  1013. }
  1014. ConstantRange NegRes = getEmpty();
  1015. if (!PosL.isEmptySet() && !NegR.isEmptySet())
  1016. // pos / neg = neg.
  1017. NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
  1018. PosL.Lower.sdiv(NegR.Lower) + 1);
  1019. if (!NegL.isEmptySet() && !PosR.isEmptySet())
  1020. // neg / pos = neg.
  1021. NegRes = NegRes.unionWith(
  1022. ConstantRange(NegL.Lower.sdiv(PosR.Lower),
  1023. (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
  1024. // Prefer a non-wrapping signed range here.
  1025. ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);
  1026. // Preserve the zero that we dropped when splitting the LHS by sign.
  1027. if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
  1028. Res = Res.unionWith(ConstantRange(Zero));
  1029. return Res;
  1030. }
  1031. ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
  1032. if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
  1033. return getEmpty();
  1034. // L % R for L < R is L.
  1035. if (getUnsignedMax().ult(RHS.getUnsignedMin()))
  1036. return *this;
  1037. // L % R is <= L and < R.
  1038. APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
  1039. return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(Upper));
  1040. }
  1041. ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
  1042. if (isEmptySet() || RHS.isEmptySet())
  1043. return getEmpty();
  1044. ConstantRange AbsRHS = RHS.abs();
  1045. APInt MinAbsRHS = AbsRHS.getUnsignedMin();
  1046. APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
  1047. // Modulus by zero is UB.
  1048. if (MaxAbsRHS.isNullValue())
  1049. return getEmpty();
  1050. if (MinAbsRHS.isNullValue())
  1051. ++MinAbsRHS;
  1052. APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
  1053. if (MinLHS.isNonNegative()) {
  1054. // L % R for L < R is L.
  1055. if (MaxLHS.ult(MinAbsRHS))
  1056. return *this;
  1057. // L % R is <= L and < R.
  1058. APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
  1059. return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(Upper));
  1060. }
  1061. // Same basic logic as above, but the result is negative.
  1062. if (MaxLHS.isNegative()) {
  1063. if (MinLHS.ugt(-MinAbsRHS))
  1064. return *this;
  1065. APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
  1066. return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
  1067. }
  1068. // LHS range crosses zero.
  1069. APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
  1070. APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
  1071. return ConstantRange(std::move(Lower), std::move(Upper));
  1072. }
  1073. ConstantRange ConstantRange::binaryNot() const {
  1074. if (isEmptySet())
  1075. return getEmpty();
  1076. if (isWrappedSet())
  1077. return getFull();
  1078. return ConstantRange(APInt::getAllOnesValue(getBitWidth())).sub(*this);
  1079. }
  1080. ConstantRange
  1081. ConstantRange::binaryAnd(const ConstantRange &Other) const {
  1082. if (isEmptySet() || Other.isEmptySet())
  1083. return getEmpty();
  1084. // Use APInt's implementation of AND for single element ranges.
  1085. if (isSingleElement() && Other.isSingleElement())
  1086. return {*getSingleElement() & *Other.getSingleElement()};
  1087. // TODO: replace this with something less conservative
  1088. APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
  1089. return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
  1090. }
  1091. ConstantRange
  1092. ConstantRange::binaryOr(const ConstantRange &Other) const {
  1093. if (isEmptySet() || Other.isEmptySet())
  1094. return getEmpty();
  1095. // Use APInt's implementation of OR for single element ranges.
  1096. if (isSingleElement() && Other.isSingleElement())
  1097. return {*getSingleElement() | *Other.getSingleElement()};
  1098. // TODO: replace this with something less conservative
  1099. APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
  1100. return getNonEmpty(std::move(umax), APInt::getNullValue(getBitWidth()));
  1101. }
  1102. ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {
  1103. if (isEmptySet() || Other.isEmptySet())
  1104. return getEmpty();
  1105. // Use APInt's implementation of XOR for single element ranges.
  1106. if (isSingleElement() && Other.isSingleElement())
  1107. return {*getSingleElement() ^ *Other.getSingleElement()};
  1108. // Special-case binary complement, since we can give a precise answer.
  1109. if (Other.isSingleElement() && Other.getSingleElement()->isAllOnesValue())
  1110. return binaryNot();
  1111. if (isSingleElement() && getSingleElement()->isAllOnesValue())
  1112. return Other.binaryNot();
  1113. // TODO: replace this with something less conservative
  1114. return getFull();
  1115. }
  1116. ConstantRange
  1117. ConstantRange::shl(const ConstantRange &Other) const {
  1118. if (isEmptySet() || Other.isEmptySet())
  1119. return getEmpty();
  1120. APInt max = getUnsignedMax();
  1121. APInt Other_umax = Other.getUnsignedMax();
  1122. // If we are shifting by maximum amount of
  1123. // zero return return the original range.
  1124. if (Other_umax.isNullValue())
  1125. return *this;
  1126. // there's overflow!
  1127. if (Other_umax.ugt(max.countLeadingZeros()))
  1128. return getFull();
  1129. // FIXME: implement the other tricky cases
  1130. APInt min = getUnsignedMin();
  1131. min <<= Other.getUnsignedMin();
  1132. max <<= Other_umax;
  1133. return ConstantRange(std::move(min), std::move(max) + 1);
  1134. }
  1135. ConstantRange
  1136. ConstantRange::lshr(const ConstantRange &Other) const {
  1137. if (isEmptySet() || Other.isEmptySet())
  1138. return getEmpty();
  1139. APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
  1140. APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
  1141. return getNonEmpty(std::move(min), std::move(max));
  1142. }
  1143. ConstantRange
  1144. ConstantRange::ashr(const ConstantRange &Other) const {
  1145. if (isEmptySet() || Other.isEmptySet())
  1146. return getEmpty();
  1147. // May straddle zero, so handle both positive and negative cases.
  1148. // 'PosMax' is the upper bound of the result of the ashr
  1149. // operation, when Upper of the LHS of ashr is a non-negative.
  1150. // number. Since ashr of a non-negative number will result in a
  1151. // smaller number, the Upper value of LHS is shifted right with
  1152. // the minimum value of 'Other' instead of the maximum value.
  1153. APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
  1154. // 'PosMin' is the lower bound of the result of the ashr
  1155. // operation, when Lower of the LHS is a non-negative number.
  1156. // Since ashr of a non-negative number will result in a smaller
  1157. // number, the Lower value of LHS is shifted right with the
  1158. // maximum value of 'Other'.
  1159. APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
  1160. // 'NegMax' is the upper bound of the result of the ashr
  1161. // operation, when Upper of the LHS of ashr is a negative number.
  1162. // Since 'ashr' of a negative number will result in a bigger
  1163. // number, the Upper value of LHS is shifted right with the
  1164. // maximum value of 'Other'.
  1165. APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
  1166. // 'NegMin' is the lower bound of the result of the ashr
  1167. // operation, when Lower of the LHS of ashr is a negative number.
  1168. // Since 'ashr' of a negative number will result in a bigger
  1169. // number, the Lower value of LHS is shifted right with the
  1170. // minimum value of 'Other'.
  1171. APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
  1172. APInt max, min;
  1173. if (getSignedMin().isNonNegative()) {
  1174. // Upper and Lower of LHS are non-negative.
  1175. min = PosMin;
  1176. max = PosMax;
  1177. } else if (getSignedMax().isNegative()) {
  1178. // Upper and Lower of LHS are negative.
  1179. min = NegMin;
  1180. max = NegMax;
  1181. } else {
  1182. // Upper is non-negative and Lower is negative.
  1183. min = NegMin;
  1184. max = PosMax;
  1185. }
  1186. return getNonEmpty(std::move(min), std::move(max));
  1187. }
  1188. ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
  1189. if (isEmptySet() || Other.isEmptySet())
  1190. return getEmpty();
  1191. APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
  1192. APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
  1193. return getNonEmpty(std::move(NewL), std::move(NewU));
  1194. }
  1195. ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
  1196. if (isEmptySet() || Other.isEmptySet())
  1197. return getEmpty();
  1198. APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
  1199. APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
  1200. return getNonEmpty(std::move(NewL), std::move(NewU));
  1201. }
  1202. ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
  1203. if (isEmptySet() || Other.isEmptySet())
  1204. return getEmpty();
  1205. APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
  1206. APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
  1207. return getNonEmpty(std::move(NewL), std::move(NewU));
  1208. }
  1209. ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
  1210. if (isEmptySet() || Other.isEmptySet())
  1211. return getEmpty();
  1212. APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
  1213. APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
  1214. return getNonEmpty(std::move(NewL), std::move(NewU));
  1215. }
  1216. ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {
  1217. if (isEmptySet() || Other.isEmptySet())
  1218. return getEmpty();
  1219. APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());
  1220. APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;
  1221. return getNonEmpty(std::move(NewL), std::move(NewU));
  1222. }
  1223. ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {
  1224. if (isEmptySet() || Other.isEmptySet())
  1225. return getEmpty();
  1226. // Because we could be dealing with negative numbers here, the lower bound is
  1227. // the smallest of the cartesian product of the lower and upper ranges;
  1228. // for example:
  1229. // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
  1230. // Similarly for the upper bound, swapping min for max.
  1231. APInt this_min = getSignedMin().sext(getBitWidth() * 2);
  1232. APInt this_max = getSignedMax().sext(getBitWidth() * 2);
  1233. APInt Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
  1234. APInt Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
  1235. auto L = {this_min * Other_min, this_min * Other_max, this_max * Other_min,
  1236. this_max * Other_max};
  1237. auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
  1238. // Note that we wanted to perform signed saturating multiplication,
  1239. // so since we performed plain multiplication in twice the bitwidth,
  1240. // we need to perform signed saturating truncation.
  1241. return getNonEmpty(std::min(L, Compare).truncSSat(getBitWidth()),
  1242. std::max(L, Compare).truncSSat(getBitWidth()) + 1);
  1243. }
  1244. ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {
  1245. if (isEmptySet() || Other.isEmptySet())
  1246. return getEmpty();
  1247. APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());
  1248. APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;
  1249. return getNonEmpty(std::move(NewL), std::move(NewU));
  1250. }
  1251. ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {
  1252. if (isEmptySet() || Other.isEmptySet())
  1253. return getEmpty();
  1254. APInt Min = getSignedMin(), Max = getSignedMax();
  1255. APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
  1256. APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);
  1257. APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
  1258. return getNonEmpty(std::move(NewL), std::move(NewU));
  1259. }
  1260. ConstantRange ConstantRange::inverse() const {
  1261. if (isFullSet())
  1262. return getEmpty();
  1263. if (isEmptySet())
  1264. return getFull();
  1265. return ConstantRange(Upper, Lower);
  1266. }
  1267. ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
  1268. if (isEmptySet())
  1269. return getEmpty();
  1270. if (isSignWrappedSet()) {
  1271. APInt Lo;
  1272. // Check whether the range crosses zero.
  1273. if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
  1274. Lo = APInt::getNullValue(getBitWidth());
  1275. else
  1276. Lo = APIntOps::umin(Lower, -Upper + 1);
  1277. // If SignedMin is not poison, then it is included in the result range.
  1278. if (IntMinIsPoison)
  1279. return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()));
  1280. else
  1281. return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
  1282. }
  1283. APInt SMin = getSignedMin(), SMax = getSignedMax();
  1284. // Skip SignedMin if it is poison.
  1285. if (IntMinIsPoison && SMin.isMinSignedValue()) {
  1286. // The range may become empty if it *only* contains SignedMin.
  1287. if (SMax.isMinSignedValue())
  1288. return getEmpty();
  1289. ++SMin;
  1290. }
  1291. // All non-negative.
  1292. if (SMin.isNonNegative())
  1293. return *this;
  1294. // All negative.
  1295. if (SMax.isNegative())
  1296. return ConstantRange(-SMax, -SMin + 1);
  1297. // Range crosses zero.
  1298. return ConstantRange(APInt::getNullValue(getBitWidth()),
  1299. APIntOps::umax(-SMin, SMax) + 1);
  1300. }
  1301. ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
  1302. const ConstantRange &Other) const {
  1303. if (isEmptySet() || Other.isEmptySet())
  1304. return OverflowResult::MayOverflow;
  1305. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1306. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1307. // a u+ b overflows high iff a u> ~b.
  1308. if (Min.ugt(~OtherMin))
  1309. return OverflowResult::AlwaysOverflowsHigh;
  1310. if (Max.ugt(~OtherMax))
  1311. return OverflowResult::MayOverflow;
  1312. return OverflowResult::NeverOverflows;
  1313. }
  1314. ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
  1315. const ConstantRange &Other) const {
  1316. if (isEmptySet() || Other.isEmptySet())
  1317. return OverflowResult::MayOverflow;
  1318. APInt Min = getSignedMin(), Max = getSignedMax();
  1319. APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
  1320. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  1321. APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
  1322. // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
  1323. // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
  1324. if (Min.isNonNegative() && OtherMin.isNonNegative() &&
  1325. Min.sgt(SignedMax - OtherMin))
  1326. return OverflowResult::AlwaysOverflowsHigh;
  1327. if (Max.isNegative() && OtherMax.isNegative() &&
  1328. Max.slt(SignedMin - OtherMax))
  1329. return OverflowResult::AlwaysOverflowsLow;
  1330. if (Max.isNonNegative() && OtherMax.isNonNegative() &&
  1331. Max.sgt(SignedMax - OtherMax))
  1332. return OverflowResult::MayOverflow;
  1333. if (Min.isNegative() && OtherMin.isNegative() &&
  1334. Min.slt(SignedMin - OtherMin))
  1335. return OverflowResult::MayOverflow;
  1336. return OverflowResult::NeverOverflows;
  1337. }
  1338. ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
  1339. const ConstantRange &Other) const {
  1340. if (isEmptySet() || Other.isEmptySet())
  1341. return OverflowResult::MayOverflow;
  1342. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1343. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1344. // a u- b overflows low iff a u< b.
  1345. if (Max.ult(OtherMin))
  1346. return OverflowResult::AlwaysOverflowsLow;
  1347. if (Min.ult(OtherMax))
  1348. return OverflowResult::MayOverflow;
  1349. return OverflowResult::NeverOverflows;
  1350. }
  1351. ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
  1352. const ConstantRange &Other) const {
  1353. if (isEmptySet() || Other.isEmptySet())
  1354. return OverflowResult::MayOverflow;
  1355. APInt Min = getSignedMin(), Max = getSignedMax();
  1356. APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
  1357. APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
  1358. APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
  1359. // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
  1360. // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
  1361. if (Min.isNonNegative() && OtherMax.isNegative() &&
  1362. Min.sgt(SignedMax + OtherMax))
  1363. return OverflowResult::AlwaysOverflowsHigh;
  1364. if (Max.isNegative() && OtherMin.isNonNegative() &&
  1365. Max.slt(SignedMin + OtherMin))
  1366. return OverflowResult::AlwaysOverflowsLow;
  1367. if (Max.isNonNegative() && OtherMin.isNegative() &&
  1368. Max.sgt(SignedMax + OtherMin))
  1369. return OverflowResult::MayOverflow;
  1370. if (Min.isNegative() && OtherMax.isNonNegative() &&
  1371. Min.slt(SignedMin + OtherMax))
  1372. return OverflowResult::MayOverflow;
  1373. return OverflowResult::NeverOverflows;
  1374. }
  1375. ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
  1376. const ConstantRange &Other) const {
  1377. if (isEmptySet() || Other.isEmptySet())
  1378. return OverflowResult::MayOverflow;
  1379. APInt Min = getUnsignedMin(), Max = getUnsignedMax();
  1380. APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
  1381. bool Overflow;
  1382. (void) Min.umul_ov(OtherMin, Overflow);
  1383. if (Overflow)
  1384. return OverflowResult::AlwaysOverflowsHigh;
  1385. (void) Max.umul_ov(OtherMax, Overflow);
  1386. if (Overflow)
  1387. return OverflowResult::MayOverflow;
  1388. return OverflowResult::NeverOverflows;
  1389. }
  1390. void ConstantRange::print(raw_ostream &OS) const {
  1391. if (isFullSet())
  1392. OS << "full-set";
  1393. else if (isEmptySet())
  1394. OS << "empty-set";
  1395. else
  1396. OS << "[" << Lower << "," << Upper << ")";
  1397. }
  1398. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1399. LLVM_DUMP_METHOD void ConstantRange::dump() const {
  1400. print(dbgs());
  1401. }
  1402. #endif
  1403. ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
  1404. const unsigned NumRanges = Ranges.getNumOperands() / 2;
  1405. assert(NumRanges >= 1 && "Must have at least one range!");
  1406. assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
  1407. auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
  1408. auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
  1409. ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
  1410. for (unsigned i = 1; i < NumRanges; ++i) {
  1411. auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
  1412. auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
  1413. // Note: unionWith will potentially create a range that contains values not
  1414. // contained in any of the original N ranges.
  1415. CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
  1416. }
  1417. return CR;
  1418. }