22f1c144ea2680df17b281dc394d7a24658ba18d
[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/Analysis/InstructionSimplify.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Operator.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/PatternMatch.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include <cstring>
30 using namespace llvm;
31 using namespace llvm::PatternMatch;
32
33 const unsigned MaxDepth = 6;
34
35 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
36 /// unknown returns 0).  For vector types, returns the element type's bitwidth.
37 static unsigned getBitWidth(Type *Ty, const TargetData *TD) {
38   if (unsigned BitWidth = Ty->getScalarSizeInBits())
39     return BitWidth;
40   assert(isa<PointerType>(Ty) && "Expected a pointer type!");
41   return TD ? TD->getPointerSizeInBits() : 0;
42 }
43
44 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
45 /// known to be either zero or one and return them in the KnownZero/KnownOne
46 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
47 /// processing.
48 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
49 /// we cannot optimize based on the assumption that it is zero without changing
50 /// it to be an explicit zero.  If we don't change it to zero, other code could
51 /// optimized based on the contradictory assumption that it is non-zero.
52 /// Because instcombine aggressively folds operations with undef args anyway,
53 /// this won't lose us code quality.
54 ///
55 /// This function is defined on values with integer type, values with pointer
56 /// type (but only if TD is non-null), and vectors of integers.  In the case
57 /// where V is a vector, the mask, known zero, and known one values are the
58 /// same width as the vector element, and the bit is set only if it is true
59 /// for all of the elements in the vector.
60 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
61                              APInt &KnownZero, APInt &KnownOne,
62                              const TargetData *TD, unsigned Depth) {
63   assert(V && "No Value?");
64   assert(Depth <= MaxDepth && "Limit Search Depth");
65   unsigned BitWidth = Mask.getBitWidth();
66   assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy())
67          && "Not integer or pointer type!");
68   assert((!TD ||
69           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
70          (!V->getType()->isIntOrIntVectorTy() ||
71           V->getType()->getScalarSizeInBits() == BitWidth) &&
72          KnownZero.getBitWidth() == BitWidth && 
73          KnownOne.getBitWidth() == BitWidth &&
74          "V, Mask, KnownOne and KnownZero should have same BitWidth");
75
76   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
77     // We know all of the bits for a constant!
78     KnownOne = CI->getValue() & Mask;
79     KnownZero = ~KnownOne & Mask;
80     return;
81   }
82   // Null and aggregate-zero are all-zeros.
83   if (isa<ConstantPointerNull>(V) ||
84       isa<ConstantAggregateZero>(V)) {
85     KnownOne.clearAllBits();
86     KnownZero = Mask;
87     return;
88   }
89   // Handle a constant vector by taking the intersection of the known bits of
90   // each element.
91   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
92     KnownZero.setAllBits(); KnownOne.setAllBits();
93     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
94       APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
95       ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
96                         TD, Depth);
97       KnownZero &= KnownZero2;
98       KnownOne &= KnownOne2;
99     }
100     return;
101   }
102   // The address of an aligned GlobalValue has trailing zeros.
103   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
104     unsigned Align = GV->getAlignment();
105     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
106       Type *ObjectType = GV->getType()->getElementType();
107       // If the object is defined in the current Module, we'll be giving
108       // it the preferred alignment. Otherwise, we have to assume that it
109       // may only have the minimum ABI alignment.
110       if (!GV->isDeclaration() && !GV->mayBeOverridden())
111         Align = TD->getPrefTypeAlignment(ObjectType);
112       else
113         Align = TD->getABITypeAlignment(ObjectType);
114     }
115     if (Align > 0)
116       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
117                                               CountTrailingZeros_32(Align));
118     else
119       KnownZero.clearAllBits();
120     KnownOne.clearAllBits();
121     return;
122   }
123   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
124   // the bits of its aliasee.
125   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
126     if (GA->mayBeOverridden()) {
127       KnownZero.clearAllBits(); KnownOne.clearAllBits();
128     } else {
129       ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
130                         TD, Depth+1);
131     }
132     return;
133   }
134   
135   if (Argument *A = dyn_cast<Argument>(V)) {
136     // Get alignment information off byval arguments if specified in the IR.
137     if (A->hasByValAttr())
138       if (unsigned Align = A->getParamAlignment())
139         KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
140                                                 CountTrailingZeros_32(Align));
141     return;
142   }
143
144   // Start out not knowing anything.
145   KnownZero.clearAllBits(); KnownOne.clearAllBits();
146
147   if (Depth == MaxDepth || Mask == 0)
148     return;  // Limit search depth.
149
150   Operator *I = dyn_cast<Operator>(V);
151   if (!I) return;
152
153   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
154   switch (I->getOpcode()) {
155   default: break;
156   case Instruction::And: {
157     // If either the LHS or the RHS are Zero, the result is zero.
158     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
159     APInt Mask2(Mask & ~KnownZero);
160     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
161                       Depth+1);
162     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
163     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
164     
165     // Output known-1 bits are only known if set in both the LHS & RHS.
166     KnownOne &= KnownOne2;
167     // Output known-0 are known to be clear if zero in either the LHS | RHS.
168     KnownZero |= KnownZero2;
169     return;
170   }
171   case Instruction::Or: {
172     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
173     APInt Mask2(Mask & ~KnownOne);
174     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
175                       Depth+1);
176     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
177     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
178     
179     // Output known-0 bits are only known if clear in both the LHS & RHS.
180     KnownZero &= KnownZero2;
181     // Output known-1 are known to be set if set in either the LHS | RHS.
182     KnownOne |= KnownOne2;
183     return;
184   }
185   case Instruction::Xor: {
186     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
187     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
188                       Depth+1);
189     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
190     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
191     
192     // Output known-0 bits are known if clear or set in both the LHS & RHS.
193     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
194     // Output known-1 are known to be set if set in only one of the LHS, RHS.
195     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
196     KnownZero = KnownZeroOut;
197     return;
198   }
199   case Instruction::Mul: {
200     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
201     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
202     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
203                       Depth+1);
204     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
205     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
206
207     bool isKnownNegative = false;
208     bool isKnownNonNegative = false;
209     // If the multiplication is known not to overflow, compute the sign bit.
210     if (Mask.isNegative() &&
211         cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap()) {
212       Value *Op1 = I->getOperand(1), *Op2 = I->getOperand(0);
213       if (Op1 == Op2) {
214         // The product of a number with itself is non-negative.
215         isKnownNonNegative = true;
216       } else {
217         bool isKnownNonNegative1 = KnownZero.isNegative();
218         bool isKnownNonNegative2 = KnownZero2.isNegative();
219         bool isKnownNegative1 = KnownOne.isNegative();
220         bool isKnownNegative2 = KnownOne2.isNegative();
221         // The product of two numbers with the same sign is non-negative.
222         isKnownNonNegative = (isKnownNegative1 && isKnownNegative2) ||
223           (isKnownNonNegative1 && isKnownNonNegative2);
224         // The product of a negative number and a non-negative number is either
225         // negative or zero.
226         if (!isKnownNonNegative)
227           isKnownNegative = (isKnownNegative1 && isKnownNonNegative2 &&
228                              isKnownNonZero(Op2, TD, Depth)) ||
229                             (isKnownNegative2 && isKnownNonNegative1 &&
230                              isKnownNonZero(Op1, TD, Depth));
231       }
232     }
233
234     // If low bits are zero in either operand, output low known-0 bits.
235     // Also compute a conserative estimate for high known-0 bits.
236     // More trickiness is possible, but this is sufficient for the
237     // interesting case of alignment computation.
238     KnownOne.clearAllBits();
239     unsigned TrailZ = KnownZero.countTrailingOnes() +
240                       KnownZero2.countTrailingOnes();
241     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
242                                KnownZero2.countLeadingOnes(),
243                                BitWidth) - BitWidth;
244
245     TrailZ = std::min(TrailZ, BitWidth);
246     LeadZ = std::min(LeadZ, BitWidth);
247     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
248                 APInt::getHighBitsSet(BitWidth, LeadZ);
249     KnownZero &= Mask;
250
251     // Only make use of no-wrap flags if we failed to compute the sign bit
252     // directly.  This matters if the multiplication always overflows, in
253     // which case we prefer to follow the result of the direct computation,
254     // though as the program is invoking undefined behaviour we can choose
255     // whatever we like here.
256     if (isKnownNonNegative && !KnownOne.isNegative())
257       KnownZero.setBit(BitWidth - 1);
258     else if (isKnownNegative && !KnownZero.isNegative())
259       KnownOne.setBit(BitWidth - 1);
260
261     return;
262   }
263   case Instruction::UDiv: {
264     // For the purposes of computing leading zeros we can conservatively
265     // treat a udiv as a logical right shift by the power of 2 known to
266     // be less than the denominator.
267     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
268     ComputeMaskedBits(I->getOperand(0),
269                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
270     unsigned LeadZ = KnownZero2.countLeadingOnes();
271
272     KnownOne2.clearAllBits();
273     KnownZero2.clearAllBits();
274     ComputeMaskedBits(I->getOperand(1),
275                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
276     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
277     if (RHSUnknownLeadingOnes != BitWidth)
278       LeadZ = std::min(BitWidth,
279                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
280
281     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
282     return;
283   }
284   case Instruction::Select:
285     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
286     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
287                       Depth+1);
288     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
289     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
290
291     // Only known if known in both the LHS and RHS.
292     KnownOne &= KnownOne2;
293     KnownZero &= KnownZero2;
294     return;
295   case Instruction::FPTrunc:
296   case Instruction::FPExt:
297   case Instruction::FPToUI:
298   case Instruction::FPToSI:
299   case Instruction::SIToFP:
300   case Instruction::UIToFP:
301     return; // Can't work with floating point.
302   case Instruction::PtrToInt:
303   case Instruction::IntToPtr:
304     // We can't handle these if we don't know the pointer size.
305     if (!TD) return;
306     // FALL THROUGH and handle them the same as zext/trunc.
307   case Instruction::ZExt:
308   case Instruction::Trunc: {
309     Type *SrcTy = I->getOperand(0)->getType();
310     
311     unsigned SrcBitWidth;
312     // Note that we handle pointer operands here because of inttoptr/ptrtoint
313     // which fall through here.
314     if (SrcTy->isPointerTy())
315       SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
316     else
317       SrcBitWidth = SrcTy->getScalarSizeInBits();
318     
319     APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
320     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
321     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
322     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
323                       Depth+1);
324     KnownZero = KnownZero.zextOrTrunc(BitWidth);
325     KnownOne = KnownOne.zextOrTrunc(BitWidth);
326     // Any top bits are known to be zero.
327     if (BitWidth > SrcBitWidth)
328       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
329     return;
330   }
331   case Instruction::BitCast: {
332     Type *SrcTy = I->getOperand(0)->getType();
333     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
334         // TODO: For now, not handling conversions like:
335         // (bitcast i64 %x to <2 x i32>)
336         !I->getType()->isVectorTy()) {
337       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
338                         Depth+1);
339       return;
340     }
341     break;
342   }
343   case Instruction::SExt: {
344     // Compute the bits in the result that are not present in the input.
345     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
346       
347     APInt MaskIn = Mask.trunc(SrcBitWidth);
348     KnownZero = KnownZero.trunc(SrcBitWidth);
349     KnownOne = KnownOne.trunc(SrcBitWidth);
350     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
351                       Depth+1);
352     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
353     KnownZero = KnownZero.zext(BitWidth);
354     KnownOne = KnownOne.zext(BitWidth);
355
356     // If the sign bit of the input is known set or clear, then we know the
357     // top bits of the result.
358     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
359       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
360     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
361       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
362     return;
363   }
364   case Instruction::Shl:
365     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
366     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
367       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
368       APInt Mask2(Mask.lshr(ShiftAmt));
369       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
370                         Depth+1);
371       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
372       KnownZero <<= ShiftAmt;
373       KnownOne  <<= ShiftAmt;
374       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
375       return;
376     }
377     break;
378   case Instruction::LShr:
379     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
380     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
381       // Compute the new bits that are at the top now.
382       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
383       
384       // Unsigned shift right.
385       APInt Mask2(Mask.shl(ShiftAmt));
386       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
387                         Depth+1);
388       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
389       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
390       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
391       // high bits known zero.
392       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
393       return;
394     }
395     break;
396   case Instruction::AShr:
397     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
398     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
399       // Compute the new bits that are at the top now.
400       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
401       
402       // Signed shift right.
403       APInt Mask2(Mask.shl(ShiftAmt));
404       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
405                         Depth+1);
406       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
407       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
408       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
409         
410       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
411       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
412         KnownZero |= HighBits;
413       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
414         KnownOne |= HighBits;
415       return;
416     }
417     break;
418   case Instruction::Sub: {
419     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
420       // We know that the top bits of C-X are clear if X contains less bits
421       // than C (i.e. no wrap-around can happen).  For example, 20-X is
422       // positive if we can prove that X is >= 0 and < 16.
423       if (!CLHS->getValue().isNegative()) {
424         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
425         // NLZ can't be BitWidth with no sign bit
426         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
427         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
428                           TD, Depth+1);
429     
430         // If all of the MaskV bits are known to be zero, then we know the
431         // output top bits are zero, because we now know that the output is
432         // from [0-C].
433         if ((KnownZero2 & MaskV) == MaskV) {
434           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
435           // Top bits known zero.
436           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
437         }
438       }        
439     }
440   }
441   // fall through
442   case Instruction::Add: {
443     // If one of the operands has trailing zeros, then the bits that the
444     // other operand has in those bit positions will be preserved in the
445     // result. For an add, this works with either operand. For a subtract,
446     // this only works if the known zeros are in the right operand.
447     APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
448     APInt Mask2 = APInt::getLowBitsSet(BitWidth,
449                                        BitWidth - Mask.countLeadingZeros());
450     ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
451                       Depth+1);
452     assert((LHSKnownZero & LHSKnownOne) == 0 &&
453            "Bits known to be one AND zero?");
454     unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
455
456     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 
457                       Depth+1);
458     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
459     unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
460
461     // Determine which operand has more trailing zeros, and use that
462     // many bits from the other operand.
463     if (LHSKnownZeroOut > RHSKnownZeroOut) {
464       if (I->getOpcode() == Instruction::Add) {
465         APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
466         KnownZero |= KnownZero2 & Mask;
467         KnownOne  |= KnownOne2 & Mask;
468       } else {
469         // If the known zeros are in the left operand for a subtract,
470         // fall back to the minimum known zeros in both operands.
471         KnownZero |= APInt::getLowBitsSet(BitWidth,
472                                           std::min(LHSKnownZeroOut,
473                                                    RHSKnownZeroOut));
474       }
475     } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
476       APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
477       KnownZero |= LHSKnownZero & Mask;
478       KnownOne  |= LHSKnownOne & Mask;
479     }
480
481     // Are we still trying to solve for the sign bit?
482     if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()){
483       OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(I);
484       if (OBO->hasNoSignedWrap()) {
485         if (I->getOpcode() == Instruction::Add) {
486           // Adding two positive numbers can't wrap into negative
487           if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
488             KnownZero |= APInt::getSignBit(BitWidth);
489           // and adding two negative numbers can't wrap into positive.
490           else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
491             KnownOne |= APInt::getSignBit(BitWidth);
492         } else {
493           // Subtracting a negative number from a positive one can't wrap
494           if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
495             KnownZero |= APInt::getSignBit(BitWidth);
496           // neither can subtracting a positive number from a negative one.
497           else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
498             KnownOne |= APInt::getSignBit(BitWidth);
499         }
500       }
501     }
502
503     return;
504   }
505   case Instruction::SRem:
506     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
507       APInt RA = Rem->getValue().abs();
508       if (RA.isPowerOf2()) {
509         APInt LowBits = RA - 1;
510         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
511         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
512                           Depth+1);
513
514         // The low bits of the first operand are unchanged by the srem.
515         KnownZero = KnownZero2 & LowBits;
516         KnownOne = KnownOne2 & LowBits;
517
518         // If the first operand is non-negative or has all low bits zero, then
519         // the upper bits are all zero.
520         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
521           KnownZero |= ~LowBits;
522
523         // If the first operand is negative and not all low bits are zero, then
524         // the upper bits are all one.
525         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
526           KnownOne |= ~LowBits;
527
528         KnownZero &= Mask;
529         KnownOne &= Mask;
530
531         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
532       }
533     }
534
535     // The sign bit is the LHS's sign bit, except when the result of the
536     // remainder is zero.
537     if (Mask.isNegative() && KnownZero.isNonNegative()) {
538       APInt Mask2 = APInt::getSignBit(BitWidth);
539       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
540       ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
541                         Depth+1);
542       // If it's known zero, our sign bit is also zero.
543       if (LHSKnownZero.isNegative())
544         KnownZero |= LHSKnownZero;
545     }
546
547     break;
548   case Instruction::URem: {
549     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
550       APInt RA = Rem->getValue();
551       if (RA.isPowerOf2()) {
552         APInt LowBits = (RA - 1);
553         APInt Mask2 = LowBits & Mask;
554         KnownZero |= ~LowBits & Mask;
555         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
556                           Depth+1);
557         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
558         break;
559       }
560     }
561
562     // Since the result is less than or equal to either operand, any leading
563     // zero bits in either operand must also exist in the result.
564     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
565     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
566                       TD, Depth+1);
567     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
568                       TD, Depth+1);
569
570     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
571                                 KnownZero2.countLeadingOnes());
572     KnownOne.clearAllBits();
573     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
574     break;
575   }
576
577   case Instruction::Alloca: {
578     AllocaInst *AI = cast<AllocaInst>(V);
579     unsigned Align = AI->getAlignment();
580     if (Align == 0 && TD)
581       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
582     
583     if (Align > 0)
584       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
585                                               CountTrailingZeros_32(Align));
586     break;
587   }
588   case Instruction::GetElementPtr: {
589     // Analyze all of the subscripts of this getelementptr instruction
590     // to determine if we can prove known low zero bits.
591     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
592     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
593     ComputeMaskedBits(I->getOperand(0), LocalMask,
594                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
595     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
596
597     gep_type_iterator GTI = gep_type_begin(I);
598     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
599       Value *Index = I->getOperand(i);
600       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
601         // Handle struct member offset arithmetic.
602         if (!TD) return;
603         const StructLayout *SL = TD->getStructLayout(STy);
604         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
605         uint64_t Offset = SL->getElementOffset(Idx);
606         TrailZ = std::min(TrailZ,
607                           CountTrailingZeros_64(Offset));
608       } else {
609         // Handle array index arithmetic.
610         Type *IndexedTy = GTI.getIndexedType();
611         if (!IndexedTy->isSized()) return;
612         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
613         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
614         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
615         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
616         ComputeMaskedBits(Index, LocalMask,
617                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
618         TrailZ = std::min(TrailZ,
619                           unsigned(CountTrailingZeros_64(TypeSize) +
620                                    LocalKnownZero.countTrailingOnes()));
621       }
622     }
623     
624     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
625     break;
626   }
627   case Instruction::PHI: {
628     PHINode *P = cast<PHINode>(I);
629     // Handle the case of a simple two-predecessor recurrence PHI.
630     // There's a lot more that could theoretically be done here, but
631     // this is sufficient to catch some interesting cases.
632     if (P->getNumIncomingValues() == 2) {
633       for (unsigned i = 0; i != 2; ++i) {
634         Value *L = P->getIncomingValue(i);
635         Value *R = P->getIncomingValue(!i);
636         Operator *LU = dyn_cast<Operator>(L);
637         if (!LU)
638           continue;
639         unsigned Opcode = LU->getOpcode();
640         // Check for operations that have the property that if
641         // both their operands have low zero bits, the result
642         // will have low zero bits.
643         if (Opcode == Instruction::Add ||
644             Opcode == Instruction::Sub ||
645             Opcode == Instruction::And ||
646             Opcode == Instruction::Or ||
647             Opcode == Instruction::Mul) {
648           Value *LL = LU->getOperand(0);
649           Value *LR = LU->getOperand(1);
650           // Find a recurrence.
651           if (LL == I)
652             L = LR;
653           else if (LR == I)
654             L = LL;
655           else
656             break;
657           // Ok, we have a PHI of the form L op= R. Check for low
658           // zero bits.
659           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
660           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
661           Mask2 = APInt::getLowBitsSet(BitWidth,
662                                        KnownZero2.countTrailingOnes());
663
664           // We need to take the minimum number of known bits
665           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
666           ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
667
668           KnownZero = Mask &
669                       APInt::getLowBitsSet(BitWidth,
670                                            std::min(KnownZero2.countTrailingOnes(),
671                                                     KnownZero3.countTrailingOnes()));
672           break;
673         }
674       }
675     }
676
677     // Unreachable blocks may have zero-operand PHI nodes.
678     if (P->getNumIncomingValues() == 0)
679       return;
680
681     // Otherwise take the unions of the known bit sets of the operands,
682     // taking conservative care to avoid excessive recursion.
683     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
684       // Skip if every incoming value references to ourself.
685       if (P->hasConstantValue() == P)
686         break;
687
688       KnownZero = APInt::getAllOnesValue(BitWidth);
689       KnownOne = APInt::getAllOnesValue(BitWidth);
690       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
691         // Skip direct self references.
692         if (P->getIncomingValue(i) == P) continue;
693
694         KnownZero2 = APInt(BitWidth, 0);
695         KnownOne2 = APInt(BitWidth, 0);
696         // Recurse, but cap the recursion to one level, because we don't
697         // want to waste time spinning around in loops.
698         ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
699                           KnownZero2, KnownOne2, TD, MaxDepth-1);
700         KnownZero &= KnownZero2;
701         KnownOne &= KnownOne2;
702         // If all bits have been ruled out, there's no need to check
703         // more operands.
704         if (!KnownZero && !KnownOne)
705           break;
706       }
707     }
708     break;
709   }
710   case Instruction::Call:
711     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
712       switch (II->getIntrinsicID()) {
713       default: break;
714       case Intrinsic::ctpop:
715       case Intrinsic::ctlz:
716       case Intrinsic::cttz: {
717         unsigned LowBits = Log2_32(BitWidth)+1;
718         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
719         break;
720       }
721       case Intrinsic::x86_sse42_crc32_64_8:
722       case Intrinsic::x86_sse42_crc32_64_64:
723         KnownZero = APInt::getHighBitsSet(64, 32);
724         break;
725       }
726     }
727     break;
728   }
729 }
730
731 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
732 /// one.  Convenience wrapper around ComputeMaskedBits.
733 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
734                           const TargetData *TD, unsigned Depth) {
735   unsigned BitWidth = getBitWidth(V->getType(), TD);
736   if (!BitWidth) {
737     KnownZero = false;
738     KnownOne = false;
739     return;
740   }
741   APInt ZeroBits(BitWidth, 0);
742   APInt OneBits(BitWidth, 0);
743   ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
744                     Depth);
745   KnownOne = OneBits[BitWidth - 1];
746   KnownZero = ZeroBits[BitWidth - 1];
747 }
748
749 /// isPowerOfTwo - Return true if the given value is known to have exactly one
750 /// bit set when defined. For vectors return true if every element is known to
751 /// be a power of two when defined.  Supports values with integer or pointer
752 /// types and vectors of integers.
753 bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
754                         unsigned Depth) {
755   if (Constant *C = dyn_cast<Constant>(V)) {
756     if (C->isNullValue())
757       return OrZero;
758     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
759       return CI->getValue().isPowerOf2();
760     // TODO: Handle vector constants.
761   }
762
763   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
764   // it is shifted off the end then the result is undefined.
765   if (match(V, m_Shl(m_One(), m_Value())))
766     return true;
767
768   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
769   // bottom.  If it is shifted off the bottom then the result is undefined.
770   if (match(V, m_LShr(m_SignBit(), m_Value())))
771     return true;
772
773   // The remaining tests are all recursive, so bail out if we hit the limit.
774   if (Depth++ == MaxDepth)
775     return false;
776
777   Value *X = 0, *Y = 0;
778   // A shift of a power of two is a power of two or zero.
779   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
780                  match(V, m_Shr(m_Value(X), m_Value()))))
781     return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
782
783   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
784     return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
785
786   if (SelectInst *SI = dyn_cast<SelectInst>(V))
787     return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
788       isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
789
790   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
791     // A power of two and'd with anything is a power of two or zero.
792     if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
793         isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
794       return true;
795     // X & (-X) is always a power of two or zero.
796     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
797       return true;
798     return false;
799   }
800
801   // An exact divide or right shift can only shift off zero bits, so the result
802   // is a power of two only if the first operand is a power of two and not
803   // copying a sign bit (sdiv int_min, 2).
804   if (match(V, m_LShr(m_Value(), m_Value())) ||
805       match(V, m_UDiv(m_Value(), m_Value()))) {
806     PossiblyExactOperator *PEO = cast<PossiblyExactOperator>(V);
807     if (PEO->isExact())
808       return isPowerOfTwo(PEO->getOperand(0), TD, OrZero, Depth);
809   }
810
811   return false;
812 }
813
814 /// isKnownNonZero - Return true if the given value is known to be non-zero
815 /// when defined.  For vectors return true if every element is known to be
816 /// non-zero when defined.  Supports values with integer or pointer type and
817 /// vectors of integers.
818 bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
819   if (Constant *C = dyn_cast<Constant>(V)) {
820     if (C->isNullValue())
821       return false;
822     if (isa<ConstantInt>(C))
823       // Must be non-zero due to null test above.
824       return true;
825     // TODO: Handle vectors
826     return false;
827   }
828
829   // The remaining tests are all recursive, so bail out if we hit the limit.
830   if (Depth++ >= MaxDepth)
831     return false;
832
833   unsigned BitWidth = getBitWidth(V->getType(), TD);
834
835   // X | Y != 0 if X != 0 or Y != 0.
836   Value *X = 0, *Y = 0;
837   if (match(V, m_Or(m_Value(X), m_Value(Y))))
838     return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
839
840   // ext X != 0 if X != 0.
841   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
842     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
843
844   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
845   // if the lowest bit is shifted off the end.
846   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
847     // shl nuw can't remove any non-zero bits.
848     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
849     if (BO->hasNoUnsignedWrap())
850       return isKnownNonZero(X, TD, Depth);
851
852     APInt KnownZero(BitWidth, 0);
853     APInt KnownOne(BitWidth, 0);
854     ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
855     if (KnownOne[0])
856       return true;
857   }
858   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
859   // defined if the sign bit is shifted off the end.
860   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
861     // shr exact can only shift out zero bits.
862     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
863     if (BO->isExact())
864       return isKnownNonZero(X, TD, Depth);
865
866     bool XKnownNonNegative, XKnownNegative;
867     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
868     if (XKnownNegative)
869       return true;
870   }
871   // div exact can only produce a zero if the dividend is zero.
872   else if (match(V, m_IDiv(m_Value(X), m_Value()))) {
873     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
874     if (BO->isExact())
875       return isKnownNonZero(X, TD, Depth);
876   }
877   // X + Y.
878   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
879     bool XKnownNonNegative, XKnownNegative;
880     bool YKnownNonNegative, YKnownNegative;
881     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
882     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
883
884     // If X and Y are both non-negative (as signed values) then their sum is not
885     // zero unless both X and Y are zero.
886     if (XKnownNonNegative && YKnownNonNegative)
887       if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
888         return true;
889
890     // If X and Y are both negative (as signed values) then their sum is not
891     // zero unless both X and Y equal INT_MIN.
892     if (BitWidth && XKnownNegative && YKnownNegative) {
893       APInt KnownZero(BitWidth, 0);
894       APInt KnownOne(BitWidth, 0);
895       APInt Mask = APInt::getSignedMaxValue(BitWidth);
896       // The sign bit of X is set.  If some other bit is set then X is not equal
897       // to INT_MIN.
898       ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
899       if ((KnownOne & Mask) != 0)
900         return true;
901       // The sign bit of Y is set.  If some other bit is set then Y is not equal
902       // to INT_MIN.
903       ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
904       if ((KnownOne & Mask) != 0)
905         return true;
906     }
907
908     // The sum of a non-negative number and a power of two is not zero.
909     if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
910       return true;
911     if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
912       return true;
913   }
914   // X * Y.
915   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
916     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
917     // If X and Y are non-zero then so is X * Y as long as the multiplication
918     // does not overflow.
919     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
920         isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
921       return true;
922   }
923   // (C ? X : Y) != 0 if X != 0 and Y != 0.
924   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
925     if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
926         isKnownNonZero(SI->getFalseValue(), TD, Depth))
927       return true;
928   }
929
930   if (!BitWidth) return false;
931   APInt KnownZero(BitWidth, 0);
932   APInt KnownOne(BitWidth, 0);
933   ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
934                     TD, Depth);
935   return KnownOne != 0;
936 }
937
938 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
939 /// this predicate to simplify operations downstream.  Mask is known to be zero
940 /// for bits that V cannot have.
941 ///
942 /// This function is defined on values with integer type, values with pointer
943 /// type (but only if TD is non-null), and vectors of integers.  In the case
944 /// where V is a vector, the mask, known zero, and known one values are the
945 /// same width as the vector element, and the bit is set only if it is true
946 /// for all of the elements in the vector.
947 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
948                              const TargetData *TD, unsigned Depth) {
949   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
950   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
951   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
952   return (KnownZero & Mask) == Mask;
953 }
954
955
956
957 /// ComputeNumSignBits - Return the number of times the sign bit of the
958 /// register is replicated into the other bits.  We know that at least 1 bit
959 /// is always equal to the sign bit (itself), but other cases can give us
960 /// information.  For example, immediately after an "ashr X, 2", we know that
961 /// the top 3 bits are all equal to each other, so we return 3.
962 ///
963 /// 'Op' must have a scalar integer type.
964 ///
965 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
966                                   unsigned Depth) {
967   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
968          "ComputeNumSignBits requires a TargetData object to operate "
969          "on non-integer values!");
970   Type *Ty = V->getType();
971   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
972                          Ty->getScalarSizeInBits();
973   unsigned Tmp, Tmp2;
974   unsigned FirstAnswer = 1;
975
976   // Note that ConstantInt is handled by the general ComputeMaskedBits case
977   // below.
978
979   if (Depth == 6)
980     return 1;  // Limit search depth.
981   
982   Operator *U = dyn_cast<Operator>(V);
983   switch (Operator::getOpcode(V)) {
984   default: break;
985   case Instruction::SExt:
986     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
987     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
988     
989   case Instruction::AShr:
990     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
991     // ashr X, C   -> adds C sign bits.
992     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
993       Tmp += C->getZExtValue();
994       if (Tmp > TyBits) Tmp = TyBits;
995     }
996     // vector ashr X, <C, C, C, C>  -> adds C sign bits
997     if (ConstantVector *C = dyn_cast<ConstantVector>(U->getOperand(1))) {
998       if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
999         Tmp += CI->getZExtValue();
1000         if (Tmp > TyBits) Tmp = TyBits;
1001       }
1002     }
1003     return Tmp;
1004   case Instruction::Shl:
1005     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
1006       // shl destroys sign bits.
1007       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1008       if (C->getZExtValue() >= TyBits ||      // Bad shift.
1009           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
1010       return Tmp - C->getZExtValue();
1011     }
1012     break;
1013   case Instruction::And:
1014   case Instruction::Or:
1015   case Instruction::Xor:    // NOT is handled here.
1016     // Logical binary ops preserve the number of sign bits at the worst.
1017     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1018     if (Tmp != 1) {
1019       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1020       FirstAnswer = std::min(Tmp, Tmp2);
1021       // We computed what we know about the sign bits as our first
1022       // answer. Now proceed to the generic code that uses
1023       // ComputeMaskedBits, and pick whichever answer is better.
1024     }
1025     break;
1026
1027   case Instruction::Select:
1028     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1029     if (Tmp == 1) return 1;  // Early out.
1030     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1031     return std::min(Tmp, Tmp2);
1032     
1033   case Instruction::Add:
1034     // Add can have at most one carry bit.  Thus we know that the output
1035     // is, at worst, one more bit than the inputs.
1036     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1037     if (Tmp == 1) return 1;  // Early out.
1038       
1039     // Special case decrementing a value (ADD X, -1):
1040     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
1041       if (CRHS->isAllOnesValue()) {
1042         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1043         APInt Mask = APInt::getAllOnesValue(TyBits);
1044         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1045                           Depth+1);
1046         
1047         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1048         // sign bits set.
1049         if ((KnownZero | APInt(TyBits, 1)) == Mask)
1050           return TyBits;
1051         
1052         // If we are subtracting one from a positive number, there is no carry
1053         // out of the result.
1054         if (KnownZero.isNegative())
1055           return Tmp;
1056       }
1057       
1058     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1059     if (Tmp2 == 1) return 1;
1060     return std::min(Tmp, Tmp2)-1;
1061     
1062   case Instruction::Sub:
1063     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1064     if (Tmp2 == 1) return 1;
1065       
1066     // Handle NEG.
1067     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1068       if (CLHS->isNullValue()) {
1069         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1070         APInt Mask = APInt::getAllOnesValue(TyBits);
1071         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
1072                           TD, Depth+1);
1073         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1074         // sign bits set.
1075         if ((KnownZero | APInt(TyBits, 1)) == Mask)
1076           return TyBits;
1077         
1078         // If the input is known to be positive (the sign bit is known clear),
1079         // the output of the NEG has the same number of sign bits as the input.
1080         if (KnownZero.isNegative())
1081           return Tmp2;
1082         
1083         // Otherwise, we treat this like a SUB.
1084       }
1085     
1086     // Sub can have at most one carry bit.  Thus we know that the output
1087     // is, at worst, one more bit than the inputs.
1088     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1089     if (Tmp == 1) return 1;  // Early out.
1090     return std::min(Tmp, Tmp2)-1;
1091       
1092   case Instruction::PHI: {
1093     PHINode *PN = cast<PHINode>(U);
1094     // Don't analyze large in-degree PHIs.
1095     if (PN->getNumIncomingValues() > 4) break;
1096     
1097     // Take the minimum of all incoming values.  This can't infinitely loop
1098     // because of our depth threshold.
1099     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1100     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1101       if (Tmp == 1) return Tmp;
1102       Tmp = std::min(Tmp,
1103                      ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
1104     }
1105     return Tmp;
1106   }
1107
1108   case Instruction::Trunc:
1109     // FIXME: it's tricky to do anything useful for this, but it is an important
1110     // case for targets like X86.
1111     break;
1112   }
1113   
1114   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1115   // use this information.
1116   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1117   APInt Mask = APInt::getAllOnesValue(TyBits);
1118   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1119   
1120   if (KnownZero.isNegative()) {        // sign bit is 0
1121     Mask = KnownZero;
1122   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1123     Mask = KnownOne;
1124   } else {
1125     // Nothing known.
1126     return FirstAnswer;
1127   }
1128   
1129   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1130   // the number of identical bits in the top of the input value.
1131   Mask = ~Mask;
1132   Mask <<= Mask.getBitWidth()-TyBits;
1133   // Return # leading zeros.  We use 'min' here in case Val was zero before
1134   // shifting.  We don't want to return '64' as for an i32 "0".
1135   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1136 }
1137
1138 /// ComputeMultiple - This function computes the integer multiple of Base that
1139 /// equals V.  If successful, it returns true and returns the multiple in
1140 /// Multiple.  If unsuccessful, it returns false. It looks
1141 /// through SExt instructions only if LookThroughSExt is true.
1142 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
1143                            bool LookThroughSExt, unsigned Depth) {
1144   const unsigned MaxDepth = 6;
1145
1146   assert(V && "No Value?");
1147   assert(Depth <= MaxDepth && "Limit Search Depth");
1148   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
1149
1150   Type *T = V->getType();
1151
1152   ConstantInt *CI = dyn_cast<ConstantInt>(V);
1153
1154   if (Base == 0)
1155     return false;
1156     
1157   if (Base == 1) {
1158     Multiple = V;
1159     return true;
1160   }
1161
1162   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1163   Constant *BaseVal = ConstantInt::get(T, Base);
1164   if (CO && CO == BaseVal) {
1165     // Multiple is 1.
1166     Multiple = ConstantInt::get(T, 1);
1167     return true;
1168   }
1169
1170   if (CI && CI->getZExtValue() % Base == 0) {
1171     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1172     return true;  
1173   }
1174   
1175   if (Depth == MaxDepth) return false;  // Limit search depth.
1176         
1177   Operator *I = dyn_cast<Operator>(V);
1178   if (!I) return false;
1179
1180   switch (I->getOpcode()) {
1181   default: break;
1182   case Instruction::SExt:
1183     if (!LookThroughSExt) return false;
1184     // otherwise fall through to ZExt
1185   case Instruction::ZExt:
1186     return ComputeMultiple(I->getOperand(0), Base, Multiple,
1187                            LookThroughSExt, Depth+1);
1188   case Instruction::Shl:
1189   case Instruction::Mul: {
1190     Value *Op0 = I->getOperand(0);
1191     Value *Op1 = I->getOperand(1);
1192
1193     if (I->getOpcode() == Instruction::Shl) {
1194       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1195       if (!Op1CI) return false;
1196       // Turn Op0 << Op1 into Op0 * 2^Op1
1197       APInt Op1Int = Op1CI->getValue();
1198       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
1199       APInt API(Op1Int.getBitWidth(), 0);
1200       API.setBit(BitToSet);
1201       Op1 = ConstantInt::get(V->getContext(), API);
1202     }
1203
1204     Value *Mul0 = NULL;
1205     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1206       if (Constant *Op1C = dyn_cast<Constant>(Op1))
1207         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1208           if (Op1C->getType()->getPrimitiveSizeInBits() < 
1209               MulC->getType()->getPrimitiveSizeInBits())
1210             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1211           if (Op1C->getType()->getPrimitiveSizeInBits() > 
1212               MulC->getType()->getPrimitiveSizeInBits())
1213             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1214           
1215           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1216           Multiple = ConstantExpr::getMul(MulC, Op1C);
1217           return true;
1218         }
1219
1220       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1221         if (Mul0CI->getValue() == 1) {
1222           // V == Base * Op1, so return Op1
1223           Multiple = Op1;
1224           return true;
1225         }
1226     }
1227
1228     Value *Mul1 = NULL;
1229     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1230       if (Constant *Op0C = dyn_cast<Constant>(Op0))
1231         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1232           if (Op0C->getType()->getPrimitiveSizeInBits() < 
1233               MulC->getType()->getPrimitiveSizeInBits())
1234             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1235           if (Op0C->getType()->getPrimitiveSizeInBits() > 
1236               MulC->getType()->getPrimitiveSizeInBits())
1237             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1238           
1239           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1240           Multiple = ConstantExpr::getMul(MulC, Op0C);
1241           return true;
1242         }
1243
1244       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1245         if (Mul1CI->getValue() == 1) {
1246           // V == Base * Op0, so return Op0
1247           Multiple = Op0;
1248           return true;
1249         }
1250     }
1251   }
1252   }
1253
1254   // We could not determine if V is a multiple of Base.
1255   return false;
1256 }
1257
1258 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
1259 /// value is never equal to -0.0.
1260 ///
1261 /// NOTE: this function will need to be revisited when we support non-default
1262 /// rounding modes!
1263 ///
1264 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1265   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1266     return !CFP->getValueAPF().isNegZero();
1267   
1268   if (Depth == 6)
1269     return 1;  // Limit search depth.
1270
1271   const Operator *I = dyn_cast<Operator>(V);
1272   if (I == 0) return false;
1273   
1274   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1275   if (I->getOpcode() == Instruction::FAdd &&
1276       isa<ConstantFP>(I->getOperand(1)) && 
1277       cast<ConstantFP>(I->getOperand(1))->isNullValue())
1278     return true;
1279     
1280   // sitofp and uitofp turn into +0.0 for zero.
1281   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1282     return true;
1283   
1284   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1285     // sqrt(-0.0) = -0.0, no other negative results are possible.
1286     if (II->getIntrinsicID() == Intrinsic::sqrt)
1287       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
1288   
1289   if (const CallInst *CI = dyn_cast<CallInst>(I))
1290     if (const Function *F = CI->getCalledFunction()) {
1291       if (F->isDeclaration()) {
1292         // abs(x) != -0.0
1293         if (F->getName() == "abs") return true;
1294         // fabs[lf](x) != -0.0
1295         if (F->getName() == "fabs") return true;
1296         if (F->getName() == "fabsf") return true;
1297         if (F->getName() == "fabsl") return true;
1298         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1299             F->getName() == "sqrtl")
1300           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
1301       }
1302     }
1303   
1304   return false;
1305 }
1306
1307 /// isBytewiseValue - If the specified value can be set by repeating the same
1308 /// byte in memory, return the i8 value that it is represented with.  This is
1309 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1310 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
1311 /// byte store (e.g. i16 0x1234), return null.
1312 Value *llvm::isBytewiseValue(Value *V) {
1313   // All byte-wide stores are splatable, even of arbitrary variables.
1314   if (V->getType()->isIntegerTy(8)) return V;
1315
1316   // Handle 'null' ConstantArrayZero etc.
1317   if (Constant *C = dyn_cast<Constant>(V))
1318     if (C->isNullValue())
1319       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
1320   
1321   // Constant float and double values can be handled as integer values if the
1322   // corresponding integer value is "byteable".  An important case is 0.0. 
1323   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1324     if (CFP->getType()->isFloatTy())
1325       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1326     if (CFP->getType()->isDoubleTy())
1327       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1328     // Don't handle long double formats, which have strange constraints.
1329   }
1330   
1331   // We can handle constant integers that are power of two in size and a 
1332   // multiple of 8 bits.
1333   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1334     unsigned Width = CI->getBitWidth();
1335     if (isPowerOf2_32(Width) && Width > 8) {
1336       // We can handle this value if the recursive binary decomposition is the
1337       // same at all levels.
1338       APInt Val = CI->getValue();
1339       APInt Val2;
1340       while (Val.getBitWidth() != 8) {
1341         unsigned NextWidth = Val.getBitWidth()/2;
1342         Val2  = Val.lshr(NextWidth);
1343         Val2 = Val2.trunc(Val.getBitWidth()/2);
1344         Val = Val.trunc(Val.getBitWidth()/2);
1345         
1346         // If the top/bottom halves aren't the same, reject it.
1347         if (Val != Val2)
1348           return 0;
1349       }
1350       return ConstantInt::get(V->getContext(), Val);
1351     }
1352   }
1353   
1354   // A ConstantArray is splatable if all its members are equal and also
1355   // splatable.
1356   if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1357     if (CA->getNumOperands() == 0)
1358       return 0;
1359     
1360     Value *Val = isBytewiseValue(CA->getOperand(0));
1361     if (!Val)
1362       return 0;
1363     
1364     for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I)
1365       if (CA->getOperand(I-1) != CA->getOperand(I))
1366         return 0;
1367     
1368     return Val;
1369   }
1370   
1371   // Conceptually, we could handle things like:
1372   //   %a = zext i8 %X to i16
1373   //   %b = shl i16 %a, 8
1374   //   %c = or i16 %a, %b
1375   // but until there is an example that actually needs this, it doesn't seem
1376   // worth worrying about.
1377   return 0;
1378 }
1379
1380
1381 // This is the recursive version of BuildSubAggregate. It takes a few different
1382 // arguments. Idxs is the index within the nested struct From that we are
1383 // looking at now (which is of type IndexedType). IdxSkip is the number of
1384 // indices from Idxs that should be left out when inserting into the resulting
1385 // struct. To is the result struct built so far, new insertvalue instructions
1386 // build on that.
1387 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
1388                                 SmallVector<unsigned, 10> &Idxs,
1389                                 unsigned IdxSkip,
1390                                 Instruction *InsertBefore) {
1391   llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
1392   if (STy) {
1393     // Save the original To argument so we can modify it
1394     Value *OrigTo = To;
1395     // General case, the type indexed by Idxs is a struct
1396     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1397       // Process each struct element recursively
1398       Idxs.push_back(i);
1399       Value *PrevTo = To;
1400       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1401                              InsertBefore);
1402       Idxs.pop_back();
1403       if (!To) {
1404         // Couldn't find any inserted value for this index? Cleanup
1405         while (PrevTo != OrigTo) {
1406           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1407           PrevTo = Del->getAggregateOperand();
1408           Del->eraseFromParent();
1409         }
1410         // Stop processing elements
1411         break;
1412       }
1413     }
1414     // If we successfully found a value for each of our subaggregates
1415     if (To)
1416       return To;
1417   }
1418   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1419   // the struct's elements had a value that was inserted directly. In the latter
1420   // case, perhaps we can't determine each of the subelements individually, but
1421   // we might be able to find the complete struct somewhere.
1422   
1423   // Find the value that is at that particular spot
1424   Value *V = FindInsertedValue(From, Idxs);
1425
1426   if (!V)
1427     return NULL;
1428
1429   // Insert the value in the new (sub) aggregrate
1430   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
1431                                        "tmp", InsertBefore);
1432 }
1433
1434 // This helper takes a nested struct and extracts a part of it (which is again a
1435 // struct) into a new value. For example, given the struct:
1436 // { a, { b, { c, d }, e } }
1437 // and the indices "1, 1" this returns
1438 // { c, d }.
1439 //
1440 // It does this by inserting an insertvalue for each element in the resulting
1441 // struct, as opposed to just inserting a single struct. This will only work if
1442 // each of the elements of the substruct are known (ie, inserted into From by an
1443 // insertvalue instruction somewhere).
1444 //
1445 // All inserted insertvalue instructions are inserted before InsertBefore
1446 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
1447                                 Instruction *InsertBefore) {
1448   assert(InsertBefore && "Must have someplace to insert!");
1449   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1450                                                              idx_range);
1451   Value *To = UndefValue::get(IndexedType);
1452   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
1453   unsigned IdxSkip = Idxs.size();
1454
1455   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1456 }
1457
1458 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1459 /// the scalar value indexed is already around as a register, for example if it
1460 /// were inserted directly into the aggregrate.
1461 ///
1462 /// If InsertBefore is not null, this function will duplicate (modified)
1463 /// insertvalues when a part of a nested struct is extracted.
1464 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1465                                Instruction *InsertBefore) {
1466   // Nothing to index? Just return V then (this is useful at the end of our
1467   // recursion)
1468   if (idx_range.empty())
1469     return V;
1470   // We have indices, so V should have an indexable type
1471   assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
1472          && "Not looking at a struct or array?");
1473   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range)
1474          && "Invalid indices for type?");
1475   CompositeType *PTy = cast<CompositeType>(V->getType());
1476
1477   if (isa<UndefValue>(V))
1478     return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
1479                                                               idx_range));
1480   else if (isa<ConstantAggregateZero>(V))
1481     return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy, 
1482                                                                   idx_range));
1483   else if (Constant *C = dyn_cast<Constant>(V)) {
1484     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1485       // Recursively process this constant
1486       return FindInsertedValue(C->getOperand(idx_range[0]), idx_range.slice(1),
1487                                InsertBefore);
1488   } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1489     // Loop the indices for the insertvalue instruction in parallel with the
1490     // requested indices
1491     const unsigned *req_idx = idx_range.begin();
1492     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1493          i != e; ++i, ++req_idx) {
1494       if (req_idx == idx_range.end()) {
1495         if (InsertBefore)
1496           // The requested index identifies a part of a nested aggregate. Handle
1497           // this specially. For example,
1498           // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1499           // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1500           // %C = extractvalue {i32, { i32, i32 } } %B, 1
1501           // This can be changed into
1502           // %A = insertvalue {i32, i32 } undef, i32 10, 0
1503           // %C = insertvalue {i32, i32 } %A, i32 11, 1
1504           // which allows the unused 0,0 element from the nested struct to be
1505           // removed.
1506           return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1507                                    InsertBefore);
1508         else
1509           // We can't handle this without inserting insertvalues
1510           return 0;
1511       }
1512       
1513       // This insert value inserts something else than what we are looking for.
1514       // See if the (aggregrate) value inserted into has the value we are
1515       // looking for, then.
1516       if (*req_idx != *i)
1517         return FindInsertedValue(I->getAggregateOperand(), idx_range,
1518                                  InsertBefore);
1519     }
1520     // If we end up here, the indices of the insertvalue match with those
1521     // requested (though possibly only partially). Now we recursively look at
1522     // the inserted value, passing any remaining indices.
1523     return FindInsertedValue(I->getInsertedValueOperand(),
1524                              makeArrayRef(req_idx, idx_range.end()),
1525                              InsertBefore);
1526   } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1527     // If we're extracting a value from an aggregrate that was extracted from
1528     // something else, we can extract from that something else directly instead.
1529     // However, we will need to chain I's indices with the requested indices.
1530    
1531     // Calculate the number of indices required 
1532     unsigned size = I->getNumIndices() + idx_range.size();
1533     // Allocate some space to put the new indices in
1534     SmallVector<unsigned, 5> Idxs;
1535     Idxs.reserve(size);
1536     // Add indices from the extract value instruction
1537     Idxs.append(I->idx_begin(), I->idx_end());
1538     
1539     // Add requested indices
1540     Idxs.append(idx_range.begin(), idx_range.end());
1541
1542     assert(Idxs.size() == size 
1543            && "Number of indices added not correct?");
1544     
1545     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
1546   }
1547   // Otherwise, we don't know (such as, extracting from a function return value
1548   // or load instruction)
1549   return 0;
1550 }
1551
1552 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1553 /// it can be expressed as a base pointer plus a constant offset.  Return the
1554 /// base and offset to the caller.
1555 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1556                                               const TargetData &TD) {
1557   Operator *PtrOp = dyn_cast<Operator>(Ptr);
1558   if (PtrOp == 0) return Ptr;
1559   
1560   // Just look through bitcasts.
1561   if (PtrOp->getOpcode() == Instruction::BitCast)
1562     return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1563   
1564   // If this is a GEP with constant indices, we can look through it.
1565   GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1566   if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1567   
1568   gep_type_iterator GTI = gep_type_begin(GEP);
1569   for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1570        ++I, ++GTI) {
1571     ConstantInt *OpC = cast<ConstantInt>(*I);
1572     if (OpC->isZero()) continue;
1573     
1574     // Handle a struct and array indices which add their offset to the pointer.
1575     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1576       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1577     } else {
1578       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1579       Offset += OpC->getSExtValue()*Size;
1580     }
1581   }
1582   
1583   // Re-sign extend from the pointer size if needed to get overflow edge cases
1584   // right.
1585   unsigned PtrSize = TD.getPointerSizeInBits();
1586   if (PtrSize < 64)
1587     Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1588   
1589   return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1590 }
1591
1592
1593 /// GetConstantStringInfo - This function computes the length of a
1594 /// null-terminated C string pointed to by V.  If successful, it returns true
1595 /// and returns the string in Str.  If unsuccessful, it returns false.
1596 bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1597                                  uint64_t Offset, bool StopAtNul) {
1598   // If V is NULL then return false;
1599   if (V == NULL) return false;
1600
1601   // Look through bitcast instructions.
1602   if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1603     return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1604   
1605   // If the value is not a GEP instruction nor a constant expression with a
1606   // GEP instruction, then return false because ConstantArray can't occur
1607   // any other way.
1608   const User *GEP = 0;
1609   if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1610     GEP = GEPI;
1611   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1612     if (CE->getOpcode() == Instruction::BitCast)
1613       return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1614     if (CE->getOpcode() != Instruction::GetElementPtr)
1615       return false;
1616     GEP = CE;
1617   }
1618   
1619   if (GEP) {
1620     // Make sure the GEP has exactly three arguments.
1621     if (GEP->getNumOperands() != 3)
1622       return false;
1623     
1624     // Make sure the index-ee is a pointer to array of i8.
1625     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1626     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1627     if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
1628       return false;
1629     
1630     // Check to make sure that the first operand of the GEP is an integer and
1631     // has value 0 so that we are sure we're indexing into the initializer.
1632     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1633     if (FirstIdx == 0 || !FirstIdx->isZero())
1634       return false;
1635     
1636     // If the second index isn't a ConstantInt, then this is a variable index
1637     // into the array.  If this occurs, we can't say anything meaningful about
1638     // the string.
1639     uint64_t StartIdx = 0;
1640     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1641       StartIdx = CI->getZExtValue();
1642     else
1643       return false;
1644     return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1645                                  StopAtNul);
1646   }
1647
1648   // The GEP instruction, constant or instruction, must reference a global
1649   // variable that is a constant and is initialized. The referenced constant
1650   // initializer is the array that we'll use for optimization.
1651   const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1652   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1653     return false;
1654   const Constant *GlobalInit = GV->getInitializer();
1655   
1656   // Handle the all-zeros case
1657   if (GlobalInit->isNullValue()) {
1658     // This is a degenerate case. The initializer is constant zero so the
1659     // length of the string must be zero.
1660     Str.clear();
1661     return true;
1662   }
1663   
1664   // Must be a Constant Array
1665   const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1666   if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
1667     return false;
1668   
1669   // Get the number of elements in the array
1670   uint64_t NumElts = Array->getType()->getNumElements();
1671   
1672   if (Offset > NumElts)
1673     return false;
1674   
1675   // Traverse the constant array from 'Offset' which is the place the GEP refers
1676   // to in the array.
1677   Str.reserve(NumElts-Offset);
1678   for (unsigned i = Offset; i != NumElts; ++i) {
1679     const Constant *Elt = Array->getOperand(i);
1680     const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1681     if (!CI) // This array isn't suitable, non-int initializer.
1682       return false;
1683     if (StopAtNul && CI->isZero())
1684       return true; // we found end of string, success!
1685     Str += (char)CI->getZExtValue();
1686   }
1687   
1688   // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1689   return true;
1690 }
1691
1692 // These next two are very similar to the above, but also look through PHI
1693 // nodes.
1694 // TODO: See if we can integrate these two together.
1695
1696 /// GetStringLengthH - If we can compute the length of the string pointed to by
1697 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1698 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1699   // Look through noop bitcast instructions.
1700   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1701     return GetStringLengthH(BCI->getOperand(0), PHIs);
1702
1703   // If this is a PHI node, there are two cases: either we have already seen it
1704   // or we haven't.
1705   if (PHINode *PN = dyn_cast<PHINode>(V)) {
1706     if (!PHIs.insert(PN))
1707       return ~0ULL;  // already in the set.
1708
1709     // If it was new, see if all the input strings are the same length.
1710     uint64_t LenSoFar = ~0ULL;
1711     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1712       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1713       if (Len == 0) return 0; // Unknown length -> unknown.
1714
1715       if (Len == ~0ULL) continue;
1716
1717       if (Len != LenSoFar && LenSoFar != ~0ULL)
1718         return 0;    // Disagree -> unknown.
1719       LenSoFar = Len;
1720     }
1721
1722     // Success, all agree.
1723     return LenSoFar;
1724   }
1725
1726   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1727   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1728     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1729     if (Len1 == 0) return 0;
1730     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1731     if (Len2 == 0) return 0;
1732     if (Len1 == ~0ULL) return Len2;
1733     if (Len2 == ~0ULL) return Len1;
1734     if (Len1 != Len2) return 0;
1735     return Len1;
1736   }
1737
1738   // As a special-case, "@string = constant i8 0" is also a string with zero
1739   // length, not wrapped in a bitcast or GEP.
1740   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
1741     if (GV->isConstant() && GV->hasDefinitiveInitializer())
1742       if (GV->getInitializer()->isNullValue()) return 1;
1743     return 0;
1744   }
1745
1746   // If the value is not a GEP instruction nor a constant expression with a
1747   // GEP instruction, then return unknown.
1748   User *GEP = 0;
1749   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1750     GEP = GEPI;
1751   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1752     if (CE->getOpcode() != Instruction::GetElementPtr)
1753       return 0;
1754     GEP = CE;
1755   } else {
1756     return 0;
1757   }
1758
1759   // Make sure the GEP has exactly three arguments.
1760   if (GEP->getNumOperands() != 3)
1761     return 0;
1762
1763   // Check to make sure that the first operand of the GEP is an integer and
1764   // has value 0 so that we are sure we're indexing into the initializer.
1765   if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1766     if (!Idx->isZero())
1767       return 0;
1768   } else
1769     return 0;
1770
1771   // If the second index isn't a ConstantInt, then this is a variable index
1772   // into the array.  If this occurs, we can't say anything meaningful about
1773   // the string.
1774   uint64_t StartIdx = 0;
1775   if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1776     StartIdx = CI->getZExtValue();
1777   else
1778     return 0;
1779
1780   // The GEP instruction, constant or instruction, must reference a global
1781   // variable that is a constant and is initialized. The referenced constant
1782   // initializer is the array that we'll use for optimization.
1783   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1784   if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1785       GV->mayBeOverridden())
1786     return 0;
1787   Constant *GlobalInit = GV->getInitializer();
1788
1789   // Handle the ConstantAggregateZero case, which is a degenerate case. The
1790   // initializer is constant zero so the length of the string must be zero.
1791   if (isa<ConstantAggregateZero>(GlobalInit))
1792     return 1;  // Len = 0 offset by 1.
1793
1794   // Must be a Constant Array
1795   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1796   if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1797     return false;
1798
1799   // Get the number of elements in the array
1800   uint64_t NumElts = Array->getType()->getNumElements();
1801
1802   // Traverse the constant array from StartIdx (derived above) which is
1803   // the place the GEP refers to in the array.
1804   for (unsigned i = StartIdx; i != NumElts; ++i) {
1805     Constant *Elt = Array->getOperand(i);
1806     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1807     if (!CI) // This array isn't suitable, non-int initializer.
1808       return 0;
1809     if (CI->isZero())
1810       return i-StartIdx+1; // We found end of string, success!
1811   }
1812
1813   return 0; // The array isn't null terminated, conservatively return 'unknown'.
1814 }
1815
1816 /// GetStringLength - If we can compute the length of the string pointed to by
1817 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1818 uint64_t llvm::GetStringLength(Value *V) {
1819   if (!V->getType()->isPointerTy()) return 0;
1820
1821   SmallPtrSet<PHINode*, 32> PHIs;
1822   uint64_t Len = GetStringLengthH(V, PHIs);
1823   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1824   // an empty string as a length.
1825   return Len == ~0ULL ? 1 : Len;
1826 }
1827
1828 Value *
1829 llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
1830   if (!V->getType()->isPointerTy())
1831     return V;
1832   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1833     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1834       V = GEP->getPointerOperand();
1835     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1836       V = cast<Operator>(V)->getOperand(0);
1837     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1838       if (GA->mayBeOverridden())
1839         return V;
1840       V = GA->getAliasee();
1841     } else {
1842       // See if InstructionSimplify knows any relevant tricks.
1843       if (Instruction *I = dyn_cast<Instruction>(V))
1844         // TODO: Acquire a DominatorTree and use it.
1845         if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
1846           V = Simplified;
1847           continue;
1848         }
1849
1850       return V;
1851     }
1852     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1853   }
1854   return V;
1855 }
1856
1857 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1858 /// are lifetime markers.
1859 ///
1860 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1861   for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1862        UI != UE; ++UI) {
1863     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1864     if (!II) return false;
1865
1866     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1867         II->getIntrinsicID() != Intrinsic::lifetime_end)
1868       return false;
1869   }
1870   return true;
1871 }