blob: 9d6459d29445d9254aafcdd4242fcf695c1cbf1e [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"
Dan Gohman307a7c42009-09-15 16:14:44 +000019#include "llvm/GlobalAlias.h"
Chris Lattner173234a2008-06-02 01:18:21 +000020#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000021#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000022#include "llvm/Operator.h"
Bill Wendling0582ae92009-03-13 04:39:26 +000023#include "llvm/Target/TargetData.h"
Chris Lattner173234a2008-06-02 01:18:21 +000024#include "llvm/Support/GetElementPtrTypeIterator.h"
25#include "llvm/Support/MathExtras.h"
Eric Christopher25ec4832010-03-05 06:58:57 +000026#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000027#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000028using namespace llvm;
29
Chris Lattner173234a2008-06-02 01:18:21 +000030/// ComputeMaskedBits - Determine which of the bits specified in Mask are
31/// known to be either zero or one and return them in the KnownZero/KnownOne
32/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
33/// processing.
34/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
35/// we cannot optimize based on the assumption that it is zero without changing
36/// it to be an explicit zero. If we don't change it to zero, other code could
37/// optimized based on the contradictory assumption that it is non-zero.
38/// Because instcombine aggressively folds operations with undef args anyway,
39/// this won't lose us code quality.
Chris Lattnercf5128e2009-09-08 00:06:16 +000040///
41/// This function is defined on values with integer type, values with pointer
42/// type (but only if TD is non-null), and vectors of integers. In the case
43/// where V is a vector, the mask, known zero, and known one values are the
44/// same width as the vector element, and the bit is set only if it is true
45/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +000046void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
47 APInt &KnownZero, APInt &KnownOne,
Dan Gohman846a2f22009-08-27 17:51:25 +000048 const TargetData *TD, unsigned Depth) {
Dan Gohman9004c8a2009-05-21 02:28:33 +000049 const unsigned MaxDepth = 6;
Chris Lattner173234a2008-06-02 01:18:21 +000050 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +000051 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +000052 unsigned BitWidth = Mask.getBitWidth();
Duncan Sands1df98592010-02-16 11:11:14 +000053 assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy())
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000054 && "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +000055 assert((!TD ||
56 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000057 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman6de29f82009-06-15 22:12:54 +000058 V->getType()->getScalarSizeInBits() == BitWidth) &&
Chris Lattner173234a2008-06-02 01:18:21 +000059 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 }
Dan Gohman6de29f82009-06-15 22:12:54 +000069 // Null and aggregate-zero are all-zeros.
70 if (isa<ConstantPointerNull>(V) ||
71 isa<ConstantAggregateZero>(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +000072 KnownOne.clear();
73 KnownZero = Mask;
74 return;
75 }
Dan Gohman6de29f82009-06-15 22:12:54 +000076 // Handle a constant vector by taking the intersection of the known bits of
77 // each element.
78 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
79 KnownZero.set(); KnownOne.set();
80 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
81 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
82 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
83 TD, Depth);
84 KnownZero &= KnownZero2;
85 KnownOne &= KnownOne2;
86 }
87 return;
88 }
Chris Lattner173234a2008-06-02 01:18:21 +000089 // The address of an aligned GlobalValue has trailing zeros.
90 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
91 unsigned Align = GV->getAlignment();
Dan Gohman00407252009-08-11 15:50:03 +000092 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
93 const Type *ObjectType = GV->getType()->getElementType();
94 // If the object is defined in the current Module, we'll be giving
95 // it the preferred alignment. Otherwise, we have to assume that it
96 // may only have the minimum ABI alignment.
97 if (!GV->isDeclaration() && !GV->mayBeOverridden())
98 Align = TD->getPrefTypeAlignment(ObjectType);
99 else
100 Align = TD->getABITypeAlignment(ObjectType);
101 }
Chris Lattner173234a2008-06-02 01:18:21 +0000102 if (Align > 0)
103 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
104 CountTrailingZeros_32(Align));
105 else
106 KnownZero.clear();
107 KnownOne.clear();
108 return;
109 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000110 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
111 // the bits of its aliasee.
112 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
113 if (GA->mayBeOverridden()) {
114 KnownZero.clear(); KnownOne.clear();
115 } else {
116 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
117 TD, Depth+1);
118 }
119 return;
120 }
Chris Lattner173234a2008-06-02 01:18:21 +0000121
122 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
123
Dan Gohman9004c8a2009-05-21 02:28:33 +0000124 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000125 return; // Limit search depth.
126
Dan Gohmanca178902009-07-17 20:47:02 +0000127 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000128 if (!I) return;
129
130 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000131 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000132 default: break;
133 case Instruction::And: {
134 // If either the LHS or the RHS are Zero, the result is zero.
135 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
136 APInt Mask2(Mask & ~KnownZero);
137 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
138 Depth+1);
139 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
140 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
141
142 // Output known-1 bits are only known if set in both the LHS & RHS.
143 KnownOne &= KnownOne2;
144 // Output known-0 are known to be clear if zero in either the LHS | RHS.
145 KnownZero |= KnownZero2;
146 return;
147 }
148 case Instruction::Or: {
149 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
150 APInt Mask2(Mask & ~KnownOne);
151 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
152 Depth+1);
153 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
154 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
155
156 // Output known-0 bits are only known if clear in both the LHS & RHS.
157 KnownZero &= KnownZero2;
158 // Output known-1 are known to be set if set in either the LHS | RHS.
159 KnownOne |= KnownOne2;
160 return;
161 }
162 case Instruction::Xor: {
163 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
164 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
165 Depth+1);
166 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
167 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
168
169 // Output known-0 bits are known if clear or set in both the LHS & RHS.
170 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
171 // Output known-1 are known to be set if set in only one of the LHS, RHS.
172 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
173 KnownZero = KnownZeroOut;
174 return;
175 }
176 case Instruction::Mul: {
177 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
178 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
179 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
180 Depth+1);
181 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
182 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
183
184 // If low bits are zero in either operand, output low known-0 bits.
185 // Also compute a conserative estimate for high known-0 bits.
186 // More trickiness is possible, but this is sufficient for the
187 // interesting case of alignment computation.
188 KnownOne.clear();
189 unsigned TrailZ = KnownZero.countTrailingOnes() +
190 KnownZero2.countTrailingOnes();
191 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
192 KnownZero2.countLeadingOnes(),
193 BitWidth) - BitWidth;
194
195 TrailZ = std::min(TrailZ, BitWidth);
196 LeadZ = std::min(LeadZ, BitWidth);
197 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
198 APInt::getHighBitsSet(BitWidth, LeadZ);
199 KnownZero &= Mask;
200 return;
201 }
202 case Instruction::UDiv: {
203 // For the purposes of computing leading zeros we can conservatively
204 // treat a udiv as a logical right shift by the power of 2 known to
205 // be less than the denominator.
206 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
207 ComputeMaskedBits(I->getOperand(0),
208 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
209 unsigned LeadZ = KnownZero2.countLeadingOnes();
210
211 KnownOne2.clear();
212 KnownZero2.clear();
213 ComputeMaskedBits(I->getOperand(1),
214 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
215 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
216 if (RHSUnknownLeadingOnes != BitWidth)
217 LeadZ = std::min(BitWidth,
218 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
219
220 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
221 return;
222 }
223 case Instruction::Select:
224 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
225 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
226 Depth+1);
227 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
228 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
229
230 // Only known if known in both the LHS and RHS.
231 KnownOne &= KnownOne2;
232 KnownZero &= KnownZero2;
233 return;
234 case Instruction::FPTrunc:
235 case Instruction::FPExt:
236 case Instruction::FPToUI:
237 case Instruction::FPToSI:
238 case Instruction::SIToFP:
239 case Instruction::UIToFP:
240 return; // Can't work with floating point.
241 case Instruction::PtrToInt:
242 case Instruction::IntToPtr:
243 // We can't handle these if we don't know the pointer size.
244 if (!TD) return;
245 // FALL THROUGH and handle them the same as zext/trunc.
246 case Instruction::ZExt:
247 case Instruction::Trunc: {
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000248 const Type *SrcTy = I->getOperand(0)->getType();
249
250 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000251 // Note that we handle pointer operands here because of inttoptr/ptrtoint
252 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000253 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000254 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
255 else
256 SrcBitWidth = SrcTy->getScalarSizeInBits();
257
Chris Lattner173234a2008-06-02 01:18:21 +0000258 APInt MaskIn(Mask);
259 MaskIn.zextOrTrunc(SrcBitWidth);
260 KnownZero.zextOrTrunc(SrcBitWidth);
261 KnownOne.zextOrTrunc(SrcBitWidth);
262 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
263 Depth+1);
264 KnownZero.zextOrTrunc(BitWidth);
265 KnownOne.zextOrTrunc(BitWidth);
266 // Any top bits are known to be zero.
267 if (BitWidth > SrcBitWidth)
268 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
269 return;
270 }
271 case Instruction::BitCast: {
272 const Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000273 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000274 // TODO: For now, not handling conversions like:
275 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000276 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000277 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
278 Depth+1);
279 return;
280 }
281 break;
282 }
283 case Instruction::SExt: {
284 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000285 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000286
287 APInt MaskIn(Mask);
288 MaskIn.trunc(SrcBitWidth);
289 KnownZero.trunc(SrcBitWidth);
290 KnownOne.trunc(SrcBitWidth);
291 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
292 Depth+1);
293 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
294 KnownZero.zext(BitWidth);
295 KnownOne.zext(BitWidth);
296
297 // If the sign bit of the input is known set or clear, then we know the
298 // top bits of the result.
299 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
300 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
301 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
302 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
303 return;
304 }
305 case Instruction::Shl:
306 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
307 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
308 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
309 APInt Mask2(Mask.lshr(ShiftAmt));
310 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
311 Depth+1);
312 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
313 KnownZero <<= ShiftAmt;
314 KnownOne <<= ShiftAmt;
315 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
316 return;
317 }
318 break;
319 case Instruction::LShr:
320 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
321 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
322 // Compute the new bits that are at the top now.
323 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
324
325 // Unsigned shift right.
326 APInt Mask2(Mask.shl(ShiftAmt));
327 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
328 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000329 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000330 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
331 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
332 // high bits known zero.
333 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
334 return;
335 }
336 break;
337 case Instruction::AShr:
338 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
339 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
340 // Compute the new bits that are at the top now.
341 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
342
343 // Signed shift right.
344 APInt Mask2(Mask.shl(ShiftAmt));
345 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
346 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000347 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000348 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
349 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
350
351 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
352 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
353 KnownZero |= HighBits;
354 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
355 KnownOne |= HighBits;
356 return;
357 }
358 break;
359 case Instruction::Sub: {
360 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
361 // We know that the top bits of C-X are clear if X contains less bits
362 // than C (i.e. no wrap-around can happen). For example, 20-X is
363 // positive if we can prove that X is >= 0 and < 16.
364 if (!CLHS->getValue().isNegative()) {
365 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
366 // NLZ can't be BitWidth with no sign bit
367 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
368 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
369 TD, Depth+1);
370
371 // If all of the MaskV bits are known to be zero, then we know the
372 // output top bits are zero, because we now know that the output is
373 // from [0-C].
374 if ((KnownZero2 & MaskV) == MaskV) {
375 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
376 // Top bits known zero.
377 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
378 }
379 }
380 }
381 }
382 // fall through
383 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000384 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000385 // other operand has in those bit positions will be preserved in the
386 // result. For an add, this works with either operand. For a subtract,
387 // this only works if the known zeros are in the right operand.
388 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
389 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
390 BitWidth - Mask.countLeadingZeros());
391 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000392 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000393 assert((LHSKnownZero & LHSKnownOne) == 0 &&
394 "Bits known to be one AND zero?");
395 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000396
397 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
398 Depth+1);
399 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000400 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000401
Dan Gohman39250432009-05-24 18:02:35 +0000402 // Determine which operand has more trailing zeros, and use that
403 // many bits from the other operand.
404 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000405 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000406 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
407 KnownZero |= KnownZero2 & Mask;
408 KnownOne |= KnownOne2 & Mask;
409 } else {
410 // If the known zeros are in the left operand for a subtract,
411 // fall back to the minimum known zeros in both operands.
412 KnownZero |= APInt::getLowBitsSet(BitWidth,
413 std::min(LHSKnownZeroOut,
414 RHSKnownZeroOut));
415 }
416 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
417 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
418 KnownZero |= LHSKnownZero & Mask;
419 KnownOne |= LHSKnownOne & Mask;
420 }
Chris Lattner173234a2008-06-02 01:18:21 +0000421 return;
422 }
423 case Instruction::SRem:
424 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000425 APInt RA = Rem->getValue().abs();
426 if (RA.isPowerOf2()) {
427 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000428 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
429 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
430 Depth+1);
431
Duncan Sandscfd54182010-01-29 06:18:37 +0000432 // The low bits of the first operand are unchanged by the srem.
433 KnownZero = KnownZero2 & LowBits;
434 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000435
Duncan Sandscfd54182010-01-29 06:18:37 +0000436 // If the first operand is non-negative or has all low bits zero, then
437 // the upper bits are all zero.
438 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
439 KnownZero |= ~LowBits;
440
441 // If the first operand is negative and not all low bits are zero, then
442 // the upper bits are all one.
443 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
444 KnownOne |= ~LowBits;
445
446 KnownZero &= Mask;
447 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000448
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000449 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000450 }
451 }
452 break;
453 case Instruction::URem: {
454 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
455 APInt RA = Rem->getValue();
456 if (RA.isPowerOf2()) {
457 APInt LowBits = (RA - 1);
458 APInt Mask2 = LowBits & Mask;
459 KnownZero |= ~LowBits & Mask;
460 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
461 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000462 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000463 break;
464 }
465 }
466
467 // Since the result is less than or equal to either operand, any leading
468 // zero bits in either operand must also exist in the result.
469 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
470 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
471 TD, Depth+1);
472 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
473 TD, Depth+1);
474
Chris Lattner79abedb2009-01-20 18:22:57 +0000475 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000476 KnownZero2.countLeadingOnes());
477 KnownOne.clear();
478 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
479 break;
480 }
481
Victor Hernandeza276c602009-10-17 01:18:07 +0000482 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000483 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000484 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000485 if (Align == 0 && TD)
486 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000487
488 if (Align > 0)
489 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
490 CountTrailingZeros_32(Align));
491 break;
492 }
493 case Instruction::GetElementPtr: {
494 // Analyze all of the subscripts of this getelementptr instruction
495 // to determine if we can prove known low zero bits.
496 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
497 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
498 ComputeMaskedBits(I->getOperand(0), LocalMask,
499 LocalKnownZero, LocalKnownOne, TD, Depth+1);
500 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
501
502 gep_type_iterator GTI = gep_type_begin(I);
503 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
504 Value *Index = I->getOperand(i);
505 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
506 // Handle struct member offset arithmetic.
507 if (!TD) return;
508 const StructLayout *SL = TD->getStructLayout(STy);
509 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
510 uint64_t Offset = SL->getElementOffset(Idx);
511 TrailZ = std::min(TrailZ,
512 CountTrailingZeros_64(Offset));
513 } else {
514 // Handle array index arithmetic.
515 const Type *IndexedTy = GTI.getIndexedType();
516 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000517 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000518 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000519 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
520 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
521 ComputeMaskedBits(Index, LocalMask,
522 LocalKnownZero, LocalKnownOne, TD, Depth+1);
523 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000524 unsigned(CountTrailingZeros_64(TypeSize) +
525 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000526 }
527 }
528
529 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
530 break;
531 }
532 case Instruction::PHI: {
533 PHINode *P = cast<PHINode>(I);
534 // Handle the case of a simple two-predecessor recurrence PHI.
535 // There's a lot more that could theoretically be done here, but
536 // this is sufficient to catch some interesting cases.
537 if (P->getNumIncomingValues() == 2) {
538 for (unsigned i = 0; i != 2; ++i) {
539 Value *L = P->getIncomingValue(i);
540 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000541 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000542 if (!LU)
543 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000544 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000545 // Check for operations that have the property that if
546 // both their operands have low zero bits, the result
547 // will have low zero bits.
548 if (Opcode == Instruction::Add ||
549 Opcode == Instruction::Sub ||
550 Opcode == Instruction::And ||
551 Opcode == Instruction::Or ||
552 Opcode == Instruction::Mul) {
553 Value *LL = LU->getOperand(0);
554 Value *LR = LU->getOperand(1);
555 // Find a recurrence.
556 if (LL == I)
557 L = LR;
558 else if (LR == I)
559 L = LL;
560 else
561 break;
562 // Ok, we have a PHI of the form L op= R. Check for low
563 // zero bits.
564 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
565 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
566 Mask2 = APInt::getLowBitsSet(BitWidth,
567 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000568
569 // We need to take the minimum number of known bits
570 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
571 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
572
Chris Lattner173234a2008-06-02 01:18:21 +0000573 KnownZero = Mask &
574 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000575 std::min(KnownZero2.countTrailingOnes(),
576 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000577 break;
578 }
579 }
580 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000581
582 // Otherwise take the unions of the known bit sets of the operands,
583 // taking conservative care to avoid excessive recursion.
584 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
585 KnownZero = APInt::getAllOnesValue(BitWidth);
586 KnownOne = APInt::getAllOnesValue(BitWidth);
587 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
588 // Skip direct self references.
589 if (P->getIncomingValue(i) == P) continue;
590
591 KnownZero2 = APInt(BitWidth, 0);
592 KnownOne2 = APInt(BitWidth, 0);
593 // Recurse, but cap the recursion to one level, because we don't
594 // want to waste time spinning around in loops.
595 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
596 KnownZero2, KnownOne2, TD, MaxDepth-1);
597 KnownZero &= KnownZero2;
598 KnownOne &= KnownOne2;
599 // If all bits have been ruled out, there's no need to check
600 // more operands.
601 if (!KnownZero && !KnownOne)
602 break;
603 }
604 }
Chris Lattner173234a2008-06-02 01:18:21 +0000605 break;
606 }
607 case Instruction::Call:
608 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
609 switch (II->getIntrinsicID()) {
610 default: break;
611 case Intrinsic::ctpop:
612 case Intrinsic::ctlz:
613 case Intrinsic::cttz: {
614 unsigned LowBits = Log2_32(BitWidth)+1;
615 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
616 break;
617 }
618 }
619 }
620 break;
621 }
622}
623
624/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
625/// this predicate to simplify operations downstream. Mask is known to be zero
626/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000627///
628/// This function is defined on values with integer type, values with pointer
629/// type (but only if TD is non-null), and vectors of integers. In the case
630/// where V is a vector, the mask, known zero, and known one values are the
631/// same width as the vector element, and the bit is set only if it is true
632/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000633bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000634 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000635 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
636 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638 return (KnownZero & Mask) == Mask;
639}
640
641
642
643/// ComputeNumSignBits - Return the number of times the sign bit of the
644/// register is replicated into the other bits. We know that at least 1 bit
645/// is always equal to the sign bit (itself), but other cases can give us
646/// information. For example, immediately after an "ashr X, 2", we know that
647/// the top 3 bits are all equal to each other, so we return 3.
648///
649/// 'Op' must have a scalar integer type.
650///
Dan Gohman846a2f22009-08-27 17:51:25 +0000651unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
652 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000653 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000654 "ComputeNumSignBits requires a TargetData object to operate "
655 "on non-integer values!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000656 const Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000657 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
658 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000659 unsigned Tmp, Tmp2;
660 unsigned FirstAnswer = 1;
661
Chris Lattnerd82e5112008-06-02 18:39:07 +0000662 // Note that ConstantInt is handled by the general ComputeMaskedBits case
663 // below.
664
Chris Lattner173234a2008-06-02 01:18:21 +0000665 if (Depth == 6)
666 return 1; // Limit search depth.
667
Dan Gohmanca178902009-07-17 20:47:02 +0000668 Operator *U = dyn_cast<Operator>(V);
669 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000670 default: break;
671 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +0000672 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000673 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
674
675 case Instruction::AShr:
676 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
677 // ashr X, C -> adds C sign bits.
678 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
679 Tmp += C->getZExtValue();
680 if (Tmp > TyBits) Tmp = TyBits;
681 }
682 return Tmp;
683 case Instruction::Shl:
684 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
685 // shl destroys sign bits.
686 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
687 if (C->getZExtValue() >= TyBits || // Bad shift.
688 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
689 return Tmp - C->getZExtValue();
690 }
691 break;
692 case Instruction::And:
693 case Instruction::Or:
694 case Instruction::Xor: // NOT is handled here.
695 // Logical binary ops preserve the number of sign bits at the worst.
696 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
697 if (Tmp != 1) {
698 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
699 FirstAnswer = std::min(Tmp, Tmp2);
700 // We computed what we know about the sign bits as our first
701 // answer. Now proceed to the generic code that uses
702 // ComputeMaskedBits, and pick whichever answer is better.
703 }
704 break;
705
706 case Instruction::Select:
707 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
708 if (Tmp == 1) return 1; // Early out.
709 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
710 return std::min(Tmp, Tmp2);
711
712 case Instruction::Add:
713 // Add can have at most one carry bit. Thus we know that the output
714 // is, at worst, one more bit than the inputs.
715 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
716 if (Tmp == 1) return 1; // Early out.
717
718 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +0000719 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +0000720 if (CRHS->isAllOnesValue()) {
721 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
722 APInt Mask = APInt::getAllOnesValue(TyBits);
723 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
724 Depth+1);
725
726 // If the input is known to be 0 or 1, the output is 0/-1, which is all
727 // sign bits set.
728 if ((KnownZero | APInt(TyBits, 1)) == Mask)
729 return TyBits;
730
731 // If we are subtracting one from a positive number, there is no carry
732 // out of the result.
733 if (KnownZero.isNegative())
734 return Tmp;
735 }
736
737 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
738 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000739 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +0000740
741 case Instruction::Sub:
742 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
743 if (Tmp2 == 1) return 1;
744
745 // Handle NEG.
746 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
747 if (CLHS->isNullValue()) {
748 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
749 APInt Mask = APInt::getAllOnesValue(TyBits);
750 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
751 TD, Depth+1);
752 // If the input is known to be 0 or 1, the output is 0/-1, which is all
753 // sign bits set.
754 if ((KnownZero | APInt(TyBits, 1)) == Mask)
755 return TyBits;
756
757 // If the input is known to be positive (the sign bit is known clear),
758 // the output of the NEG has the same number of sign bits as the input.
759 if (KnownZero.isNegative())
760 return Tmp2;
761
762 // Otherwise, we treat this like a SUB.
763 }
764
765 // Sub can have at most one carry bit. Thus we know that the output
766 // is, at worst, one more bit than the inputs.
767 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
768 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000769 return std::min(Tmp, Tmp2)-1;
770
771 case Instruction::PHI: {
772 PHINode *PN = cast<PHINode>(U);
773 // Don't analyze large in-degree PHIs.
774 if (PN->getNumIncomingValues() > 4) break;
775
776 // Take the minimum of all incoming values. This can't infinitely loop
777 // because of our depth threshold.
778 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
779 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
780 if (Tmp == 1) return Tmp;
781 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +0000782 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000783 }
784 return Tmp;
785 }
786
Chris Lattner173234a2008-06-02 01:18:21 +0000787 case Instruction::Trunc:
788 // FIXME: it's tricky to do anything useful for this, but it is an important
789 // case for targets like X86.
790 break;
791 }
792
793 // Finally, if we can prove that the top bits of the result are 0's or 1's,
794 // use this information.
795 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
796 APInt Mask = APInt::getAllOnesValue(TyBits);
797 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
798
799 if (KnownZero.isNegative()) { // sign bit is 0
800 Mask = KnownZero;
801 } else if (KnownOne.isNegative()) { // sign bit is 1;
802 Mask = KnownOne;
803 } else {
804 // Nothing known.
805 return FirstAnswer;
806 }
807
808 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
809 // the number of identical bits in the top of the input value.
810 Mask = ~Mask;
811 Mask <<= Mask.getBitWidth()-TyBits;
812 // Return # leading zeros. We use 'min' here in case Val was zero before
813 // shifting. We don't want to return '64' as for an i32 "0".
814 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
815}
Chris Lattner833f25d2008-06-02 01:29:46 +0000816
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000817/// ComputeMultiple - This function computes the integer multiple of Base that
818/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000819/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000820/// through SExt instructions only if LookThroughSExt is true.
821bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000822 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000823 const unsigned MaxDepth = 6;
824
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000825 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000826 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000827 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000828
829 const Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000830
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000831 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000832
833 if (Base == 0)
834 return false;
835
836 if (Base == 1) {
837 Multiple = V;
838 return true;
839 }
840
841 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
842 Constant *BaseVal = ConstantInt::get(T, Base);
843 if (CO && CO == BaseVal) {
844 // Multiple is 1.
845 Multiple = ConstantInt::get(T, 1);
846 return true;
847 }
848
849 if (CI && CI->getZExtValue() % Base == 0) {
850 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
851 return true;
852 }
853
854 if (Depth == MaxDepth) return false; // Limit search depth.
855
856 Operator *I = dyn_cast<Operator>(V);
857 if (!I) return false;
858
859 switch (I->getOpcode()) {
860 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +0000861 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000862 if (!LookThroughSExt) return false;
863 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +0000864 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000865 return ComputeMultiple(I->getOperand(0), Base, Multiple,
866 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000867 case Instruction::Shl:
868 case Instruction::Mul: {
869 Value *Op0 = I->getOperand(0);
870 Value *Op1 = I->getOperand(1);
871
872 if (I->getOpcode() == Instruction::Shl) {
873 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
874 if (!Op1CI) return false;
875 // Turn Op0 << Op1 into Op0 * 2^Op1
876 APInt Op1Int = Op1CI->getValue();
877 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +0000878 APInt API(Op1Int.getBitWidth(), 0);
879 API.set(BitToSet);
880 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000881 }
882
883 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +0000884 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
885 if (Constant *Op1C = dyn_cast<Constant>(Op1))
886 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
887 if (Op1C->getType()->getPrimitiveSizeInBits() <
888 MulC->getType()->getPrimitiveSizeInBits())
889 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
890 if (Op1C->getType()->getPrimitiveSizeInBits() >
891 MulC->getType()->getPrimitiveSizeInBits())
892 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
893
894 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
895 Multiple = ConstantExpr::getMul(MulC, Op1C);
896 return true;
897 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000898
899 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
900 if (Mul0CI->getValue() == 1) {
901 // V == Base * Op1, so return Op1
902 Multiple = Op1;
903 return true;
904 }
905 }
906
Chris Lattnere9711312010-09-05 17:20:46 +0000907 Value *Mul1 = NULL;
908 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
909 if (Constant *Op0C = dyn_cast<Constant>(Op0))
910 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
911 if (Op0C->getType()->getPrimitiveSizeInBits() <
912 MulC->getType()->getPrimitiveSizeInBits())
913 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
914 if (Op0C->getType()->getPrimitiveSizeInBits() >
915 MulC->getType()->getPrimitiveSizeInBits())
916 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
917
918 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
919 Multiple = ConstantExpr::getMul(MulC, Op0C);
920 return true;
921 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000922
923 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
924 if (Mul1CI->getValue() == 1) {
925 // V == Base * Op0, so return Op0
926 Multiple = Op0;
927 return true;
928 }
929 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000930 }
931 }
932
933 // We could not determine if V is a multiple of Base.
934 return false;
935}
936
Chris Lattner833f25d2008-06-02 01:29:46 +0000937/// CannotBeNegativeZero - Return true if we can prove that the specified FP
938/// value is never equal to -0.0.
939///
940/// NOTE: this function will need to be revisited when we support non-default
941/// rounding modes!
942///
943bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
944 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
945 return !CFP->getValueAPF().isNegZero();
946
947 if (Depth == 6)
948 return 1; // Limit search depth.
949
Dan Gohmanca178902009-07-17 20:47:02 +0000950 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +0000951 if (I == 0) return false;
952
953 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000954 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +0000955 isa<ConstantFP>(I->getOperand(1)) &&
956 cast<ConstantFP>(I->getOperand(1))->isNullValue())
957 return true;
958
959 // sitofp and uitofp turn into +0.0 for zero.
960 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
961 return true;
962
963 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
964 // sqrt(-0.0) = -0.0, no other negative results are possible.
965 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +0000966 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +0000967
968 if (const CallInst *CI = dyn_cast<CallInst>(I))
969 if (const Function *F = CI->getCalledFunction()) {
970 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000971 // abs(x) != -0.0
972 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +0000973 // fabs[lf](x) != -0.0
974 if (F->getName() == "fabs") return true;
975 if (F->getName() == "fabsf") return true;
976 if (F->getName() == "fabsl") return true;
977 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
978 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +0000979 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +0000980 }
981 }
982
983 return false;
984}
985
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000986// This is the recursive version of BuildSubAggregate. It takes a few different
987// arguments. Idxs is the index within the nested struct From that we are
988// looking at now (which is of type IndexedType). IdxSkip is the number of
989// indices from Idxs that should be left out when inserting into the resulting
990// struct. To is the result struct built so far, new insertvalue instructions
991// build on that.
Dan Gohman7db949d2009-08-07 01:32:21 +0000992static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
993 SmallVector<unsigned, 10> &Idxs,
994 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +0000995 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000996 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
997 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000998 // Save the original To argument so we can modify it
999 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001000 // General case, the type indexed by Idxs is a struct
1001 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1002 // Process each struct element recursively
1003 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001004 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001005 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001006 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001007 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001008 if (!To) {
1009 // Couldn't find any inserted value for this index? Cleanup
1010 while (PrevTo != OrigTo) {
1011 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1012 PrevTo = Del->getAggregateOperand();
1013 Del->eraseFromParent();
1014 }
1015 // Stop processing elements
1016 break;
1017 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001018 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001019 // If we succesfully found a value for each of our subaggregates
1020 if (To)
1021 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001022 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001023 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1024 // the struct's elements had a value that was inserted directly. In the latter
1025 // case, perhaps we can't determine each of the subelements individually, but
1026 // we might be able to find the complete struct somewhere.
1027
1028 // Find the value that is at that particular spot
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001029 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001030
1031 if (!V)
1032 return NULL;
1033
1034 // Insert the value in the new (sub) aggregrate
1035 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
1036 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001037}
1038
1039// This helper takes a nested struct and extracts a part of it (which is again a
1040// struct) into a new value. For example, given the struct:
1041// { a, { b, { c, d }, e } }
1042// and the indices "1, 1" this returns
1043// { c, d }.
1044//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001045// It does this by inserting an insertvalue for each element in the resulting
1046// struct, as opposed to just inserting a single struct. This will only work if
1047// each of the elements of the substruct are known (ie, inserted into From by an
1048// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001049//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001050// All inserted insertvalue instructions are inserted before InsertBefore
Dan Gohman7db949d2009-08-07 01:32:21 +00001051static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001052 const unsigned *idx_end,
Dan Gohman7db949d2009-08-07 01:32:21 +00001053 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001054 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001055 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1056 idx_begin,
1057 idx_end);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001058 Value *To = UndefValue::get(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001059 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
1060 unsigned IdxSkip = Idxs.size();
1061
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001062 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001063}
1064
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001065/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1066/// the scalar value indexed is already around as a register, for example if it
1067/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001068///
1069/// If InsertBefore is not null, this function will duplicate (modified)
1070/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001071Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001072 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001073 // Nothing to index? Just return V then (this is useful at the end of our
1074 // recursion)
1075 if (idx_begin == idx_end)
1076 return V;
1077 // We have indices, so V should have an indexable type
Duncan Sands1df98592010-02-16 11:11:14 +00001078 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001079 && "Not looking at a struct or array?");
1080 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
1081 && "Invalid indices for type?");
1082 const CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +00001083
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001084 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001085 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001086 idx_begin,
1087 idx_end));
1088 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00001089 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Owen Anderson76f600b2009-07-06 22:37:39 +00001090 idx_begin,
1091 idx_end));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001092 else if (Constant *C = dyn_cast<Constant>(V)) {
1093 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1094 // Recursively process this constant
Owen Anderson76f600b2009-07-06 22:37:39 +00001095 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001096 idx_end, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001097 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1098 // Loop the indices for the insertvalue instruction in parallel with the
1099 // requested indices
1100 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001101 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1102 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +00001103 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001104 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001105 // The requested index identifies a part of a nested aggregate. Handle
1106 // this specially. For example,
1107 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1108 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1109 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1110 // This can be changed into
1111 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1112 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1113 // which allows the unused 0,0 element from the nested struct to be
1114 // removed.
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001115 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +00001116 else
1117 // We can't handle this without inserting insertvalues
1118 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +00001119 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001120
1121 // This insert value inserts something else than what we are looking for.
1122 // See if the (aggregrate) value inserted into has the value we are
1123 // looking for, then.
1124 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001125 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001126 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001127 }
1128 // If we end up here, the indices of the insertvalue match with those
1129 // requested (though possibly only partially). Now we recursively look at
1130 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001131 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001132 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001133 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1134 // If we're extracting a value from an aggregrate that was extracted from
1135 // something else, we can extract from that something else directly instead.
1136 // However, we will need to chain I's indices with the requested indices.
1137
1138 // Calculate the number of indices required
1139 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
1140 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001141 SmallVector<unsigned, 5> Idxs;
1142 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001143 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001144 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001145 i != e; ++i)
1146 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001147
1148 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001149 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1150 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001151
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001152 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001153 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001154
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001155 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001156 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001157 }
1158 // Otherwise, we don't know (such as, extracting from a function return value
1159 // or load instruction)
1160 return 0;
1161}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001162
1163/// GetConstantStringInfo - This function computes the length of a
1164/// null-terminated C string pointed to by V. If successful, it returns true
1165/// and returns the string in Str. If unsuccessful, it returns false.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001166bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1167 uint64_t Offset,
Bill Wendling0582ae92009-03-13 04:39:26 +00001168 bool StopAtNul) {
1169 // If V is NULL then return false;
1170 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001171
1172 // Look through bitcast instructions.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001173 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001174 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1175
Evan Cheng0ff39b32008-06-30 07:31:25 +00001176 // If the value is not a GEP instruction nor a constant expression with a
1177 // GEP instruction, then return false because ConstantArray can't occur
1178 // any other way
Dan Gohman0a60fa32010-04-14 22:20:45 +00001179 const User *GEP = 0;
1180 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001181 GEP = GEPI;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001182 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001183 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001184 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1185 if (CE->getOpcode() != Instruction::GetElementPtr)
1186 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001187 GEP = CE;
1188 }
1189
1190 if (GEP) {
1191 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001192 if (GEP->getNumOperands() != 3)
1193 return false;
1194
Evan Cheng0ff39b32008-06-30 07:31:25 +00001195 // Make sure the index-ee is a pointer to array of i8.
1196 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1197 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001198 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001199 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001200
1201 // Check to make sure that the first operand of the GEP is an integer and
1202 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001203 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001204 if (FirstIdx == 0 || !FirstIdx->isZero())
1205 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001206
1207 // If the second index isn't a ConstantInt, then this is a variable index
1208 // into the array. If this occurs, we can't say anything meaningful about
1209 // the string.
1210 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001211 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001212 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001213 else
1214 return false;
1215 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001216 StopAtNul);
1217 }
1218
1219 // The GEP instruction, constant or instruction, must reference a global
1220 // variable that is a constant and is initialized. The referenced constant
1221 // initializer is the array that we'll use for optimization.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001222 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001223 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001224 return false;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001225 const Constant *GlobalInit = GV->getInitializer();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001226
1227 // Handle the ConstantAggregateZero case
Bill Wendling0582ae92009-03-13 04:39:26 +00001228 if (isa<ConstantAggregateZero>(GlobalInit)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001229 // This is a degenerate case. The initializer is constant zero so the
1230 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001231 Str.clear();
1232 return true;
1233 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001234
1235 // Must be a Constant Array
Dan Gohman0a60fa32010-04-14 22:20:45 +00001236 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001237 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001238 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001239
1240 // Get the number of elements in the array
1241 uint64_t NumElts = Array->getType()->getNumElements();
1242
Bill Wendling0582ae92009-03-13 04:39:26 +00001243 if (Offset > NumElts)
1244 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001245
1246 // Traverse the constant array from 'Offset' which is the place the GEP refers
1247 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001248 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001249 for (unsigned i = Offset; i != NumElts; ++i) {
Dan Gohman0a60fa32010-04-14 22:20:45 +00001250 const Constant *Elt = Array->getOperand(i);
1251 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001252 if (!CI) // This array isn't suitable, non-int initializer.
1253 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001254 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001255 return true; // we found end of string, success!
1256 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001257 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001258
Evan Cheng0ff39b32008-06-30 07:31:25 +00001259 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001260 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001261}
Eric Christopher25ec4832010-03-05 06:58:57 +00001262
1263// These next two are very similar to the above, but also look through PHI
1264// nodes.
1265// TODO: See if we can integrate these two together.
1266
1267/// GetStringLengthH - If we can compute the length of the string pointed to by
1268/// the specified pointer, return 'len+1'. If we can't, return 0.
1269static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1270 // Look through noop bitcast instructions.
1271 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1272 return GetStringLengthH(BCI->getOperand(0), PHIs);
1273
1274 // If this is a PHI node, there are two cases: either we have already seen it
1275 // or we haven't.
1276 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1277 if (!PHIs.insert(PN))
1278 return ~0ULL; // already in the set.
1279
1280 // If it was new, see if all the input strings are the same length.
1281 uint64_t LenSoFar = ~0ULL;
1282 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1283 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1284 if (Len == 0) return 0; // Unknown length -> unknown.
1285
1286 if (Len == ~0ULL) continue;
1287
1288 if (Len != LenSoFar && LenSoFar != ~0ULL)
1289 return 0; // Disagree -> unknown.
1290 LenSoFar = Len;
1291 }
1292
1293 // Success, all agree.
1294 return LenSoFar;
1295 }
1296
1297 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1298 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1299 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1300 if (Len1 == 0) return 0;
1301 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1302 if (Len2 == 0) return 0;
1303 if (Len1 == ~0ULL) return Len2;
1304 if (Len2 == ~0ULL) return Len1;
1305 if (Len1 != Len2) return 0;
1306 return Len1;
1307 }
1308
1309 // If the value is not a GEP instruction nor a constant expression with a
1310 // GEP instruction, then return unknown.
1311 User *GEP = 0;
1312 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1313 GEP = GEPI;
1314 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1315 if (CE->getOpcode() != Instruction::GetElementPtr)
1316 return 0;
1317 GEP = CE;
1318 } else {
1319 return 0;
1320 }
1321
1322 // Make sure the GEP has exactly three arguments.
1323 if (GEP->getNumOperands() != 3)
1324 return 0;
1325
1326 // Check to make sure that the first operand of the GEP is an integer and
1327 // has value 0 so that we are sure we're indexing into the initializer.
1328 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1329 if (!Idx->isZero())
1330 return 0;
1331 } else
1332 return 0;
1333
1334 // If the second index isn't a ConstantInt, then this is a variable index
1335 // into the array. If this occurs, we can't say anything meaningful about
1336 // the string.
1337 uint64_t StartIdx = 0;
1338 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1339 StartIdx = CI->getZExtValue();
1340 else
1341 return 0;
1342
1343 // The GEP instruction, constant or instruction, must reference a global
1344 // variable that is a constant and is initialized. The referenced constant
1345 // initializer is the array that we'll use for optimization.
1346 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1347 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1348 GV->mayBeOverridden())
1349 return 0;
1350 Constant *GlobalInit = GV->getInitializer();
1351
1352 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1353 // initializer is constant zero so the length of the string must be zero.
1354 if (isa<ConstantAggregateZero>(GlobalInit))
1355 return 1; // Len = 0 offset by 1.
1356
1357 // Must be a Constant Array
1358 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1359 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1360 return false;
1361
1362 // Get the number of elements in the array
1363 uint64_t NumElts = Array->getType()->getNumElements();
1364
1365 // Traverse the constant array from StartIdx (derived above) which is
1366 // the place the GEP refers to in the array.
1367 for (unsigned i = StartIdx; i != NumElts; ++i) {
1368 Constant *Elt = Array->getOperand(i);
1369 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1370 if (!CI) // This array isn't suitable, non-int initializer.
1371 return 0;
1372 if (CI->isZero())
1373 return i-StartIdx+1; // We found end of string, success!
1374 }
1375
1376 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1377}
1378
1379/// GetStringLength - If we can compute the length of the string pointed to by
1380/// the specified pointer, return 'len+1'. If we can't, return 0.
1381uint64_t llvm::GetStringLength(Value *V) {
1382 if (!V->getType()->isPointerTy()) return 0;
1383
1384 SmallPtrSet<PHINode*, 32> PHIs;
1385 uint64_t Len = GetStringLengthH(V, PHIs);
1386 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1387 // an empty string as a length.
1388 return Len == ~0ULL ? 1 : Len;
1389}