ConstantRange.cpp 61 KB

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