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