1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines that help analyze properties that chains of
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/MathExtras.h"
26 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
27 /// opcode value. Otherwise return UserOp1.
28 static unsigned getOpcode(const Value *V) {
29 if (const Instruction *I = dyn_cast<Instruction>(V))
30 return I->getOpcode();
31 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
32 return CE->getOpcode();
33 // Use UserOp1 to mean there's no opcode.
34 return Instruction::UserOp1;
38 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
39 /// known to be either zero or one and return them in the KnownZero/KnownOne
40 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
42 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
43 /// we cannot optimize based on the assumption that it is zero without changing
44 /// it to be an explicit zero. If we don't change it to zero, other code could
45 /// optimized based on the contradictory assumption that it is non-zero.
46 /// Because instcombine aggressively folds operations with undef args anyway,
47 /// this won't lose us code quality.
48 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
49 APInt &KnownZero, APInt &KnownOne,
50 TargetData *TD, unsigned Depth) {
51 const unsigned MaxDepth = 6;
52 assert(V && "No Value?");
53 assert(Depth <= MaxDepth && "Limit Search Depth");
54 unsigned BitWidth = Mask.getBitWidth();
55 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
56 "Not integer or pointer type!");
57 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
58 (!isa<IntegerType>(V->getType()) ||
59 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
60 KnownZero.getBitWidth() == BitWidth &&
61 KnownOne.getBitWidth() == BitWidth &&
62 "V, Mask, KnownOne and KnownZero should have same BitWidth");
64 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
65 // We know all of the bits for a constant!
66 KnownOne = CI->getValue() & Mask;
67 KnownZero = ~KnownOne & Mask;
71 if (isa<ConstantPointerNull>(V)) {
76 // The address of an aligned GlobalValue has trailing zeros.
77 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
78 unsigned Align = GV->getAlignment();
79 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
80 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
82 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
83 CountTrailingZeros_32(Align));
90 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
92 if (Depth == MaxDepth || Mask == 0)
93 return; // Limit search depth.
95 User *I = dyn_cast<User>(V);
98 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
99 switch (getOpcode(I)) {
101 case Instruction::And: {
102 // If either the LHS or the RHS are Zero, the result is zero.
103 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
104 APInt Mask2(Mask & ~KnownZero);
105 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
107 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
108 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
110 // Output known-1 bits are only known if set in both the LHS & RHS.
111 KnownOne &= KnownOne2;
112 // Output known-0 are known to be clear if zero in either the LHS | RHS.
113 KnownZero |= KnownZero2;
116 case Instruction::Or: {
117 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
118 APInt Mask2(Mask & ~KnownOne);
119 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
121 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
122 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
124 // Output known-0 bits are only known if clear in both the LHS & RHS.
125 KnownZero &= KnownZero2;
126 // Output known-1 are known to be set if set in either the LHS | RHS.
127 KnownOne |= KnownOne2;
130 case Instruction::Xor: {
131 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
132 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
134 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
135 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
137 // Output known-0 bits are known if clear or set in both the LHS & RHS.
138 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
139 // Output known-1 are known to be set if set in only one of the LHS, RHS.
140 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
141 KnownZero = KnownZeroOut;
144 case Instruction::Mul: {
145 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
146 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
147 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
149 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
150 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
152 // If low bits are zero in either operand, output low known-0 bits.
153 // Also compute a conserative estimate for high known-0 bits.
154 // More trickiness is possible, but this is sufficient for the
155 // interesting case of alignment computation.
157 unsigned TrailZ = KnownZero.countTrailingOnes() +
158 KnownZero2.countTrailingOnes();
159 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
160 KnownZero2.countLeadingOnes(),
161 BitWidth) - BitWidth;
163 TrailZ = std::min(TrailZ, BitWidth);
164 LeadZ = std::min(LeadZ, BitWidth);
165 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
166 APInt::getHighBitsSet(BitWidth, LeadZ);
170 case Instruction::UDiv: {
171 // For the purposes of computing leading zeros we can conservatively
172 // treat a udiv as a logical right shift by the power of 2 known to
173 // be less than the denominator.
174 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
175 ComputeMaskedBits(I->getOperand(0),
176 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
177 unsigned LeadZ = KnownZero2.countLeadingOnes();
181 ComputeMaskedBits(I->getOperand(1),
182 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
183 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
184 if (RHSUnknownLeadingOnes != BitWidth)
185 LeadZ = std::min(BitWidth,
186 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
188 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
191 case Instruction::Select:
192 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
193 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
195 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
196 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
198 // Only known if known in both the LHS and RHS.
199 KnownOne &= KnownOne2;
200 KnownZero &= KnownZero2;
202 case Instruction::FPTrunc:
203 case Instruction::FPExt:
204 case Instruction::FPToUI:
205 case Instruction::FPToSI:
206 case Instruction::SIToFP:
207 case Instruction::UIToFP:
208 return; // Can't work with floating point.
209 case Instruction::PtrToInt:
210 case Instruction::IntToPtr:
211 // We can't handle these if we don't know the pointer size.
213 // FALL THROUGH and handle them the same as zext/trunc.
214 case Instruction::ZExt:
215 case Instruction::Trunc: {
216 // Note that we handle pointer operands here because of inttoptr/ptrtoint
217 // which fall through here.
218 const Type *SrcTy = I->getOperand(0)->getType();
219 unsigned SrcBitWidth = TD ?
220 TD->getTypeSizeInBits(SrcTy) :
221 SrcTy->getPrimitiveSizeInBits();
223 MaskIn.zextOrTrunc(SrcBitWidth);
224 KnownZero.zextOrTrunc(SrcBitWidth);
225 KnownOne.zextOrTrunc(SrcBitWidth);
226 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
228 KnownZero.zextOrTrunc(BitWidth);
229 KnownOne.zextOrTrunc(BitWidth);
230 // Any top bits are known to be zero.
231 if (BitWidth > SrcBitWidth)
232 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
235 case Instruction::BitCast: {
236 const Type *SrcTy = I->getOperand(0)->getType();
237 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
238 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
244 case Instruction::SExt: {
245 // Compute the bits in the result that are not present in the input.
246 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
247 unsigned SrcBitWidth = SrcTy->getBitWidth();
250 MaskIn.trunc(SrcBitWidth);
251 KnownZero.trunc(SrcBitWidth);
252 KnownOne.trunc(SrcBitWidth);
253 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
255 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
256 KnownZero.zext(BitWidth);
257 KnownOne.zext(BitWidth);
259 // If the sign bit of the input is known set or clear, then we know the
260 // top bits of the result.
261 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
262 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
263 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
264 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
267 case Instruction::Shl:
268 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
269 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
270 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
271 APInt Mask2(Mask.lshr(ShiftAmt));
272 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
274 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
275 KnownZero <<= ShiftAmt;
276 KnownOne <<= ShiftAmt;
277 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
281 case Instruction::LShr:
282 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
283 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
284 // Compute the new bits that are at the top now.
285 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
287 // Unsigned shift right.
288 APInt Mask2(Mask.shl(ShiftAmt));
289 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
291 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
292 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
293 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
294 // high bits known zero.
295 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
299 case Instruction::AShr:
300 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
301 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
302 // Compute the new bits that are at the top now.
303 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
305 // Signed shift right.
306 APInt Mask2(Mask.shl(ShiftAmt));
307 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
309 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
310 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
311 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
314 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
315 KnownZero |= HighBits;
316 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
317 KnownOne |= HighBits;
321 case Instruction::Sub: {
322 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
323 // We know that the top bits of C-X are clear if X contains less bits
324 // than C (i.e. no wrap-around can happen). For example, 20-X is
325 // positive if we can prove that X is >= 0 and < 16.
326 if (!CLHS->getValue().isNegative()) {
327 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
328 // NLZ can't be BitWidth with no sign bit
329 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
330 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
333 // If all of the MaskV bits are known to be zero, then we know the
334 // output top bits are zero, because we now know that the output is
336 if ((KnownZero2 & MaskV) == MaskV) {
337 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
338 // Top bits known zero.
339 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
345 case Instruction::Add: {
346 // If one of the operands has trailing zeros, than the bits that the
347 // other operand has in those bit positions will be preserved in the
348 // result. For an add, this works with either operand. For a subtract,
349 // this only works if the known zeros are in the right operand.
350 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
351 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
352 BitWidth - Mask.countLeadingZeros());
353 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
355 assert((LHSKnownZero & LHSKnownOne) == 0 &&
356 "Bits known to be one AND zero?");
357 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
359 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
361 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
362 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
364 // Determine which operand has more trailing zeros, and use that
365 // many bits from the other operand.
366 if (LHSKnownZeroOut > RHSKnownZeroOut) {
367 if (getOpcode(I) == Instruction::Add) {
368 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
369 KnownZero |= KnownZero2 & Mask;
370 KnownOne |= KnownOne2 & Mask;
372 // If the known zeros are in the left operand for a subtract,
373 // fall back to the minimum known zeros in both operands.
374 KnownZero |= APInt::getLowBitsSet(BitWidth,
375 std::min(LHSKnownZeroOut,
378 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
379 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
380 KnownZero |= LHSKnownZero & Mask;
381 KnownOne |= LHSKnownOne & Mask;
385 case Instruction::SRem:
386 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
387 APInt RA = Rem->getValue();
388 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
389 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
390 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
391 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
394 // If the sign bit of the first operand is zero, the sign bit of
395 // the result is zero. If the first operand has no one bits below
396 // the second operand's single 1 bit, its sign will be zero.
397 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
398 KnownZero2 |= ~LowBits;
400 KnownZero |= KnownZero2 & Mask;
402 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
406 case Instruction::URem: {
407 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
408 APInt RA = Rem->getValue();
409 if (RA.isPowerOf2()) {
410 APInt LowBits = (RA - 1);
411 APInt Mask2 = LowBits & Mask;
412 KnownZero |= ~LowBits & Mask;
413 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
415 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
420 // Since the result is less than or equal to either operand, any leading
421 // zero bits in either operand must also exist in the result.
422 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
423 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
425 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
428 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
429 KnownZero2.countLeadingOnes());
431 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
435 case Instruction::Alloca:
436 case Instruction::Malloc: {
437 AllocationInst *AI = cast<AllocationInst>(V);
438 unsigned Align = AI->getAlignment();
439 if (Align == 0 && TD) {
440 if (isa<AllocaInst>(AI))
441 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
442 else if (isa<MallocInst>(AI)) {
443 // Malloc returns maximally aligned memory.
444 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
447 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
450 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
455 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
456 CountTrailingZeros_32(Align));
459 case Instruction::GetElementPtr: {
460 // Analyze all of the subscripts of this getelementptr instruction
461 // to determine if we can prove known low zero bits.
462 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
463 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
464 ComputeMaskedBits(I->getOperand(0), LocalMask,
465 LocalKnownZero, LocalKnownOne, TD, Depth+1);
466 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
468 gep_type_iterator GTI = gep_type_begin(I);
469 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
470 Value *Index = I->getOperand(i);
471 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
472 // Handle struct member offset arithmetic.
474 const StructLayout *SL = TD->getStructLayout(STy);
475 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
476 uint64_t Offset = SL->getElementOffset(Idx);
477 TrailZ = std::min(TrailZ,
478 CountTrailingZeros_64(Offset));
480 // Handle array index arithmetic.
481 const Type *IndexedTy = GTI.getIndexedType();
482 if (!IndexedTy->isSized()) return;
483 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
484 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
485 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
486 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
487 ComputeMaskedBits(Index, LocalMask,
488 LocalKnownZero, LocalKnownOne, TD, Depth+1);
489 TrailZ = std::min(TrailZ,
490 unsigned(CountTrailingZeros_64(TypeSize) +
491 LocalKnownZero.countTrailingOnes()));
495 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
498 case Instruction::PHI: {
499 PHINode *P = cast<PHINode>(I);
500 // Handle the case of a simple two-predecessor recurrence PHI.
501 // There's a lot more that could theoretically be done here, but
502 // this is sufficient to catch some interesting cases.
503 if (P->getNumIncomingValues() == 2) {
504 for (unsigned i = 0; i != 2; ++i) {
505 Value *L = P->getIncomingValue(i);
506 Value *R = P->getIncomingValue(!i);
507 User *LU = dyn_cast<User>(L);
510 unsigned Opcode = getOpcode(LU);
511 // Check for operations that have the property that if
512 // both their operands have low zero bits, the result
513 // will have low zero bits.
514 if (Opcode == Instruction::Add ||
515 Opcode == Instruction::Sub ||
516 Opcode == Instruction::And ||
517 Opcode == Instruction::Or ||
518 Opcode == Instruction::Mul) {
519 Value *LL = LU->getOperand(0);
520 Value *LR = LU->getOperand(1);
521 // Find a recurrence.
528 // Ok, we have a PHI of the form L op= R. Check for low
530 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
531 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
532 Mask2 = APInt::getLowBitsSet(BitWidth,
533 KnownZero2.countTrailingOnes());
535 // We need to take the minimum number of known bits
536 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
537 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
540 APInt::getLowBitsSet(BitWidth,
541 std::min(KnownZero2.countTrailingOnes(),
542 KnownZero3.countTrailingOnes()));
548 // Otherwise take the unions of the known bit sets of the operands,
549 // taking conservative care to avoid excessive recursion.
550 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
551 KnownZero = APInt::getAllOnesValue(BitWidth);
552 KnownOne = APInt::getAllOnesValue(BitWidth);
553 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
554 // Skip direct self references.
555 if (P->getIncomingValue(i) == P) continue;
557 KnownZero2 = APInt(BitWidth, 0);
558 KnownOne2 = APInt(BitWidth, 0);
559 // Recurse, but cap the recursion to one level, because we don't
560 // want to waste time spinning around in loops.
561 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
562 KnownZero2, KnownOne2, TD, MaxDepth-1);
563 KnownZero &= KnownZero2;
564 KnownOne &= KnownOne2;
565 // If all bits have been ruled out, there's no need to check
567 if (!KnownZero && !KnownOne)
573 case Instruction::Call:
574 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
575 switch (II->getIntrinsicID()) {
577 case Intrinsic::ctpop:
578 case Intrinsic::ctlz:
579 case Intrinsic::cttz: {
580 unsigned LowBits = Log2_32(BitWidth)+1;
581 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
590 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
591 /// this predicate to simplify operations downstream. Mask is known to be zero
592 /// for bits that V cannot have.
593 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
594 TargetData *TD, unsigned Depth) {
595 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
596 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
597 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
598 return (KnownZero & Mask) == Mask;
603 /// ComputeNumSignBits - Return the number of times the sign bit of the
604 /// register is replicated into the other bits. We know that at least 1 bit
605 /// is always equal to the sign bit (itself), but other cases can give us
606 /// information. For example, immediately after an "ashr X, 2", we know that
607 /// the top 3 bits are all equal to each other, so we return 3.
609 /// 'Op' must have a scalar integer type.
611 unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
612 const IntegerType *Ty = cast<IntegerType>(V->getType());
613 unsigned TyBits = Ty->getBitWidth();
615 unsigned FirstAnswer = 1;
617 // Note that ConstantInt is handled by the general ComputeMaskedBits case
621 return 1; // Limit search depth.
623 User *U = dyn_cast<User>(V);
624 switch (getOpcode(V)) {
626 case Instruction::SExt:
627 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
628 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
630 case Instruction::AShr:
631 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
632 // ashr X, C -> adds C sign bits.
633 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
634 Tmp += C->getZExtValue();
635 if (Tmp > TyBits) Tmp = TyBits;
638 case Instruction::Shl:
639 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
640 // shl destroys sign bits.
641 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
642 if (C->getZExtValue() >= TyBits || // Bad shift.
643 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
644 return Tmp - C->getZExtValue();
647 case Instruction::And:
648 case Instruction::Or:
649 case Instruction::Xor: // NOT is handled here.
650 // Logical binary ops preserve the number of sign bits at the worst.
651 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
653 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
654 FirstAnswer = std::min(Tmp, Tmp2);
655 // We computed what we know about the sign bits as our first
656 // answer. Now proceed to the generic code that uses
657 // ComputeMaskedBits, and pick whichever answer is better.
661 case Instruction::Select:
662 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
663 if (Tmp == 1) return 1; // Early out.
664 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
665 return std::min(Tmp, Tmp2);
667 case Instruction::Add:
668 // Add can have at most one carry bit. Thus we know that the output
669 // is, at worst, one more bit than the inputs.
670 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
671 if (Tmp == 1) return 1; // Early out.
673 // Special case decrementing a value (ADD X, -1):
674 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
675 if (CRHS->isAllOnesValue()) {
676 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
677 APInt Mask = APInt::getAllOnesValue(TyBits);
678 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
681 // If the input is known to be 0 or 1, the output is 0/-1, which is all
683 if ((KnownZero | APInt(TyBits, 1)) == Mask)
686 // If we are subtracting one from a positive number, there is no carry
687 // out of the result.
688 if (KnownZero.isNegative())
692 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
693 if (Tmp2 == 1) return 1;
694 return std::min(Tmp, Tmp2)-1;
697 case Instruction::Sub:
698 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
699 if (Tmp2 == 1) return 1;
702 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
703 if (CLHS->isNullValue()) {
704 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
705 APInt Mask = APInt::getAllOnesValue(TyBits);
706 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
708 // If the input is known to be 0 or 1, the output is 0/-1, which is all
710 if ((KnownZero | APInt(TyBits, 1)) == Mask)
713 // If the input is known to be positive (the sign bit is known clear),
714 // the output of the NEG has the same number of sign bits as the input.
715 if (KnownZero.isNegative())
718 // Otherwise, we treat this like a SUB.
721 // Sub can have at most one carry bit. Thus we know that the output
722 // is, at worst, one more bit than the inputs.
723 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
724 if (Tmp == 1) return 1; // Early out.
725 return std::min(Tmp, Tmp2)-1;
727 case Instruction::Trunc:
728 // FIXME: it's tricky to do anything useful for this, but it is an important
729 // case for targets like X86.
733 // Finally, if we can prove that the top bits of the result are 0's or 1's,
734 // use this information.
735 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
736 APInt Mask = APInt::getAllOnesValue(TyBits);
737 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
739 if (KnownZero.isNegative()) { // sign bit is 0
741 } else if (KnownOne.isNegative()) { // sign bit is 1;
748 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
749 // the number of identical bits in the top of the input value.
751 Mask <<= Mask.getBitWidth()-TyBits;
752 // Return # leading zeros. We use 'min' here in case Val was zero before
753 // shifting. We don't want to return '64' as for an i32 "0".
754 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
757 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
758 /// value is never equal to -0.0.
760 /// NOTE: this function will need to be revisited when we support non-default
763 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
764 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
765 return !CFP->getValueAPF().isNegZero();
768 return 1; // Limit search depth.
770 const Instruction *I = dyn_cast<Instruction>(V);
771 if (I == 0) return false;
773 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
774 if (I->getOpcode() == Instruction::FAdd &&
775 isa<ConstantFP>(I->getOperand(1)) &&
776 cast<ConstantFP>(I->getOperand(1))->isNullValue())
779 // sitofp and uitofp turn into +0.0 for zero.
780 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
783 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
784 // sqrt(-0.0) = -0.0, no other negative results are possible.
785 if (II->getIntrinsicID() == Intrinsic::sqrt)
786 return CannotBeNegativeZero(II->getOperand(1), Depth+1);
788 if (const CallInst *CI = dyn_cast<CallInst>(I))
789 if (const Function *F = CI->getCalledFunction()) {
790 if (F->isDeclaration()) {
791 switch (F->getNameLen()) {
792 case 3: // abs(x) != -0.0
793 if (!strcmp(F->getNameStart(), "abs")) return true;
795 case 4: // abs[lf](x) != -0.0
796 if (!strcmp(F->getNameStart(), "absf")) return true;
797 if (!strcmp(F->getNameStart(), "absl")) return true;
806 // This is the recursive version of BuildSubAggregate. It takes a few different
807 // arguments. Idxs is the index within the nested struct From that we are
808 // looking at now (which is of type IndexedType). IdxSkip is the number of
809 // indices from Idxs that should be left out when inserting into the resulting
810 // struct. To is the result struct built so far, new insertvalue instructions
812 Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
813 SmallVector<unsigned, 10> &Idxs,
815 Instruction *InsertBefore) {
816 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
818 // Save the original To argument so we can modify it
820 // General case, the type indexed by Idxs is a struct
821 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
822 // Process each struct element recursively
825 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
829 // Couldn't find any inserted value for this index? Cleanup
830 while (PrevTo != OrigTo) {
831 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
832 PrevTo = Del->getAggregateOperand();
833 Del->eraseFromParent();
835 // Stop processing elements
839 // If we succesfully found a value for each of our subaggregates
843 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
844 // the struct's elements had a value that was inserted directly. In the latter
845 // case, perhaps we can't determine each of the subelements individually, but
846 // we might be able to find the complete struct somewhere.
848 // Find the value that is at that particular spot
849 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
854 // Insert the value in the new (sub) aggregrate
855 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
856 Idxs.end(), "tmp", InsertBefore);
859 // This helper takes a nested struct and extracts a part of it (which is again a
860 // struct) into a new value. For example, given the struct:
861 // { a, { b, { c, d }, e } }
862 // and the indices "1, 1" this returns
865 // It does this by inserting an insertvalue for each element in the resulting
866 // struct, as opposed to just inserting a single struct. This will only work if
867 // each of the elements of the substruct are known (ie, inserted into From by an
868 // insertvalue instruction somewhere).
870 // All inserted insertvalue instructions are inserted before InsertBefore
871 Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
872 const unsigned *idx_end, Instruction *InsertBefore) {
873 assert(InsertBefore && "Must have someplace to insert!");
874 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
877 Value *To = UndefValue::get(IndexedType);
878 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
879 unsigned IdxSkip = Idxs.size();
881 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
884 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
885 /// the scalar value indexed is already around as a register, for example if it
886 /// were inserted directly into the aggregrate.
888 /// If InsertBefore is not null, this function will duplicate (modified)
889 /// insertvalues when a part of a nested struct is extracted.
890 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
891 const unsigned *idx_end, Instruction *InsertBefore) {
892 // Nothing to index? Just return V then (this is useful at the end of our
894 if (idx_begin == idx_end)
896 // We have indices, so V should have an indexable type
897 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
898 && "Not looking at a struct or array?");
899 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
900 && "Invalid indices for type?");
901 const CompositeType *PTy = cast<CompositeType>(V->getType());
903 if (isa<UndefValue>(V))
904 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
907 else if (isa<ConstantAggregateZero>(V))
908 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
911 else if (Constant *C = dyn_cast<Constant>(V)) {
912 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
913 // Recursively process this constant
914 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1, idx_end,
916 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
917 // Loop the indices for the insertvalue instruction in parallel with the
919 const unsigned *req_idx = idx_begin;
920 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
921 i != e; ++i, ++req_idx) {
922 if (req_idx == idx_end) {
924 // The requested index identifies a part of a nested aggregate. Handle
925 // this specially. For example,
926 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
927 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
928 // %C = extractvalue {i32, { i32, i32 } } %B, 1
929 // This can be changed into
930 // %A = insertvalue {i32, i32 } undef, i32 10, 0
931 // %C = insertvalue {i32, i32 } %A, i32 11, 1
932 // which allows the unused 0,0 element from the nested struct to be
934 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
936 // We can't handle this without inserting insertvalues
940 // This insert value inserts something else than what we are looking for.
941 // See if the (aggregrate) value inserted into has the value we are
942 // looking for, then.
944 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
947 // If we end up here, the indices of the insertvalue match with those
948 // requested (though possibly only partially). Now we recursively look at
949 // the inserted value, passing any remaining indices.
950 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
952 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
953 // If we're extracting a value from an aggregrate that was extracted from
954 // something else, we can extract from that something else directly instead.
955 // However, we will need to chain I's indices with the requested indices.
957 // Calculate the number of indices required
958 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
959 // Allocate some space to put the new indices in
960 SmallVector<unsigned, 5> Idxs;
962 // Add indices from the extract value instruction
963 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
967 // Add requested indices
968 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
971 assert(Idxs.size() == size
972 && "Number of indices added not correct?");
974 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
977 // Otherwise, we don't know (such as, extracting from a function return value
978 // or load instruction)
982 /// GetConstantStringInfo - This function computes the length of a
983 /// null-terminated C string pointed to by V. If successful, it returns true
984 /// and returns the string in Str. If unsuccessful, it returns false.
985 bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
987 // If V is NULL then return false;
988 if (V == NULL) return false;
990 // Look through bitcast instructions.
991 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
992 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
994 // If the value is not a GEP instruction nor a constant expression with a
995 // GEP instruction, then return false because ConstantArray can't occur
998 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1000 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1001 if (CE->getOpcode() == Instruction::BitCast)
1002 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1003 if (CE->getOpcode() != Instruction::GetElementPtr)
1009 // Make sure the GEP has exactly three arguments.
1010 if (GEP->getNumOperands() != 3)
1013 // Make sure the index-ee is a pointer to array of i8.
1014 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1015 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1016 if (AT == 0 || AT->getElementType() != Type::Int8Ty)
1019 // Check to make sure that the first operand of the GEP is an integer and
1020 // has value 0 so that we are sure we're indexing into the initializer.
1021 ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1022 if (FirstIdx == 0 || !FirstIdx->isZero())
1025 // If the second index isn't a ConstantInt, then this is a variable index
1026 // into the array. If this occurs, we can't say anything meaningful about
1028 uint64_t StartIdx = 0;
1029 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1030 StartIdx = CI->getZExtValue();
1033 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1037 // The GEP instruction, constant or instruction, must reference a global
1038 // variable that is a constant and is initialized. The referenced constant
1039 // initializer is the array that we'll use for optimization.
1040 GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1041 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1043 Constant *GlobalInit = GV->getInitializer();
1045 // Handle the ConstantAggregateZero case
1046 if (isa<ConstantAggregateZero>(GlobalInit)) {
1047 // This is a degenerate case. The initializer is constant zero so the
1048 // length of the string must be zero.
1053 // Must be a Constant Array
1054 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1055 if (Array == 0 || Array->getType()->getElementType() != Type::Int8Ty)
1058 // Get the number of elements in the array
1059 uint64_t NumElts = Array->getType()->getNumElements();
1061 if (Offset > NumElts)
1064 // Traverse the constant array from 'Offset' which is the place the GEP refers
1066 Str.reserve(NumElts-Offset);
1067 for (unsigned i = Offset; i != NumElts; ++i) {
1068 Constant *Elt = Array->getOperand(i);
1069 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1070 if (!CI) // This array isn't suitable, non-int initializer.
1072 if (StopAtNul && CI->isZero())
1073 return true; // we found end of string, success!
1074 Str += (char)CI->getZExtValue();
1077 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.