blob: b956d390a813370a26b18b2327a2c04014628916 [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"
Evan Cheng0ff39b32008-06-30 07:31:25 +000018#include "llvm/GlobalVariable.h"
Chris Lattner173234a2008-06-02 01:18:21 +000019#include "llvm/IntrinsicInst.h"
20#include "llvm/Target/TargetData.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/MathExtras.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000023#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000024using namespace llvm;
25
26/// getOpcode - If this is an Instruction or a ConstantExpr, return the
27/// opcode value. Otherwise return UserOp1.
28static 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;
35}
36
37
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
41/// processing.
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.
48void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
49 APInt &KnownZero, APInt &KnownOne,
50 TargetData *TD, unsigned Depth) {
51 assert(V && "No Value?");
52 assert(Depth <= 6 && "Limit Search Depth");
53 uint32_t BitWidth = Mask.getBitWidth();
54 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
55 "Not integer or pointer type!");
56 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
57 (!isa<IntegerType>(V->getType()) ||
58 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
59 KnownZero.getBitWidth() == BitWidth &&
60 KnownOne.getBitWidth() == BitWidth &&
61 "V, Mask, KnownOne and KnownZero should have same BitWidth");
62
63 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
64 // We know all of the bits for a constant!
65 KnownOne = CI->getValue() & Mask;
66 KnownZero = ~KnownOne & Mask;
67 return;
68 }
69 // Null is all-zeros.
70 if (isa<ConstantPointerNull>(V)) {
71 KnownOne.clear();
72 KnownZero = Mask;
73 return;
74 }
75 // The address of an aligned GlobalValue has trailing zeros.
76 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
77 unsigned Align = GV->getAlignment();
78 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
79 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
80 if (Align > 0)
81 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
82 CountTrailingZeros_32(Align));
83 else
84 KnownZero.clear();
85 KnownOne.clear();
86 return;
87 }
88
89 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
90
91 if (Depth == 6 || Mask == 0)
92 return; // Limit search depth.
93
94 User *I = dyn_cast<User>(V);
95 if (!I) return;
96
97 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
98 switch (getOpcode(I)) {
99 default: break;
100 case Instruction::And: {
101 // If either the LHS or the RHS are Zero, the result is zero.
102 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
103 APInt Mask2(Mask & ~KnownZero);
104 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
105 Depth+1);
106 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
107 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
108
109 // Output known-1 bits are only known if set in both the LHS & RHS.
110 KnownOne &= KnownOne2;
111 // Output known-0 are known to be clear if zero in either the LHS | RHS.
112 KnownZero |= KnownZero2;
113 return;
114 }
115 case Instruction::Or: {
116 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
117 APInt Mask2(Mask & ~KnownOne);
118 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
119 Depth+1);
120 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
121 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
122
123 // Output known-0 bits are only known if clear in both the LHS & RHS.
124 KnownZero &= KnownZero2;
125 // Output known-1 are known to be set if set in either the LHS | RHS.
126 KnownOne |= KnownOne2;
127 return;
128 }
129 case Instruction::Xor: {
130 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
131 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
132 Depth+1);
133 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
134 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
135
136 // Output known-0 bits are known if clear or set in both the LHS & RHS.
137 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
138 // Output known-1 are known to be set if set in only one of the LHS, RHS.
139 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
140 KnownZero = KnownZeroOut;
141 return;
142 }
143 case Instruction::Mul: {
144 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
145 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
146 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
147 Depth+1);
148 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
149 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
150
151 // If low bits are zero in either operand, output low known-0 bits.
152 // Also compute a conserative estimate for high known-0 bits.
153 // More trickiness is possible, but this is sufficient for the
154 // interesting case of alignment computation.
155 KnownOne.clear();
156 unsigned TrailZ = KnownZero.countTrailingOnes() +
157 KnownZero2.countTrailingOnes();
158 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
159 KnownZero2.countLeadingOnes(),
160 BitWidth) - BitWidth;
161
162 TrailZ = std::min(TrailZ, BitWidth);
163 LeadZ = std::min(LeadZ, BitWidth);
164 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
165 APInt::getHighBitsSet(BitWidth, LeadZ);
166 KnownZero &= Mask;
167 return;
168 }
169 case Instruction::UDiv: {
170 // For the purposes of computing leading zeros we can conservatively
171 // treat a udiv as a logical right shift by the power of 2 known to
172 // be less than the denominator.
173 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
174 ComputeMaskedBits(I->getOperand(0),
175 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
176 unsigned LeadZ = KnownZero2.countLeadingOnes();
177
178 KnownOne2.clear();
179 KnownZero2.clear();
180 ComputeMaskedBits(I->getOperand(1),
181 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
182 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
183 if (RHSUnknownLeadingOnes != BitWidth)
184 LeadZ = std::min(BitWidth,
185 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
186
187 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
188 return;
189 }
190 case Instruction::Select:
191 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
192 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
193 Depth+1);
194 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
195 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
196
197 // Only known if known in both the LHS and RHS.
198 KnownOne &= KnownOne2;
199 KnownZero &= KnownZero2;
200 return;
201 case Instruction::FPTrunc:
202 case Instruction::FPExt:
203 case Instruction::FPToUI:
204 case Instruction::FPToSI:
205 case Instruction::SIToFP:
206 case Instruction::UIToFP:
207 return; // Can't work with floating point.
208 case Instruction::PtrToInt:
209 case Instruction::IntToPtr:
210 // We can't handle these if we don't know the pointer size.
211 if (!TD) return;
212 // FALL THROUGH and handle them the same as zext/trunc.
213 case Instruction::ZExt:
214 case Instruction::Trunc: {
215 // Note that we handle pointer operands here because of inttoptr/ptrtoint
216 // which fall through here.
217 const Type *SrcTy = I->getOperand(0)->getType();
218 uint32_t SrcBitWidth = TD ?
219 TD->getTypeSizeInBits(SrcTy) :
220 SrcTy->getPrimitiveSizeInBits();
221 APInt MaskIn(Mask);
222 MaskIn.zextOrTrunc(SrcBitWidth);
223 KnownZero.zextOrTrunc(SrcBitWidth);
224 KnownOne.zextOrTrunc(SrcBitWidth);
225 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
226 Depth+1);
227 KnownZero.zextOrTrunc(BitWidth);
228 KnownOne.zextOrTrunc(BitWidth);
229 // Any top bits are known to be zero.
230 if (BitWidth > SrcBitWidth)
231 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
232 return;
233 }
234 case Instruction::BitCast: {
235 const Type *SrcTy = I->getOperand(0)->getType();
236 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
237 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
238 Depth+1);
239 return;
240 }
241 break;
242 }
243 case Instruction::SExt: {
244 // Compute the bits in the result that are not present in the input.
245 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
246 uint32_t SrcBitWidth = SrcTy->getBitWidth();
247
248 APInt MaskIn(Mask);
249 MaskIn.trunc(SrcBitWidth);
250 KnownZero.trunc(SrcBitWidth);
251 KnownOne.trunc(SrcBitWidth);
252 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
253 Depth+1);
254 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
255 KnownZero.zext(BitWidth);
256 KnownOne.zext(BitWidth);
257
258 // If the sign bit of the input is known set or clear, then we know the
259 // top bits of the result.
260 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
261 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
262 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
263 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
264 return;
265 }
266 case Instruction::Shl:
267 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
268 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
269 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
270 APInt Mask2(Mask.lshr(ShiftAmt));
271 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
272 Depth+1);
273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
274 KnownZero <<= ShiftAmt;
275 KnownOne <<= ShiftAmt;
276 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
277 return;
278 }
279 break;
280 case Instruction::LShr:
281 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
282 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
283 // Compute the new bits that are at the top now.
284 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
285
286 // Unsigned shift right.
287 APInt Mask2(Mask.shl(ShiftAmt));
288 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
289 Depth+1);
290 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
291 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
292 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
293 // high bits known zero.
294 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
295 return;
296 }
297 break;
298 case Instruction::AShr:
299 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
300 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
301 // Compute the new bits that are at the top now.
302 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
303
304 // Signed shift right.
305 APInt Mask2(Mask.shl(ShiftAmt));
306 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
307 Depth+1);
308 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
309 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
310 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
311
312 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
313 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
314 KnownZero |= HighBits;
315 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
316 KnownOne |= HighBits;
317 return;
318 }
319 break;
320 case Instruction::Sub: {
321 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
322 // We know that the top bits of C-X are clear if X contains less bits
323 // than C (i.e. no wrap-around can happen). For example, 20-X is
324 // positive if we can prove that X is >= 0 and < 16.
325 if (!CLHS->getValue().isNegative()) {
326 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
327 // NLZ can't be BitWidth with no sign bit
328 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
329 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
330 TD, Depth+1);
331
332 // If all of the MaskV bits are known to be zero, then we know the
333 // output top bits are zero, because we now know that the output is
334 // from [0-C].
335 if ((KnownZero2 & MaskV) == MaskV) {
336 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
337 // Top bits known zero.
338 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
339 }
340 }
341 }
342 }
343 // fall through
344 case Instruction::Add: {
345 // Output known-0 bits are known if clear or set in both the low clear bits
346 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
347 // low 3 bits clear.
348 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
349 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
350 Depth+1);
351 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
352 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
353
354 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
355 Depth+1);
356 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
357 KnownZeroOut = std::min(KnownZeroOut,
358 KnownZero2.countTrailingOnes());
359
360 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
361 return;
362 }
363 case Instruction::SRem:
364 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
365 APInt RA = Rem->getValue();
366 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
367 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
368 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
369 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
370 Depth+1);
371
Dan Gohmana60832b2008-08-13 23:12:35 +0000372 // If the sign bit of the first operand is zero, the sign bit of
373 // the result is zero. If the first operand has no one bits below
374 // the second operand's single 1 bit, its sign will be zero.
Chris Lattner173234a2008-06-02 01:18:21 +0000375 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
376 KnownZero2 |= ~LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000377
378 KnownZero |= KnownZero2 & Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000379
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());
David Greenedce51c32008-08-21 20:45:12 +0000512
513 // We need to take the minimum number of known bits
514 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
515 KnownOne3.clear();
516 KnownZero3.clear();
517 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
518
Chris Lattner173234a2008-06-02 01:18:21 +0000519 KnownZero = Mask &
520 APInt::getLowBitsSet(BitWidth,
521 KnownZero2.countTrailingOnes());
522 break;
523 }
524 }
525 }
526 break;
527 }
528 case Instruction::Call:
529 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
530 switch (II->getIntrinsicID()) {
531 default: break;
532 case Intrinsic::ctpop:
533 case Intrinsic::ctlz:
534 case Intrinsic::cttz: {
535 unsigned LowBits = Log2_32(BitWidth)+1;
536 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
537 break;
538 }
539 }
540 }
541 break;
542 }
543}
544
545/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
546/// this predicate to simplify operations downstream. Mask is known to be zero
547/// for bits that V cannot have.
548bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
549 TargetData *TD, unsigned Depth) {
550 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
551 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
552 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
553 return (KnownZero & Mask) == Mask;
554}
555
556
557
558/// ComputeNumSignBits - Return the number of times the sign bit of the
559/// register is replicated into the other bits. We know that at least 1 bit
560/// is always equal to the sign bit (itself), but other cases can give us
561/// information. For example, immediately after an "ashr X, 2", we know that
562/// the top 3 bits are all equal to each other, so we return 3.
563///
564/// 'Op' must have a scalar integer type.
565///
566unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
567 const IntegerType *Ty = cast<IntegerType>(V->getType());
568 unsigned TyBits = Ty->getBitWidth();
569 unsigned Tmp, Tmp2;
570 unsigned FirstAnswer = 1;
571
Chris Lattnerd82e5112008-06-02 18:39:07 +0000572 // Note that ConstantInt is handled by the general ComputeMaskedBits case
573 // below.
574
Chris Lattner173234a2008-06-02 01:18:21 +0000575 if (Depth == 6)
576 return 1; // Limit search depth.
577
578 User *U = dyn_cast<User>(V);
579 switch (getOpcode(V)) {
580 default: break;
581 case Instruction::SExt:
582 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
583 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
584
585 case Instruction::AShr:
586 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
587 // ashr X, C -> adds C sign bits.
588 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
589 Tmp += C->getZExtValue();
590 if (Tmp > TyBits) Tmp = TyBits;
591 }
592 return Tmp;
593 case Instruction::Shl:
594 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
595 // shl destroys sign bits.
596 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
597 if (C->getZExtValue() >= TyBits || // Bad shift.
598 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
599 return Tmp - C->getZExtValue();
600 }
601 break;
602 case Instruction::And:
603 case Instruction::Or:
604 case Instruction::Xor: // NOT is handled here.
605 // Logical binary ops preserve the number of sign bits at the worst.
606 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
607 if (Tmp != 1) {
608 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
609 FirstAnswer = std::min(Tmp, Tmp2);
610 // We computed what we know about the sign bits as our first
611 // answer. Now proceed to the generic code that uses
612 // ComputeMaskedBits, and pick whichever answer is better.
613 }
614 break;
615
616 case Instruction::Select:
617 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
618 if (Tmp == 1) return 1; // Early out.
619 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
620 return std::min(Tmp, Tmp2);
621
622 case Instruction::Add:
623 // Add can have at most one carry bit. Thus we know that the output
624 // is, at worst, one more bit than the inputs.
625 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
626 if (Tmp == 1) return 1; // Early out.
627
628 // Special case decrementing a value (ADD X, -1):
629 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
630 if (CRHS->isAllOnesValue()) {
631 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
632 APInt Mask = APInt::getAllOnesValue(TyBits);
633 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
634 Depth+1);
635
636 // If the input is known to be 0 or 1, the output is 0/-1, which is all
637 // sign bits set.
638 if ((KnownZero | APInt(TyBits, 1)) == Mask)
639 return TyBits;
640
641 // If we are subtracting one from a positive number, there is no carry
642 // out of the result.
643 if (KnownZero.isNegative())
644 return Tmp;
645 }
646
647 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
648 if (Tmp2 == 1) return 1;
649 return std::min(Tmp, Tmp2)-1;
650 break;
651
652 case Instruction::Sub:
653 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
654 if (Tmp2 == 1) return 1;
655
656 // Handle NEG.
657 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
658 if (CLHS->isNullValue()) {
659 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
660 APInt Mask = APInt::getAllOnesValue(TyBits);
661 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
662 TD, Depth+1);
663 // If the input is known to be 0 or 1, the output is 0/-1, which is all
664 // sign bits set.
665 if ((KnownZero | APInt(TyBits, 1)) == Mask)
666 return TyBits;
667
668 // If the input is known to be positive (the sign bit is known clear),
669 // the output of the NEG has the same number of sign bits as the input.
670 if (KnownZero.isNegative())
671 return Tmp2;
672
673 // Otherwise, we treat this like a SUB.
674 }
675
676 // Sub can have at most one carry bit. Thus we know that the output
677 // is, at worst, one more bit than the inputs.
678 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
679 if (Tmp == 1) return 1; // Early out.
680 return std::min(Tmp, Tmp2)-1;
681 break;
682 case Instruction::Trunc:
683 // FIXME: it's tricky to do anything useful for this, but it is an important
684 // case for targets like X86.
685 break;
686 }
687
688 // Finally, if we can prove that the top bits of the result are 0's or 1's,
689 // use this information.
690 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
691 APInt Mask = APInt::getAllOnesValue(TyBits);
692 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
693
694 if (KnownZero.isNegative()) { // sign bit is 0
695 Mask = KnownZero;
696 } else if (KnownOne.isNegative()) { // sign bit is 1;
697 Mask = KnownOne;
698 } else {
699 // Nothing known.
700 return FirstAnswer;
701 }
702
703 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
704 // the number of identical bits in the top of the input value.
705 Mask = ~Mask;
706 Mask <<= Mask.getBitWidth()-TyBits;
707 // Return # leading zeros. We use 'min' here in case Val was zero before
708 // shifting. We don't want to return '64' as for an i32 "0".
709 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
710}
Chris Lattner833f25d2008-06-02 01:29:46 +0000711
712/// CannotBeNegativeZero - Return true if we can prove that the specified FP
713/// value is never equal to -0.0.
714///
715/// NOTE: this function will need to be revisited when we support non-default
716/// rounding modes!
717///
718bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
719 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
720 return !CFP->getValueAPF().isNegZero();
721
722 if (Depth == 6)
723 return 1; // Limit search depth.
724
725 const Instruction *I = dyn_cast<Instruction>(V);
726 if (I == 0) return false;
727
728 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
729 if (I->getOpcode() == Instruction::Add &&
730 isa<ConstantFP>(I->getOperand(1)) &&
731 cast<ConstantFP>(I->getOperand(1))->isNullValue())
732 return true;
733
734 // sitofp and uitofp turn into +0.0 for zero.
735 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
736 return true;
737
738 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
739 // sqrt(-0.0) = -0.0, no other negative results are possible.
740 if (II->getIntrinsicID() == Intrinsic::sqrt)
741 return CannotBeNegativeZero(II->getOperand(1), Depth+1);
742
743 if (const CallInst *CI = dyn_cast<CallInst>(I))
744 if (const Function *F = CI->getCalledFunction()) {
745 if (F->isDeclaration()) {
746 switch (F->getNameLen()) {
747 case 3: // abs(x) != -0.0
748 if (!strcmp(F->getNameStart(), "abs")) return true;
749 break;
750 case 4: // abs[lf](x) != -0.0
751 if (!strcmp(F->getNameStart(), "absf")) return true;
752 if (!strcmp(F->getNameStart(), "absl")) return true;
753 break;
754 }
755 }
756 }
757
758 return false;
759}
760
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000761// This is the recursive version of BuildSubAggregate. It takes a few different
762// arguments. Idxs is the index within the nested struct From that we are
763// looking at now (which is of type IndexedType). IdxSkip is the number of
764// indices from Idxs that should be left out when inserting into the resulting
765// struct. To is the result struct built so far, new insertvalue instructions
766// build on that.
767Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
768 SmallVector<unsigned, 10> &Idxs,
769 unsigned IdxSkip,
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +0000770 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000771 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
772 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000773 // Save the original To argument so we can modify it
774 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000775 // General case, the type indexed by Idxs is a struct
776 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
777 // Process each struct element recursively
778 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000779 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000780 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
781 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000782 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000783 if (!To) {
784 // Couldn't find any inserted value for this index? Cleanup
785 while (PrevTo != OrigTo) {
786 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
787 PrevTo = Del->getAggregateOperand();
788 Del->eraseFromParent();
789 }
790 // Stop processing elements
791 break;
792 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000793 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000794 // If we succesfully found a value for each of our subaggregates
795 if (To)
796 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000797 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000798 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
799 // the struct's elements had a value that was inserted directly. In the latter
800 // case, perhaps we can't determine each of the subelements individually, but
801 // we might be able to find the complete struct somewhere.
802
803 // Find the value that is at that particular spot
804 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
805
806 if (!V)
807 return NULL;
808
809 // Insert the value in the new (sub) aggregrate
810 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
811 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000812}
813
814// This helper takes a nested struct and extracts a part of it (which is again a
815// struct) into a new value. For example, given the struct:
816// { a, { b, { c, d }, e } }
817// and the indices "1, 1" this returns
818// { c, d }.
819//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000820// It does this by inserting an insertvalue for each element in the resulting
821// struct, as opposed to just inserting a single struct. This will only work if
822// each of the elements of the substruct are known (ie, inserted into From by an
823// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000824//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000825// All inserted insertvalue instructions are inserted before InsertBefore
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000826Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +0000827 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000828 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000829 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
830 idx_begin,
831 idx_end);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000832 Value *To = UndefValue::get(IndexedType);
833 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
834 unsigned IdxSkip = Idxs.size();
835
836 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
837}
838
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000839/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
840/// the scalar value indexed is already around as a register, for example if it
841/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000842///
843/// If InsertBefore is not null, this function will duplicate (modified)
844/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000845Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +0000846 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000847 // Nothing to index? Just return V then (this is useful at the end of our
848 // recursion)
849 if (idx_begin == idx_end)
850 return V;
851 // We have indices, so V should have an indexable type
852 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
853 && "Not looking at a struct or array?");
854 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
855 && "Invalid indices for type?");
856 const CompositeType *PTy = cast<CompositeType>(V->getType());
857
858 if (isa<UndefValue>(V))
859 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
860 idx_begin,
861 idx_end));
862 else if (isa<ConstantAggregateZero>(V))
863 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
864 idx_begin,
865 idx_end));
866 else if (Constant *C = dyn_cast<Constant>(V)) {
867 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
868 // Recursively process this constant
Matthijs Kooijmandddc8272008-07-16 10:47:35 +0000869 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1, idx_end,
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000870 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000871 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
872 // Loop the indices for the insertvalue instruction in parallel with the
873 // requested indices
874 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000875 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
876 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +0000877 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000878 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000879 // The requested index identifies a part of a nested aggregate. Handle
880 // this specially. For example,
881 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
882 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
883 // %C = extractvalue {i32, { i32, i32 } } %B, 1
884 // This can be changed into
885 // %A = insertvalue {i32, i32 } undef, i32 10, 0
886 // %C = insertvalue {i32, i32 } %A, i32 11, 1
887 // which allows the unused 0,0 element from the nested struct to be
888 // removed.
Matthijs Kooijman97728912008-06-16 13:28:31 +0000889 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
890 else
891 // We can't handle this without inserting insertvalues
892 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +0000893 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000894
895 // This insert value inserts something else than what we are looking for.
896 // See if the (aggregrate) value inserted into has the value we are
897 // looking for, then.
898 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000899 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
900 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000901 }
902 // If we end up here, the indices of the insertvalue match with those
903 // requested (though possibly only partially). Now we recursively look at
904 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000905 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
906 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000907 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
908 // If we're extracting a value from an aggregrate that was extracted from
909 // something else, we can extract from that something else directly instead.
910 // However, we will need to chain I's indices with the requested indices.
911
912 // Calculate the number of indices required
913 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
914 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000915 SmallVector<unsigned, 5> Idxs;
916 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000917 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000918 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000919 i != e; ++i)
920 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000921
922 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000923 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
924 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000925
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000926 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000927 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000928
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000929 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000930 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000931 }
932 // Otherwise, we don't know (such as, extracting from a function return value
933 // or load instruction)
934 return 0;
935}
Evan Cheng0ff39b32008-06-30 07:31:25 +0000936
937/// GetConstantStringInfo - This function computes the length of a
938/// null-terminated C string pointed to by V. If successful, it returns true
939/// and returns the string in Str. If unsuccessful, it returns false.
940bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
941 bool StopAtNul) {
942 // If V is NULL then return false;
943 if (V == NULL) return false;
944
945 // Look through bitcast instructions.
946 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
947 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
948
949 // If the value is not a GEP instruction nor a constant expression with a
950 // GEP instruction, then return false because ConstantArray can't occur
951 // any other way
952 User *GEP = 0;
953 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
954 GEP = GEPI;
955 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
956 if (CE->getOpcode() == Instruction::BitCast)
957 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
958 if (CE->getOpcode() != Instruction::GetElementPtr)
959 return false;
960 GEP = CE;
961 }
962
963 if (GEP) {
964 // Make sure the GEP has exactly three arguments.
965 if (GEP->getNumOperands() != 3)
966 return false;
967
968 // Make sure the index-ee is a pointer to array of i8.
969 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
970 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
971 if (AT == 0 || AT->getElementType() != Type::Int8Ty)
972 return false;
973
974 // Check to make sure that the first operand of the GEP is an integer and
975 // has value 0 so that we are sure we're indexing into the initializer.
976 ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
977 if (FirstIdx == 0 || !FirstIdx->isZero())
978 return false;
979
980 // If the second index isn't a ConstantInt, then this is a variable index
981 // into the array. If this occurs, we can't say anything meaningful about
982 // the string.
983 uint64_t StartIdx = 0;
984 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
985 StartIdx = CI->getZExtValue();
986 else
987 return false;
988 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
989 StopAtNul);
990 }
991
992 // The GEP instruction, constant or instruction, must reference a global
993 // variable that is a constant and is initialized. The referenced constant
994 // initializer is the array that we'll use for optimization.
995 GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
996 if (!GV || !GV->isConstant() || !GV->hasInitializer())
997 return false;
998 Constant *GlobalInit = GV->getInitializer();
999
1000 // Handle the ConstantAggregateZero case
1001 if (isa<ConstantAggregateZero>(GlobalInit)) {
1002 // This is a degenerate case. The initializer is constant zero so the
1003 // length of the string must be zero.
1004 Str.clear();
1005 return true;
1006 }
1007
1008 // Must be a Constant Array
1009 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1010 if (Array == 0 || Array->getType()->getElementType() != Type::Int8Ty)
1011 return false;
1012
1013 // Get the number of elements in the array
1014 uint64_t NumElts = Array->getType()->getNumElements();
1015
1016 if (Offset > NumElts)
1017 return false;
1018
1019 // Traverse the constant array from 'Offset' which is the place the GEP refers
1020 // to in the array.
1021 Str.reserve(NumElts-Offset);
1022 for (unsigned i = Offset; i != NumElts; ++i) {
1023 Constant *Elt = Array->getOperand(i);
1024 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1025 if (!CI) // This array isn't suitable, non-int initializer.
1026 return false;
1027 if (StopAtNul && CI->isZero())
1028 return true; // we found end of string, success!
1029 Str += (char)CI->getZExtValue();
1030 }
1031
1032 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1033 return true;
1034}