move ComputeMaskedBits, MaskedValueIsZero, and ComputeNumSignBits
[oota-llvm.git] / lib / Analysis / ValueTracking.cpp
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/Support/MathExtras.h"
22 using namespace llvm;
23
24 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
25 /// opcode value. Otherwise return UserOp1.
26 static unsigned getOpcode(const Value *V) {
27   if (const Instruction *I = dyn_cast<Instruction>(V))
28     return I->getOpcode();
29   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
30     return CE->getOpcode();
31   // Use UserOp1 to mean there's no opcode.
32   return Instruction::UserOp1;
33 }
34
35
36 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
37 /// known to be either zero or one and return them in the KnownZero/KnownOne
38 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
39 /// processing.
40 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
41 /// we cannot optimize based on the assumption that it is zero without changing
42 /// it to be an explicit zero.  If we don't change it to zero, other code could
43 /// optimized based on the contradictory assumption that it is non-zero.
44 /// Because instcombine aggressively folds operations with undef args anyway,
45 /// this won't lose us code quality.
46 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
47                              APInt &KnownZero, APInt &KnownOne,
48                              TargetData *TD, unsigned Depth) {
49   assert(V && "No Value?");
50   assert(Depth <= 6 && "Limit Search Depth");
51   uint32_t BitWidth = Mask.getBitWidth();
52   assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
53          "Not integer or pointer type!");
54   assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
55          (!isa<IntegerType>(V->getType()) ||
56           V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
57          KnownZero.getBitWidth() == BitWidth && 
58          KnownOne.getBitWidth() == BitWidth &&
59          "V, Mask, KnownOne and KnownZero should have same BitWidth");
60
61   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
62     // We know all of the bits for a constant!
63     KnownOne = CI->getValue() & Mask;
64     KnownZero = ~KnownOne & Mask;
65     return;
66   }
67   // Null is all-zeros.
68   if (isa<ConstantPointerNull>(V)) {
69     KnownOne.clear();
70     KnownZero = Mask;
71     return;
72   }
73   // The address of an aligned GlobalValue has trailing zeros.
74   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
75     unsigned Align = GV->getAlignment();
76     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
77       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
78     if (Align > 0)
79       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
80                                               CountTrailingZeros_32(Align));
81     else
82       KnownZero.clear();
83     KnownOne.clear();
84     return;
85   }
86
87   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
88
89   if (Depth == 6 || Mask == 0)
90     return;  // Limit search depth.
91
92   User *I = dyn_cast<User>(V);
93   if (!I) return;
94
95   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
96   switch (getOpcode(I)) {
97   default: break;
98   case Instruction::And: {
99     // If either the LHS or the RHS are Zero, the result is zero.
100     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
101     APInt Mask2(Mask & ~KnownZero);
102     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
103                       Depth+1);
104     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
105     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
106     
107     // Output known-1 bits are only known if set in both the LHS & RHS.
108     KnownOne &= KnownOne2;
109     // Output known-0 are known to be clear if zero in either the LHS | RHS.
110     KnownZero |= KnownZero2;
111     return;
112   }
113   case Instruction::Or: {
114     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
115     APInt Mask2(Mask & ~KnownOne);
116     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
117                       Depth+1);
118     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
119     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
120     
121     // Output known-0 bits are only known if clear in both the LHS & RHS.
122     KnownZero &= KnownZero2;
123     // Output known-1 are known to be set if set in either the LHS | RHS.
124     KnownOne |= KnownOne2;
125     return;
126   }
127   case Instruction::Xor: {
128     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
129     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
130                       Depth+1);
131     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
132     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
133     
134     // Output known-0 bits are known if clear or set in both the LHS & RHS.
135     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
136     // Output known-1 are known to be set if set in only one of the LHS, RHS.
137     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
138     KnownZero = KnownZeroOut;
139     return;
140   }
141   case Instruction::Mul: {
142     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
143     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
144     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
145                       Depth+1);
146     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
147     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
148     
149     // If low bits are zero in either operand, output low known-0 bits.
150     // Also compute a conserative estimate for high known-0 bits.
151     // More trickiness is possible, but this is sufficient for the
152     // interesting case of alignment computation.
153     KnownOne.clear();
154     unsigned TrailZ = KnownZero.countTrailingOnes() +
155                       KnownZero2.countTrailingOnes();
156     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
157                                KnownZero2.countLeadingOnes(),
158                                BitWidth) - BitWidth;
159
160     TrailZ = std::min(TrailZ, BitWidth);
161     LeadZ = std::min(LeadZ, BitWidth);
162     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
163                 APInt::getHighBitsSet(BitWidth, LeadZ);
164     KnownZero &= Mask;
165     return;
166   }
167   case Instruction::UDiv: {
168     // For the purposes of computing leading zeros we can conservatively
169     // treat a udiv as a logical right shift by the power of 2 known to
170     // be less than the denominator.
171     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
172     ComputeMaskedBits(I->getOperand(0),
173                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
174     unsigned LeadZ = KnownZero2.countLeadingOnes();
175
176     KnownOne2.clear();
177     KnownZero2.clear();
178     ComputeMaskedBits(I->getOperand(1),
179                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
180     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
181     if (RHSUnknownLeadingOnes != BitWidth)
182       LeadZ = std::min(BitWidth,
183                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
184
185     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
186     return;
187   }
188   case Instruction::Select:
189     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
190     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
191                       Depth+1);
192     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
193     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
194
195     // Only known if known in both the LHS and RHS.
196     KnownOne &= KnownOne2;
197     KnownZero &= KnownZero2;
198     return;
199   case Instruction::FPTrunc:
200   case Instruction::FPExt:
201   case Instruction::FPToUI:
202   case Instruction::FPToSI:
203   case Instruction::SIToFP:
204   case Instruction::UIToFP:
205     return; // Can't work with floating point.
206   case Instruction::PtrToInt:
207   case Instruction::IntToPtr:
208     // We can't handle these if we don't know the pointer size.
209     if (!TD) return;
210     // FALL THROUGH and handle them the same as zext/trunc.
211   case Instruction::ZExt:
212   case Instruction::Trunc: {
213     // Note that we handle pointer operands here because of inttoptr/ptrtoint
214     // which fall through here.
215     const Type *SrcTy = I->getOperand(0)->getType();
216     uint32_t SrcBitWidth = TD ?
217       TD->getTypeSizeInBits(SrcTy) :
218       SrcTy->getPrimitiveSizeInBits();
219     APInt MaskIn(Mask);
220     MaskIn.zextOrTrunc(SrcBitWidth);
221     KnownZero.zextOrTrunc(SrcBitWidth);
222     KnownOne.zextOrTrunc(SrcBitWidth);
223     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
224                       Depth+1);
225     KnownZero.zextOrTrunc(BitWidth);
226     KnownOne.zextOrTrunc(BitWidth);
227     // Any top bits are known to be zero.
228     if (BitWidth > SrcBitWidth)
229       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
230     return;
231   }
232   case Instruction::BitCast: {
233     const Type *SrcTy = I->getOperand(0)->getType();
234     if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
235       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
236                         Depth+1);
237       return;
238     }
239     break;
240   }
241   case Instruction::SExt: {
242     // Compute the bits in the result that are not present in the input.
243     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
244     uint32_t SrcBitWidth = SrcTy->getBitWidth();
245       
246     APInt MaskIn(Mask); 
247     MaskIn.trunc(SrcBitWidth);
248     KnownZero.trunc(SrcBitWidth);
249     KnownOne.trunc(SrcBitWidth);
250     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
251                       Depth+1);
252     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
253     KnownZero.zext(BitWidth);
254     KnownOne.zext(BitWidth);
255
256     // If the sign bit of the input is known set or clear, then we know the
257     // top bits of the result.
258     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
259       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
260     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
261       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
262     return;
263   }
264   case Instruction::Shl:
265     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
266     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
267       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
268       APInt Mask2(Mask.lshr(ShiftAmt));
269       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
270                         Depth+1);
271       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
272       KnownZero <<= ShiftAmt;
273       KnownOne  <<= ShiftAmt;
274       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
275       return;
276     }
277     break;
278   case Instruction::LShr:
279     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
280     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
281       // Compute the new bits that are at the top now.
282       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
283       
284       // Unsigned shift right.
285       APInt Mask2(Mask.shl(ShiftAmt));
286       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
287                         Depth+1);
288       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
289       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
290       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
291       // high bits known zero.
292       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
293       return;
294     }
295     break;
296   case Instruction::AShr:
297     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
298     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
299       // Compute the new bits that are at the top now.
300       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
301       
302       // Signed shift right.
303       APInt Mask2(Mask.shl(ShiftAmt));
304       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
305                         Depth+1);
306       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
307       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
308       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
309         
310       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
311       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
312         KnownZero |= HighBits;
313       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
314         KnownOne |= HighBits;
315       return;
316     }
317     break;
318   case Instruction::Sub: {
319     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
320       // We know that the top bits of C-X are clear if X contains less bits
321       // than C (i.e. no wrap-around can happen).  For example, 20-X is
322       // positive if we can prove that X is >= 0 and < 16.
323       if (!CLHS->getValue().isNegative()) {
324         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
325         // NLZ can't be BitWidth with no sign bit
326         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
327         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
328                           TD, Depth+1);
329     
330         // If all of the MaskV bits are known to be zero, then we know the
331         // output top bits are zero, because we now know that the output is
332         // from [0-C].
333         if ((KnownZero2 & MaskV) == MaskV) {
334           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
335           // Top bits known zero.
336           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
337         }
338       }        
339     }
340   }
341   // fall through
342   case Instruction::Add: {
343     // Output known-0 bits are known if clear or set in both the low clear bits
344     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
345     // low 3 bits clear.
346     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
347     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
348                       Depth+1);
349     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
350     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
351
352     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 
353                       Depth+1);
354     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
355     KnownZeroOut = std::min(KnownZeroOut, 
356                             KnownZero2.countTrailingOnes());
357
358     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
359     return;
360   }
361   case Instruction::SRem:
362     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
363       APInt RA = Rem->getValue();
364       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
365         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
366         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
367         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
368                           Depth+1);
369
370         // The sign of a remainder is equal to the sign of the first
371         // operand (zero being positive).
372         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
373           KnownZero2 |= ~LowBits;
374         else if (KnownOne2[BitWidth-1])
375           KnownOne2 |= ~LowBits;
376
377         KnownZero |= KnownZero2 & Mask;
378         KnownOne |= KnownOne2 & Mask;
379
380         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
381       }
382     }
383     break;
384   case Instruction::URem: {
385     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
386       APInt RA = Rem->getValue();
387       if (RA.isPowerOf2()) {
388         APInt LowBits = (RA - 1);
389         APInt Mask2 = LowBits & Mask;
390         KnownZero |= ~LowBits & Mask;
391         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
392                           Depth+1);
393         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
394         break;
395       }
396     }
397
398     // Since the result is less than or equal to either operand, any leading
399     // zero bits in either operand must also exist in the result.
400     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
401     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
402                       TD, Depth+1);
403     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
404                       TD, Depth+1);
405
406     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
407                                 KnownZero2.countLeadingOnes());
408     KnownOne.clear();
409     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
410     break;
411   }
412
413   case Instruction::Alloca:
414   case Instruction::Malloc: {
415     AllocationInst *AI = cast<AllocationInst>(V);
416     unsigned Align = AI->getAlignment();
417     if (Align == 0 && TD) {
418       if (isa<AllocaInst>(AI))
419         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
420       else if (isa<MallocInst>(AI)) {
421         // Malloc returns maximally aligned memory.
422         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
423         Align =
424           std::max(Align,
425                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
426         Align =
427           std::max(Align,
428                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
429       }
430     }
431     
432     if (Align > 0)
433       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
434                                               CountTrailingZeros_32(Align));
435     break;
436   }
437   case Instruction::GetElementPtr: {
438     // Analyze all of the subscripts of this getelementptr instruction
439     // to determine if we can prove known low zero bits.
440     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
441     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
442     ComputeMaskedBits(I->getOperand(0), LocalMask,
443                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
444     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
445
446     gep_type_iterator GTI = gep_type_begin(I);
447     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
448       Value *Index = I->getOperand(i);
449       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
450         // Handle struct member offset arithmetic.
451         if (!TD) return;
452         const StructLayout *SL = TD->getStructLayout(STy);
453         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
454         uint64_t Offset = SL->getElementOffset(Idx);
455         TrailZ = std::min(TrailZ,
456                           CountTrailingZeros_64(Offset));
457       } else {
458         // Handle array index arithmetic.
459         const Type *IndexedTy = GTI.getIndexedType();
460         if (!IndexedTy->isSized()) return;
461         unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
462         uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
463         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
464         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
465         ComputeMaskedBits(Index, LocalMask,
466                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
467         TrailZ = std::min(TrailZ,
468                           CountTrailingZeros_64(TypeSize) +
469                             LocalKnownZero.countTrailingOnes());
470       }
471     }
472     
473     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
474     break;
475   }
476   case Instruction::PHI: {
477     PHINode *P = cast<PHINode>(I);
478     // Handle the case of a simple two-predecessor recurrence PHI.
479     // There's a lot more that could theoretically be done here, but
480     // this is sufficient to catch some interesting cases.
481     if (P->getNumIncomingValues() == 2) {
482       for (unsigned i = 0; i != 2; ++i) {
483         Value *L = P->getIncomingValue(i);
484         Value *R = P->getIncomingValue(!i);
485         User *LU = dyn_cast<User>(L);
486         if (!LU)
487           continue;
488         unsigned Opcode = getOpcode(LU);
489         // Check for operations that have the property that if
490         // both their operands have low zero bits, the result
491         // will have low zero bits.
492         if (Opcode == Instruction::Add ||
493             Opcode == Instruction::Sub ||
494             Opcode == Instruction::And ||
495             Opcode == Instruction::Or ||
496             Opcode == Instruction::Mul) {
497           Value *LL = LU->getOperand(0);
498           Value *LR = LU->getOperand(1);
499           // Find a recurrence.
500           if (LL == I)
501             L = LR;
502           else if (LR == I)
503             L = LL;
504           else
505             break;
506           // Ok, we have a PHI of the form L op= R. Check for low
507           // zero bits.
508           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
509           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
510           Mask2 = APInt::getLowBitsSet(BitWidth,
511                                        KnownZero2.countTrailingOnes());
512           KnownOne2.clear();
513           KnownZero2.clear();
514           ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
515           KnownZero = Mask &
516                       APInt::getLowBitsSet(BitWidth,
517                                            KnownZero2.countTrailingOnes());
518           break;
519         }
520       }
521     }
522     break;
523   }
524   case Instruction::Call:
525     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
526       switch (II->getIntrinsicID()) {
527       default: break;
528       case Intrinsic::ctpop:
529       case Intrinsic::ctlz:
530       case Intrinsic::cttz: {
531         unsigned LowBits = Log2_32(BitWidth)+1;
532         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
533         break;
534       }
535       }
536     }
537     break;
538   }
539 }
540
541 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
542 /// this predicate to simplify operations downstream.  Mask is known to be zero
543 /// for bits that V cannot have.
544 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
545                              TargetData *TD, unsigned Depth) {
546   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
547   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
548   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
549   return (KnownZero & Mask) == Mask;
550 }
551
552
553
554 /// ComputeNumSignBits - Return the number of times the sign bit of the
555 /// register is replicated into the other bits.  We know that at least 1 bit
556 /// is always equal to the sign bit (itself), but other cases can give us
557 /// information.  For example, immediately after an "ashr X, 2", we know that
558 /// the top 3 bits are all equal to each other, so we return 3.
559 ///
560 /// 'Op' must have a scalar integer type.
561 ///
562 unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
563   const IntegerType *Ty = cast<IntegerType>(V->getType());
564   unsigned TyBits = Ty->getBitWidth();
565   unsigned Tmp, Tmp2;
566   unsigned FirstAnswer = 1;
567
568   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
569     if (CI->getValue().isNegative())
570       return CI->getValue().countLeadingOnes();
571     return CI->getValue().countLeadingZeros();
572   }
573   
574   if (Depth == 6)
575     return 1;  // Limit search depth.
576   
577   User *U = dyn_cast<User>(V);
578   switch (getOpcode(V)) {
579   default: break;
580   case Instruction::SExt:
581     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
582     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
583     
584   case Instruction::AShr:
585     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
586     // ashr X, C   -> adds C sign bits.
587     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
588       Tmp += C->getZExtValue();
589       if (Tmp > TyBits) Tmp = TyBits;
590     }
591     return Tmp;
592   case Instruction::Shl:
593     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
594       // shl destroys sign bits.
595       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
596       if (C->getZExtValue() >= TyBits ||      // Bad shift.
597           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
598       return Tmp - C->getZExtValue();
599     }
600     break;
601   case Instruction::And:
602   case Instruction::Or:
603   case Instruction::Xor:    // NOT is handled here.
604     // Logical binary ops preserve the number of sign bits at the worst.
605     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
606     if (Tmp != 1) {
607       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
608       FirstAnswer = std::min(Tmp, Tmp2);
609       // We computed what we know about the sign bits as our first
610       // answer. Now proceed to the generic code that uses
611       // ComputeMaskedBits, and pick whichever answer is better.
612     }
613     break;
614
615   case Instruction::Select:
616     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
617     if (Tmp == 1) return 1;  // Early out.
618     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
619     return std::min(Tmp, Tmp2);
620     
621   case Instruction::Add:
622     // Add can have at most one carry bit.  Thus we know that the output
623     // is, at worst, one more bit than the inputs.
624     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
625     if (Tmp == 1) return 1;  // Early out.
626       
627     // Special case decrementing a value (ADD X, -1):
628     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
629       if (CRHS->isAllOnesValue()) {
630         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
631         APInt Mask = APInt::getAllOnesValue(TyBits);
632         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
633                           Depth+1);
634         
635         // If the input is known to be 0 or 1, the output is 0/-1, which is all
636         // sign bits set.
637         if ((KnownZero | APInt(TyBits, 1)) == Mask)
638           return TyBits;
639         
640         // If we are subtracting one from a positive number, there is no carry
641         // out of the result.
642         if (KnownZero.isNegative())
643           return Tmp;
644       }
645       
646     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
647     if (Tmp2 == 1) return 1;
648       return std::min(Tmp, Tmp2)-1;
649     break;
650     
651   case Instruction::Sub:
652     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
653     if (Tmp2 == 1) return 1;
654       
655     // Handle NEG.
656     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
657       if (CLHS->isNullValue()) {
658         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
659         APInt Mask = APInt::getAllOnesValue(TyBits);
660         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
661                           TD, Depth+1);
662         // If the input is known to be 0 or 1, the output is 0/-1, which is all
663         // sign bits set.
664         if ((KnownZero | APInt(TyBits, 1)) == Mask)
665           return TyBits;
666         
667         // If the input is known to be positive (the sign bit is known clear),
668         // the output of the NEG has the same number of sign bits as the input.
669         if (KnownZero.isNegative())
670           return Tmp2;
671         
672         // Otherwise, we treat this like a SUB.
673       }
674     
675     // Sub can have at most one carry bit.  Thus we know that the output
676     // is, at worst, one more bit than the inputs.
677     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
678     if (Tmp == 1) return 1;  // Early out.
679       return std::min(Tmp, Tmp2)-1;
680     break;
681   case Instruction::Trunc:
682     // FIXME: it's tricky to do anything useful for this, but it is an important
683     // case for targets like X86.
684     break;
685   }
686   
687   // Finally, if we can prove that the top bits of the result are 0's or 1's,
688   // use this information.
689   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
690   APInt Mask = APInt::getAllOnesValue(TyBits);
691   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
692   
693   if (KnownZero.isNegative()) {        // sign bit is 0
694     Mask = KnownZero;
695   } else if (KnownOne.isNegative()) {  // sign bit is 1;
696     Mask = KnownOne;
697   } else {
698     // Nothing known.
699     return FirstAnswer;
700   }
701   
702   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
703   // the number of identical bits in the top of the input value.
704   Mask = ~Mask;
705   Mask <<= Mask.getBitWidth()-TyBits;
706   // Return # leading zeros.  We use 'min' here in case Val was zero before
707   // shifting.  We don't want to return '64' as for an i32 "0".
708   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
709 }