KnownBits.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. //===-- KnownBits.cpp - Stores known zeros/ones ---------------------------===//
  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. // This file contains a class for representing known zeros and ones used by
  10. // computeKnownBits.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Support/KnownBits.h"
  14. #include "llvm/Support/Debug.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include <cassert>
  17. using namespace llvm;
  18. static KnownBits computeForAddCarry(
  19. const KnownBits &LHS, const KnownBits &RHS,
  20. bool CarryZero, bool CarryOne) {
  21. assert(!(CarryZero && CarryOne) &&
  22. "Carry can't be zero and one at the same time");
  23. APInt PossibleSumZero = LHS.getMaxValue() + RHS.getMaxValue() + !CarryZero;
  24. APInt PossibleSumOne = LHS.getMinValue() + RHS.getMinValue() + CarryOne;
  25. // Compute known bits of the carry.
  26. APInt CarryKnownZero = ~(PossibleSumZero ^ LHS.Zero ^ RHS.Zero);
  27. APInt CarryKnownOne = PossibleSumOne ^ LHS.One ^ RHS.One;
  28. // Compute set of known bits (where all three relevant bits are known).
  29. APInt LHSKnownUnion = LHS.Zero | LHS.One;
  30. APInt RHSKnownUnion = RHS.Zero | RHS.One;
  31. APInt CarryKnownUnion = std::move(CarryKnownZero) | CarryKnownOne;
  32. APInt Known = std::move(LHSKnownUnion) & RHSKnownUnion & CarryKnownUnion;
  33. assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
  34. "known bits of sum differ");
  35. // Compute known bits of the result.
  36. KnownBits KnownOut;
  37. KnownOut.Zero = ~std::move(PossibleSumZero) & Known;
  38. KnownOut.One = std::move(PossibleSumOne) & Known;
  39. return KnownOut;
  40. }
  41. KnownBits KnownBits::computeForAddCarry(
  42. const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry) {
  43. assert(Carry.getBitWidth() == 1 && "Carry must be 1-bit");
  44. return ::computeForAddCarry(
  45. LHS, RHS, Carry.Zero.getBoolValue(), Carry.One.getBoolValue());
  46. }
  47. KnownBits KnownBits::computeForAddSub(bool Add, bool NSW,
  48. const KnownBits &LHS, KnownBits RHS) {
  49. KnownBits KnownOut;
  50. if (Add) {
  51. // Sum = LHS + RHS + 0
  52. KnownOut = ::computeForAddCarry(
  53. LHS, RHS, /*CarryZero*/true, /*CarryOne*/false);
  54. } else {
  55. // Sum = LHS + ~RHS + 1
  56. std::swap(RHS.Zero, RHS.One);
  57. KnownOut = ::computeForAddCarry(
  58. LHS, RHS, /*CarryZero*/false, /*CarryOne*/true);
  59. }
  60. // Are we still trying to solve for the sign bit?
  61. if (!KnownOut.isNegative() && !KnownOut.isNonNegative()) {
  62. if (NSW) {
  63. // Adding two non-negative numbers, or subtracting a negative number from
  64. // a non-negative one, can't wrap into negative.
  65. if (LHS.isNonNegative() && RHS.isNonNegative())
  66. KnownOut.makeNonNegative();
  67. // Adding two negative numbers, or subtracting a non-negative number from
  68. // a negative one, can't wrap into non-negative.
  69. else if (LHS.isNegative() && RHS.isNegative())
  70. KnownOut.makeNegative();
  71. }
  72. }
  73. return KnownOut;
  74. }
  75. KnownBits KnownBits::sextInReg(unsigned SrcBitWidth) const {
  76. unsigned BitWidth = getBitWidth();
  77. assert(0 < SrcBitWidth && SrcBitWidth <= BitWidth &&
  78. "Illegal sext-in-register");
  79. if (SrcBitWidth == BitWidth)
  80. return *this;
  81. unsigned ExtBits = BitWidth - SrcBitWidth;
  82. KnownBits Result;
  83. Result.One = One << ExtBits;
  84. Result.Zero = Zero << ExtBits;
  85. Result.One.ashrInPlace(ExtBits);
  86. Result.Zero.ashrInPlace(ExtBits);
  87. return Result;
  88. }
  89. KnownBits KnownBits::makeGE(const APInt &Val) const {
  90. // Count the number of leading bit positions where our underlying value is
  91. // known to be less than or equal to Val.
  92. unsigned N = (Zero | Val).countLeadingOnes();
  93. // For each of those bit positions, if Val has a 1 in that bit then our
  94. // underlying value must also have a 1.
  95. APInt MaskedVal(Val);
  96. MaskedVal.clearLowBits(getBitWidth() - N);
  97. return KnownBits(Zero, One | MaskedVal);
  98. }
  99. KnownBits KnownBits::umax(const KnownBits &LHS, const KnownBits &RHS) {
  100. // If we can prove that LHS >= RHS then use LHS as the result. Likewise for
  101. // RHS. Ideally our caller would already have spotted these cases and
  102. // optimized away the umax operation, but we handle them here for
  103. // completeness.
  104. if (LHS.getMinValue().uge(RHS.getMaxValue()))
  105. return LHS;
  106. if (RHS.getMinValue().uge(LHS.getMaxValue()))
  107. return RHS;
  108. // If the result of the umax is LHS then it must be greater than or equal to
  109. // the minimum possible value of RHS. Likewise for RHS. Any known bits that
  110. // are common to these two values are also known in the result.
  111. KnownBits L = LHS.makeGE(RHS.getMinValue());
  112. KnownBits R = RHS.makeGE(LHS.getMinValue());
  113. return KnownBits::commonBits(L, R);
  114. }
  115. KnownBits KnownBits::umin(const KnownBits &LHS, const KnownBits &RHS) {
  116. // Flip the range of values: [0, 0xFFFFFFFF] <-> [0xFFFFFFFF, 0]
  117. auto Flip = [](const KnownBits &Val) { return KnownBits(Val.One, Val.Zero); };
  118. return Flip(umax(Flip(LHS), Flip(RHS)));
  119. }
  120. KnownBits KnownBits::smax(const KnownBits &LHS, const KnownBits &RHS) {
  121. // Flip the range of values: [-0x80000000, 0x7FFFFFFF] <-> [0, 0xFFFFFFFF]
  122. auto Flip = [](const KnownBits &Val) {
  123. unsigned SignBitPosition = Val.getBitWidth() - 1;
  124. APInt Zero = Val.Zero;
  125. APInt One = Val.One;
  126. Zero.setBitVal(SignBitPosition, Val.One[SignBitPosition]);
  127. One.setBitVal(SignBitPosition, Val.Zero[SignBitPosition]);
  128. return KnownBits(Zero, One);
  129. };
  130. return Flip(umax(Flip(LHS), Flip(RHS)));
  131. }
  132. KnownBits KnownBits::smin(const KnownBits &LHS, const KnownBits &RHS) {
  133. // Flip the range of values: [-0x80000000, 0x7FFFFFFF] <-> [0xFFFFFFFF, 0]
  134. auto Flip = [](const KnownBits &Val) {
  135. unsigned SignBitPosition = Val.getBitWidth() - 1;
  136. APInt Zero = Val.One;
  137. APInt One = Val.Zero;
  138. Zero.setBitVal(SignBitPosition, Val.Zero[SignBitPosition]);
  139. One.setBitVal(SignBitPosition, Val.One[SignBitPosition]);
  140. return KnownBits(Zero, One);
  141. };
  142. return Flip(umax(Flip(LHS), Flip(RHS)));
  143. }
  144. KnownBits KnownBits::shl(const KnownBits &LHS, const KnownBits &RHS) {
  145. unsigned BitWidth = LHS.getBitWidth();
  146. KnownBits Known(BitWidth);
  147. // If the shift amount is a valid constant then transform LHS directly.
  148. if (RHS.isConstant() && RHS.getConstant().ult(BitWidth)) {
  149. unsigned Shift = RHS.getConstant().getZExtValue();
  150. Known = LHS;
  151. Known.Zero <<= Shift;
  152. Known.One <<= Shift;
  153. // Low bits are known zero.
  154. Known.Zero.setLowBits(Shift);
  155. return Known;
  156. }
  157. // No matter the shift amount, the trailing zeros will stay zero.
  158. unsigned MinTrailingZeros = LHS.countMinTrailingZeros();
  159. // Minimum shift amount low bits are known zero.
  160. APInt MinShiftAmount = RHS.getMinValue();
  161. if (MinShiftAmount.ult(BitWidth)) {
  162. MinTrailingZeros += MinShiftAmount.getZExtValue();
  163. MinTrailingZeros = std::min(MinTrailingZeros, BitWidth);
  164. }
  165. // If the maximum shift is in range, then find the common bits from all
  166. // possible shifts.
  167. APInt MaxShiftAmount = RHS.getMaxValue();
  168. if (MaxShiftAmount.ult(BitWidth) && !LHS.isUnknown()) {
  169. uint64_t ShiftAmtZeroMask = (~RHS.Zero).getZExtValue();
  170. uint64_t ShiftAmtOneMask = RHS.One.getZExtValue();
  171. assert(MinShiftAmount.ult(MaxShiftAmount) && "Illegal shift range");
  172. Known.Zero.setAllBits();
  173. Known.One.setAllBits();
  174. for (uint64_t ShiftAmt = MinShiftAmount.getZExtValue(),
  175. MaxShiftAmt = MaxShiftAmount.getZExtValue();
  176. ShiftAmt <= MaxShiftAmt; ++ShiftAmt) {
  177. // Skip if the shift amount is impossible.
  178. if ((ShiftAmtZeroMask & ShiftAmt) != ShiftAmt ||
  179. (ShiftAmtOneMask | ShiftAmt) != ShiftAmt)
  180. continue;
  181. KnownBits SpecificShift;
  182. SpecificShift.Zero = LHS.Zero << ShiftAmt;
  183. SpecificShift.One = LHS.One << ShiftAmt;
  184. Known = KnownBits::commonBits(Known, SpecificShift);
  185. if (Known.isUnknown())
  186. break;
  187. }
  188. }
  189. Known.Zero.setLowBits(MinTrailingZeros);
  190. return Known;
  191. }
  192. KnownBits KnownBits::lshr(const KnownBits &LHS, const KnownBits &RHS) {
  193. unsigned BitWidth = LHS.getBitWidth();
  194. KnownBits Known(BitWidth);
  195. if (RHS.isConstant() && RHS.getConstant().ult(BitWidth)) {
  196. unsigned Shift = RHS.getConstant().getZExtValue();
  197. Known = LHS;
  198. Known.Zero.lshrInPlace(Shift);
  199. Known.One.lshrInPlace(Shift);
  200. // High bits are known zero.
  201. Known.Zero.setHighBits(Shift);
  202. return Known;
  203. }
  204. // No matter the shift amount, the leading zeros will stay zero.
  205. unsigned MinLeadingZeros = LHS.countMinLeadingZeros();
  206. // Minimum shift amount high bits are known zero.
  207. APInt MinShiftAmount = RHS.getMinValue();
  208. if (MinShiftAmount.ult(BitWidth)) {
  209. MinLeadingZeros += MinShiftAmount.getZExtValue();
  210. MinLeadingZeros = std::min(MinLeadingZeros, BitWidth);
  211. }
  212. // If the maximum shift is in range, then find the common bits from all
  213. // possible shifts.
  214. APInt MaxShiftAmount = RHS.getMaxValue();
  215. if (MaxShiftAmount.ult(BitWidth) && !LHS.isUnknown()) {
  216. uint64_t ShiftAmtZeroMask = (~RHS.Zero).getZExtValue();
  217. uint64_t ShiftAmtOneMask = RHS.One.getZExtValue();
  218. assert(MinShiftAmount.ult(MaxShiftAmount) && "Illegal shift range");
  219. Known.Zero.setAllBits();
  220. Known.One.setAllBits();
  221. for (uint64_t ShiftAmt = MinShiftAmount.getZExtValue(),
  222. MaxShiftAmt = MaxShiftAmount.getZExtValue();
  223. ShiftAmt <= MaxShiftAmt; ++ShiftAmt) {
  224. // Skip if the shift amount is impossible.
  225. if ((ShiftAmtZeroMask & ShiftAmt) != ShiftAmt ||
  226. (ShiftAmtOneMask | ShiftAmt) != ShiftAmt)
  227. continue;
  228. KnownBits SpecificShift = LHS;
  229. SpecificShift.Zero.lshrInPlace(ShiftAmt);
  230. SpecificShift.One.lshrInPlace(ShiftAmt);
  231. Known = KnownBits::commonBits(Known, SpecificShift);
  232. if (Known.isUnknown())
  233. break;
  234. }
  235. }
  236. Known.Zero.setHighBits(MinLeadingZeros);
  237. return Known;
  238. }
  239. KnownBits KnownBits::ashr(const KnownBits &LHS, const KnownBits &RHS) {
  240. unsigned BitWidth = LHS.getBitWidth();
  241. KnownBits Known(BitWidth);
  242. if (RHS.isConstant() && RHS.getConstant().ult(BitWidth)) {
  243. unsigned Shift = RHS.getConstant().getZExtValue();
  244. Known = LHS;
  245. Known.Zero.ashrInPlace(Shift);
  246. Known.One.ashrInPlace(Shift);
  247. return Known;
  248. }
  249. // No matter the shift amount, the leading sign bits will stay.
  250. unsigned MinLeadingZeros = LHS.countMinLeadingZeros();
  251. unsigned MinLeadingOnes = LHS.countMinLeadingOnes();
  252. // Minimum shift amount high bits are known sign bits.
  253. APInt MinShiftAmount = RHS.getMinValue();
  254. if (MinShiftAmount.ult(BitWidth)) {
  255. if (MinLeadingZeros) {
  256. MinLeadingZeros += MinShiftAmount.getZExtValue();
  257. MinLeadingZeros = std::min(MinLeadingZeros, BitWidth);
  258. }
  259. if (MinLeadingOnes) {
  260. MinLeadingOnes += MinShiftAmount.getZExtValue();
  261. MinLeadingOnes = std::min(MinLeadingOnes, BitWidth);
  262. }
  263. }
  264. // If the maximum shift is in range, then find the common bits from all
  265. // possible shifts.
  266. APInt MaxShiftAmount = RHS.getMaxValue();
  267. if (MaxShiftAmount.ult(BitWidth) && !LHS.isUnknown()) {
  268. uint64_t ShiftAmtZeroMask = (~RHS.Zero).getZExtValue();
  269. uint64_t ShiftAmtOneMask = RHS.One.getZExtValue();
  270. assert(MinShiftAmount.ult(MaxShiftAmount) && "Illegal shift range");
  271. Known.Zero.setAllBits();
  272. Known.One.setAllBits();
  273. for (uint64_t ShiftAmt = MinShiftAmount.getZExtValue(),
  274. MaxShiftAmt = MaxShiftAmount.getZExtValue();
  275. ShiftAmt <= MaxShiftAmt; ++ShiftAmt) {
  276. // Skip if the shift amount is impossible.
  277. if ((ShiftAmtZeroMask & ShiftAmt) != ShiftAmt ||
  278. (ShiftAmtOneMask | ShiftAmt) != ShiftAmt)
  279. continue;
  280. KnownBits SpecificShift = LHS;
  281. SpecificShift.Zero.ashrInPlace(ShiftAmt);
  282. SpecificShift.One.ashrInPlace(ShiftAmt);
  283. Known = KnownBits::commonBits(Known, SpecificShift);
  284. if (Known.isUnknown())
  285. break;
  286. }
  287. }
  288. Known.Zero.setHighBits(MinLeadingZeros);
  289. Known.One.setHighBits(MinLeadingOnes);
  290. return Known;
  291. }
  292. std::optional<bool> KnownBits::eq(const KnownBits &LHS, const KnownBits &RHS) {
  293. if (LHS.isConstant() && RHS.isConstant())
  294. return std::optional<bool>(LHS.getConstant() == RHS.getConstant());
  295. if (LHS.One.intersects(RHS.Zero) || RHS.One.intersects(LHS.Zero))
  296. return std::optional<bool>(false);
  297. return std::nullopt;
  298. }
  299. std::optional<bool> KnownBits::ne(const KnownBits &LHS, const KnownBits &RHS) {
  300. if (std::optional<bool> KnownEQ = eq(LHS, RHS))
  301. return std::optional<bool>(!*KnownEQ);
  302. return std::nullopt;
  303. }
  304. std::optional<bool> KnownBits::ugt(const KnownBits &LHS, const KnownBits &RHS) {
  305. // LHS >u RHS -> false if umax(LHS) <= umax(RHS)
  306. if (LHS.getMaxValue().ule(RHS.getMinValue()))
  307. return std::optional<bool>(false);
  308. // LHS >u RHS -> true if umin(LHS) > umax(RHS)
  309. if (LHS.getMinValue().ugt(RHS.getMaxValue()))
  310. return std::optional<bool>(true);
  311. return std::nullopt;
  312. }
  313. std::optional<bool> KnownBits::uge(const KnownBits &LHS, const KnownBits &RHS) {
  314. if (std::optional<bool> IsUGT = ugt(RHS, LHS))
  315. return std::optional<bool>(!*IsUGT);
  316. return std::nullopt;
  317. }
  318. std::optional<bool> KnownBits::ult(const KnownBits &LHS, const KnownBits &RHS) {
  319. return ugt(RHS, LHS);
  320. }
  321. std::optional<bool> KnownBits::ule(const KnownBits &LHS, const KnownBits &RHS) {
  322. return uge(RHS, LHS);
  323. }
  324. std::optional<bool> KnownBits::sgt(const KnownBits &LHS, const KnownBits &RHS) {
  325. // LHS >s RHS -> false if smax(LHS) <= smax(RHS)
  326. if (LHS.getSignedMaxValue().sle(RHS.getSignedMinValue()))
  327. return std::optional<bool>(false);
  328. // LHS >s RHS -> true if smin(LHS) > smax(RHS)
  329. if (LHS.getSignedMinValue().sgt(RHS.getSignedMaxValue()))
  330. return std::optional<bool>(true);
  331. return std::nullopt;
  332. }
  333. std::optional<bool> KnownBits::sge(const KnownBits &LHS, const KnownBits &RHS) {
  334. if (std::optional<bool> KnownSGT = sgt(RHS, LHS))
  335. return std::optional<bool>(!*KnownSGT);
  336. return std::nullopt;
  337. }
  338. std::optional<bool> KnownBits::slt(const KnownBits &LHS, const KnownBits &RHS) {
  339. return sgt(RHS, LHS);
  340. }
  341. std::optional<bool> KnownBits::sle(const KnownBits &LHS, const KnownBits &RHS) {
  342. return sge(RHS, LHS);
  343. }
  344. KnownBits KnownBits::abs(bool IntMinIsPoison) const {
  345. // If the source's MSB is zero then we know the rest of the bits already.
  346. if (isNonNegative())
  347. return *this;
  348. // Absolute value preserves trailing zero count.
  349. KnownBits KnownAbs(getBitWidth());
  350. KnownAbs.Zero.setLowBits(countMinTrailingZeros());
  351. // We only know that the absolute values's MSB will be zero if INT_MIN is
  352. // poison, or there is a set bit that isn't the sign bit (otherwise it could
  353. // be INT_MIN).
  354. if (IntMinIsPoison || (!One.isZero() && !One.isMinSignedValue()))
  355. KnownAbs.Zero.setSignBit();
  356. // FIXME: Handle known negative input?
  357. // FIXME: Calculate the negated Known bits and combine them?
  358. return KnownAbs;
  359. }
  360. KnownBits KnownBits::mul(const KnownBits &LHS, const KnownBits &RHS,
  361. bool NoUndefSelfMultiply) {
  362. unsigned BitWidth = LHS.getBitWidth();
  363. assert(BitWidth == RHS.getBitWidth() && !LHS.hasConflict() &&
  364. !RHS.hasConflict() && "Operand mismatch");
  365. assert((!NoUndefSelfMultiply || LHS == RHS) &&
  366. "Self multiplication knownbits mismatch");
  367. // Compute the high known-0 bits by multiplying the unsigned max of each side.
  368. // Conservatively, M active bits * N active bits results in M + N bits in the
  369. // result. But if we know a value is a power-of-2 for example, then this
  370. // computes one more leading zero.
  371. // TODO: This could be generalized to number of sign bits (negative numbers).
  372. APInt UMaxLHS = LHS.getMaxValue();
  373. APInt UMaxRHS = RHS.getMaxValue();
  374. // For leading zeros in the result to be valid, the unsigned max product must
  375. // fit in the bitwidth (it must not overflow).
  376. bool HasOverflow;
  377. APInt UMaxResult = UMaxLHS.umul_ov(UMaxRHS, HasOverflow);
  378. unsigned LeadZ = HasOverflow ? 0 : UMaxResult.countLeadingZeros();
  379. // The result of the bottom bits of an integer multiply can be
  380. // inferred by looking at the bottom bits of both operands and
  381. // multiplying them together.
  382. // We can infer at least the minimum number of known trailing bits
  383. // of both operands. Depending on number of trailing zeros, we can
  384. // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
  385. // a and b are divisible by m and n respectively.
  386. // We then calculate how many of those bits are inferrable and set
  387. // the output. For example, the i8 mul:
  388. // a = XXXX1100 (12)
  389. // b = XXXX1110 (14)
  390. // We know the bottom 3 bits are zero since the first can be divided by
  391. // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
  392. // Applying the multiplication to the trimmed arguments gets:
  393. // XX11 (3)
  394. // X111 (7)
  395. // -------
  396. // XX11
  397. // XX11
  398. // XX11
  399. // XX11
  400. // -------
  401. // XXXXX01
  402. // Which allows us to infer the 2 LSBs. Since we're multiplying the result
  403. // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
  404. // The proof for this can be described as:
  405. // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
  406. // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
  407. // umin(countTrailingZeros(C2), C6) +
  408. // umin(C5 - umin(countTrailingZeros(C1), C5),
  409. // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
  410. // %aa = shl i8 %a, C5
  411. // %bb = shl i8 %b, C6
  412. // %aaa = or i8 %aa, C1
  413. // %bbb = or i8 %bb, C2
  414. // %mul = mul i8 %aaa, %bbb
  415. // %mask = and i8 %mul, C7
  416. // =>
  417. // %mask = i8 ((C1*C2)&C7)
  418. // Where C5, C6 describe the known bits of %a, %b
  419. // C1, C2 describe the known bottom bits of %a, %b.
  420. // C7 describes the mask of the known bits of the result.
  421. const APInt &Bottom0 = LHS.One;
  422. const APInt &Bottom1 = RHS.One;
  423. // How many times we'd be able to divide each argument by 2 (shr by 1).
  424. // This gives us the number of trailing zeros on the multiplication result.
  425. unsigned TrailBitsKnown0 = (LHS.Zero | LHS.One).countTrailingOnes();
  426. unsigned TrailBitsKnown1 = (RHS.Zero | RHS.One).countTrailingOnes();
  427. unsigned TrailZero0 = LHS.countMinTrailingZeros();
  428. unsigned TrailZero1 = RHS.countMinTrailingZeros();
  429. unsigned TrailZ = TrailZero0 + TrailZero1;
  430. // Figure out the fewest known-bits operand.
  431. unsigned SmallestOperand =
  432. std::min(TrailBitsKnown0 - TrailZero0, TrailBitsKnown1 - TrailZero1);
  433. unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
  434. APInt BottomKnown =
  435. Bottom0.getLoBits(TrailBitsKnown0) * Bottom1.getLoBits(TrailBitsKnown1);
  436. KnownBits Res(BitWidth);
  437. Res.Zero.setHighBits(LeadZ);
  438. Res.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
  439. Res.One = BottomKnown.getLoBits(ResultBitsKnown);
  440. // If we're self-multiplying then bit[1] is guaranteed to be zero.
  441. if (NoUndefSelfMultiply && BitWidth > 1) {
  442. assert(Res.One[1] == 0 &&
  443. "Self-multiplication failed Quadratic Reciprocity!");
  444. Res.Zero.setBit(1);
  445. }
  446. return Res;
  447. }
  448. KnownBits KnownBits::mulhs(const KnownBits &LHS, const KnownBits &RHS) {
  449. unsigned BitWidth = LHS.getBitWidth();
  450. assert(BitWidth == RHS.getBitWidth() && !LHS.hasConflict() &&
  451. !RHS.hasConflict() && "Operand mismatch");
  452. KnownBits WideLHS = LHS.sext(2 * BitWidth);
  453. KnownBits WideRHS = RHS.sext(2 * BitWidth);
  454. return mul(WideLHS, WideRHS).extractBits(BitWidth, BitWidth);
  455. }
  456. KnownBits KnownBits::mulhu(const KnownBits &LHS, const KnownBits &RHS) {
  457. unsigned BitWidth = LHS.getBitWidth();
  458. assert(BitWidth == RHS.getBitWidth() && !LHS.hasConflict() &&
  459. !RHS.hasConflict() && "Operand mismatch");
  460. KnownBits WideLHS = LHS.zext(2 * BitWidth);
  461. KnownBits WideRHS = RHS.zext(2 * BitWidth);
  462. return mul(WideLHS, WideRHS).extractBits(BitWidth, BitWidth);
  463. }
  464. KnownBits KnownBits::udiv(const KnownBits &LHS, const KnownBits &RHS) {
  465. unsigned BitWidth = LHS.getBitWidth();
  466. assert(!LHS.hasConflict() && !RHS.hasConflict());
  467. KnownBits Known(BitWidth);
  468. // For the purposes of computing leading zeros we can conservatively
  469. // treat a udiv as a logical right shift by the power of 2 known to
  470. // be less than the denominator.
  471. unsigned LeadZ = LHS.countMinLeadingZeros();
  472. unsigned RHSMaxLeadingZeros = RHS.countMaxLeadingZeros();
  473. if (RHSMaxLeadingZeros != BitWidth)
  474. LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
  475. Known.Zero.setHighBits(LeadZ);
  476. return Known;
  477. }
  478. KnownBits KnownBits::urem(const KnownBits &LHS, const KnownBits &RHS) {
  479. unsigned BitWidth = LHS.getBitWidth();
  480. assert(!LHS.hasConflict() && !RHS.hasConflict());
  481. KnownBits Known(BitWidth);
  482. if (RHS.isConstant() && RHS.getConstant().isPowerOf2()) {
  483. // The upper bits are all zero, the lower ones are unchanged.
  484. APInt LowBits = RHS.getConstant() - 1;
  485. Known.Zero = LHS.Zero | ~LowBits;
  486. Known.One = LHS.One & LowBits;
  487. return Known;
  488. }
  489. // Since the result is less than or equal to either operand, any leading
  490. // zero bits in either operand must also exist in the result.
  491. uint32_t Leaders =
  492. std::max(LHS.countMinLeadingZeros(), RHS.countMinLeadingZeros());
  493. Known.Zero.setHighBits(Leaders);
  494. return Known;
  495. }
  496. KnownBits KnownBits::srem(const KnownBits &LHS, const KnownBits &RHS) {
  497. unsigned BitWidth = LHS.getBitWidth();
  498. assert(!LHS.hasConflict() && !RHS.hasConflict());
  499. KnownBits Known(BitWidth);
  500. if (RHS.isConstant() && RHS.getConstant().isPowerOf2()) {
  501. // The low bits of the first operand are unchanged by the srem.
  502. APInt LowBits = RHS.getConstant() - 1;
  503. Known.Zero = LHS.Zero & LowBits;
  504. Known.One = LHS.One & LowBits;
  505. // If the first operand is non-negative or has all low bits zero, then
  506. // the upper bits are all zero.
  507. if (LHS.isNonNegative() || LowBits.isSubsetOf(LHS.Zero))
  508. Known.Zero |= ~LowBits;
  509. // If the first operand is negative and not all low bits are zero, then
  510. // the upper bits are all one.
  511. if (LHS.isNegative() && LowBits.intersects(LHS.One))
  512. Known.One |= ~LowBits;
  513. return Known;
  514. }
  515. // The sign bit is the LHS's sign bit, except when the result of the
  516. // remainder is zero. The magnitude of the result should be less than or
  517. // equal to the magnitude of the LHS. Therefore any leading zeros that exist
  518. // in the left hand side must also exist in the result.
  519. Known.Zero.setHighBits(LHS.countMinLeadingZeros());
  520. return Known;
  521. }
  522. KnownBits &KnownBits::operator&=(const KnownBits &RHS) {
  523. // Result bit is 0 if either operand bit is 0.
  524. Zero |= RHS.Zero;
  525. // Result bit is 1 if both operand bits are 1.
  526. One &= RHS.One;
  527. return *this;
  528. }
  529. KnownBits &KnownBits::operator|=(const KnownBits &RHS) {
  530. // Result bit is 0 if both operand bits are 0.
  531. Zero &= RHS.Zero;
  532. // Result bit is 1 if either operand bit is 1.
  533. One |= RHS.One;
  534. return *this;
  535. }
  536. KnownBits &KnownBits::operator^=(const KnownBits &RHS) {
  537. // Result bit is 0 if both operand bits are 0 or both are 1.
  538. APInt Z = (Zero & RHS.Zero) | (One & RHS.One);
  539. // Result bit is 1 if one operand bit is 0 and the other is 1.
  540. One = (Zero & RHS.One) | (One & RHS.Zero);
  541. Zero = std::move(Z);
  542. return *this;
  543. }
  544. void KnownBits::print(raw_ostream &OS) const {
  545. OS << "{Zero=" << Zero << ", One=" << One << "}";
  546. }
  547. void KnownBits::dump() const {
  548. print(dbgs());
  549. dbgs() << "\n";
  550. }