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