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