blob: d1b75c3f9fc4ebc08b5ba90359efdac2b6aa9b2b [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)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000072 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +000073 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)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000079 KnownZero.setAllBits(); KnownOne.setAllBits();
Dan Gohman6de29f82009-06-15 22:12:54 +000080 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
Jay Foad7a874dd2010-12-01 08:53:58 +0000106 KnownZero.clearAllBits();
107 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000108 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()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000114 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000115 } else {
116 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
117 TD, Depth+1);
118 }
119 return;
120 }
Chris Lattner173234a2008-06-02 01:18:21 +0000121
Jay Foad7a874dd2010-12-01 08:53:58 +0000122 KnownZero.clearAllBits(); KnownOne.clearAllBits(); // Start out not knowing anything.
Chris Lattner173234a2008-06-02 01:18:21 +0000123
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.
Jay Foad7a874dd2010-12-01 08:53:58 +0000188 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000189 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
Jay Foad7a874dd2010-12-01 08:53:58 +0000211 KnownOne2.clearAllBits();
212 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000213 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
Jay Foad40f8f622010-12-07 08:25:19 +0000258 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
259 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
260 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000261 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
262 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000263 KnownZero = KnownZero.zextOrTrunc(BitWidth);
264 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000265 // Any top bits are known to be zero.
266 if (BitWidth > SrcBitWidth)
267 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
268 return;
269 }
270 case Instruction::BitCast: {
271 const Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000272 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000273 // TODO: For now, not handling conversions like:
274 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000275 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000276 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
277 Depth+1);
278 return;
279 }
280 break;
281 }
282 case Instruction::SExt: {
283 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000284 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000285
Jay Foad40f8f622010-12-07 08:25:19 +0000286 APInt MaskIn = Mask.trunc(SrcBitWidth);
287 KnownZero = KnownZero.trunc(SrcBitWidth);
288 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000289 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
290 Depth+1);
291 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000292 KnownZero = KnownZero.zext(BitWidth);
293 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000294
295 // If the sign bit of the input is known set or clear, then we know the
296 // top bits of the result.
297 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
298 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
299 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
300 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
301 return;
302 }
303 case Instruction::Shl:
304 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
305 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
306 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
307 APInt Mask2(Mask.lshr(ShiftAmt));
308 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
309 Depth+1);
310 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
311 KnownZero <<= ShiftAmt;
312 KnownOne <<= ShiftAmt;
313 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
314 return;
315 }
316 break;
317 case Instruction::LShr:
318 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
319 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
320 // Compute the new bits that are at the top now.
321 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
322
323 // Unsigned shift right.
324 APInt Mask2(Mask.shl(ShiftAmt));
325 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
326 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000327 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000328 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
329 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
330 // high bits known zero.
331 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
332 return;
333 }
334 break;
335 case Instruction::AShr:
336 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
337 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
338 // Compute the new bits that are at the top now.
339 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
340
341 // Signed shift right.
342 APInt Mask2(Mask.shl(ShiftAmt));
343 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
344 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000345 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000346 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
347 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
348
349 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
350 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
351 KnownZero |= HighBits;
352 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
353 KnownOne |= HighBits;
354 return;
355 }
356 break;
357 case Instruction::Sub: {
358 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
359 // We know that the top bits of C-X are clear if X contains less bits
360 // than C (i.e. no wrap-around can happen). For example, 20-X is
361 // positive if we can prove that X is >= 0 and < 16.
362 if (!CLHS->getValue().isNegative()) {
363 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
364 // NLZ can't be BitWidth with no sign bit
365 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
366 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
367 TD, Depth+1);
368
369 // If all of the MaskV bits are known to be zero, then we know the
370 // output top bits are zero, because we now know that the output is
371 // from [0-C].
372 if ((KnownZero2 & MaskV) == MaskV) {
373 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
374 // Top bits known zero.
375 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
376 }
377 }
378 }
379 }
380 // fall through
381 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000382 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000383 // other operand has in those bit positions will be preserved in the
384 // result. For an add, this works with either operand. For a subtract,
385 // this only works if the known zeros are in the right operand.
386 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
387 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
388 BitWidth - Mask.countLeadingZeros());
389 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000390 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000391 assert((LHSKnownZero & LHSKnownOne) == 0 &&
392 "Bits known to be one AND zero?");
393 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000394
395 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
396 Depth+1);
397 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000398 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000399
Dan Gohman39250432009-05-24 18:02:35 +0000400 // Determine which operand has more trailing zeros, and use that
401 // many bits from the other operand.
402 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000403 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000404 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
405 KnownZero |= KnownZero2 & Mask;
406 KnownOne |= KnownOne2 & Mask;
407 } else {
408 // If the known zeros are in the left operand for a subtract,
409 // fall back to the minimum known zeros in both operands.
410 KnownZero |= APInt::getLowBitsSet(BitWidth,
411 std::min(LHSKnownZeroOut,
412 RHSKnownZeroOut));
413 }
414 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
415 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
416 KnownZero |= LHSKnownZero & Mask;
417 KnownOne |= LHSKnownOne & Mask;
418 }
Chris Lattner173234a2008-06-02 01:18:21 +0000419 return;
420 }
421 case Instruction::SRem:
422 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000423 APInt RA = Rem->getValue().abs();
424 if (RA.isPowerOf2()) {
425 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000426 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
427 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
428 Depth+1);
429
Duncan Sandscfd54182010-01-29 06:18:37 +0000430 // The low bits of the first operand are unchanged by the srem.
431 KnownZero = KnownZero2 & LowBits;
432 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000433
Duncan Sandscfd54182010-01-29 06:18:37 +0000434 // If the first operand is non-negative or has all low bits zero, then
435 // the upper bits are all zero.
436 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
437 KnownZero |= ~LowBits;
438
439 // If the first operand is negative and not all low bits are zero, then
440 // the upper bits are all one.
441 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
442 KnownOne |= ~LowBits;
443
444 KnownZero &= Mask;
445 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000446
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000447 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000448 }
449 }
450 break;
451 case Instruction::URem: {
452 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
453 APInt RA = Rem->getValue();
454 if (RA.isPowerOf2()) {
455 APInt LowBits = (RA - 1);
456 APInt Mask2 = LowBits & Mask;
457 KnownZero |= ~LowBits & Mask;
458 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
459 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000460 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000461 break;
462 }
463 }
464
465 // Since the result is less than or equal to either operand, any leading
466 // zero bits in either operand must also exist in the result.
467 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
468 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
469 TD, Depth+1);
470 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
471 TD, Depth+1);
472
Chris Lattner79abedb2009-01-20 18:22:57 +0000473 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000474 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000475 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000476 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
477 break;
478 }
479
Victor Hernandeza276c602009-10-17 01:18:07 +0000480 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000481 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000482 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000483 if (Align == 0 && TD)
484 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000485
486 if (Align > 0)
487 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
488 CountTrailingZeros_32(Align));
489 break;
490 }
491 case Instruction::GetElementPtr: {
492 // Analyze all of the subscripts of this getelementptr instruction
493 // to determine if we can prove known low zero bits.
494 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
495 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
496 ComputeMaskedBits(I->getOperand(0), LocalMask,
497 LocalKnownZero, LocalKnownOne, TD, Depth+1);
498 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
499
500 gep_type_iterator GTI = gep_type_begin(I);
501 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
502 Value *Index = I->getOperand(i);
503 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
504 // Handle struct member offset arithmetic.
505 if (!TD) return;
506 const StructLayout *SL = TD->getStructLayout(STy);
507 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
508 uint64_t Offset = SL->getElementOffset(Idx);
509 TrailZ = std::min(TrailZ,
510 CountTrailingZeros_64(Offset));
511 } else {
512 // Handle array index arithmetic.
513 const Type *IndexedTy = GTI.getIndexedType();
514 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000515 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000516 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000517 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
518 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
519 ComputeMaskedBits(Index, LocalMask,
520 LocalKnownZero, LocalKnownOne, TD, Depth+1);
521 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000522 unsigned(CountTrailingZeros_64(TypeSize) +
523 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000524 }
525 }
526
527 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
528 break;
529 }
530 case Instruction::PHI: {
531 PHINode *P = cast<PHINode>(I);
532 // Handle the case of a simple two-predecessor recurrence PHI.
533 // There's a lot more that could theoretically be done here, but
534 // this is sufficient to catch some interesting cases.
535 if (P->getNumIncomingValues() == 2) {
536 for (unsigned i = 0; i != 2; ++i) {
537 Value *L = P->getIncomingValue(i);
538 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000539 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000540 if (!LU)
541 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000542 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000543 // Check for operations that have the property that if
544 // both their operands have low zero bits, the result
545 // will have low zero bits.
546 if (Opcode == Instruction::Add ||
547 Opcode == Instruction::Sub ||
548 Opcode == Instruction::And ||
549 Opcode == Instruction::Or ||
550 Opcode == Instruction::Mul) {
551 Value *LL = LU->getOperand(0);
552 Value *LR = LU->getOperand(1);
553 // Find a recurrence.
554 if (LL == I)
555 L = LR;
556 else if (LR == I)
557 L = LL;
558 else
559 break;
560 // Ok, we have a PHI of the form L op= R. Check for low
561 // zero bits.
562 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
563 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
564 Mask2 = APInt::getLowBitsSet(BitWidth,
565 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000566
567 // We need to take the minimum number of known bits
568 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
569 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
570
Chris Lattner173234a2008-06-02 01:18:21 +0000571 KnownZero = Mask &
572 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000573 std::min(KnownZero2.countTrailingOnes(),
574 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000575 break;
576 }
577 }
578 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000579
580 // Otherwise take the unions of the known bit sets of the operands,
581 // taking conservative care to avoid excessive recursion.
582 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
583 KnownZero = APInt::getAllOnesValue(BitWidth);
584 KnownOne = APInt::getAllOnesValue(BitWidth);
585 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
586 // Skip direct self references.
587 if (P->getIncomingValue(i) == P) continue;
588
589 KnownZero2 = APInt(BitWidth, 0);
590 KnownOne2 = APInt(BitWidth, 0);
591 // Recurse, but cap the recursion to one level, because we don't
592 // want to waste time spinning around in loops.
593 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
594 KnownZero2, KnownOne2, TD, MaxDepth-1);
595 KnownZero &= KnownZero2;
596 KnownOne &= KnownOne2;
597 // If all bits have been ruled out, there's no need to check
598 // more operands.
599 if (!KnownZero && !KnownOne)
600 break;
601 }
602 }
Chris Lattner173234a2008-06-02 01:18:21 +0000603 break;
604 }
605 case Instruction::Call:
606 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
607 switch (II->getIntrinsicID()) {
608 default: break;
609 case Intrinsic::ctpop:
610 case Intrinsic::ctlz:
611 case Intrinsic::cttz: {
612 unsigned LowBits = Log2_32(BitWidth)+1;
613 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
614 break;
615 }
616 }
617 }
618 break;
619 }
620}
621
622/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
623/// this predicate to simplify operations downstream. Mask is known to be zero
624/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000625///
626/// This function is defined on values with integer type, values with pointer
627/// type (but only if TD is non-null), and vectors of integers. In the case
628/// where V is a vector, the mask, known zero, and known one values are the
629/// same width as the vector element, and the bit is set only if it is true
630/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000631bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000632 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000633 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
634 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
636 return (KnownZero & Mask) == Mask;
637}
638
639
640
641/// ComputeNumSignBits - Return the number of times the sign bit of the
642/// register is replicated into the other bits. We know that at least 1 bit
643/// is always equal to the sign bit (itself), but other cases can give us
644/// information. For example, immediately after an "ashr X, 2", we know that
645/// the top 3 bits are all equal to each other, so we return 3.
646///
647/// 'Op' must have a scalar integer type.
648///
Dan Gohman846a2f22009-08-27 17:51:25 +0000649unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
650 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000651 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000652 "ComputeNumSignBits requires a TargetData object to operate "
653 "on non-integer values!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000654 const Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000655 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
656 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000657 unsigned Tmp, Tmp2;
658 unsigned FirstAnswer = 1;
659
Chris Lattnerd82e5112008-06-02 18:39:07 +0000660 // Note that ConstantInt is handled by the general ComputeMaskedBits case
661 // below.
662
Chris Lattner173234a2008-06-02 01:18:21 +0000663 if (Depth == 6)
664 return 1; // Limit search depth.
665
Dan Gohmanca178902009-07-17 20:47:02 +0000666 Operator *U = dyn_cast<Operator>(V);
667 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000668 default: break;
669 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +0000670 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000671 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
672
673 case Instruction::AShr:
674 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
675 // ashr X, C -> adds C sign bits.
676 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
677 Tmp += C->getZExtValue();
678 if (Tmp > TyBits) Tmp = TyBits;
679 }
680 return Tmp;
681 case Instruction::Shl:
682 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
683 // shl destroys sign bits.
684 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
685 if (C->getZExtValue() >= TyBits || // Bad shift.
686 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
687 return Tmp - C->getZExtValue();
688 }
689 break;
690 case Instruction::And:
691 case Instruction::Or:
692 case Instruction::Xor: // NOT is handled here.
693 // Logical binary ops preserve the number of sign bits at the worst.
694 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
695 if (Tmp != 1) {
696 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
697 FirstAnswer = std::min(Tmp, Tmp2);
698 // We computed what we know about the sign bits as our first
699 // answer. Now proceed to the generic code that uses
700 // ComputeMaskedBits, and pick whichever answer is better.
701 }
702 break;
703
704 case Instruction::Select:
705 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
706 if (Tmp == 1) return 1; // Early out.
707 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
708 return std::min(Tmp, Tmp2);
709
710 case Instruction::Add:
711 // Add can have at most one carry bit. Thus we know that the output
712 // is, at worst, one more bit than the inputs.
713 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
714 if (Tmp == 1) return 1; // Early out.
715
716 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +0000717 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +0000718 if (CRHS->isAllOnesValue()) {
719 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
720 APInt Mask = APInt::getAllOnesValue(TyBits);
721 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
722 Depth+1);
723
724 // If the input is known to be 0 or 1, the output is 0/-1, which is all
725 // sign bits set.
726 if ((KnownZero | APInt(TyBits, 1)) == Mask)
727 return TyBits;
728
729 // If we are subtracting one from a positive number, there is no carry
730 // out of the result.
731 if (KnownZero.isNegative())
732 return Tmp;
733 }
734
735 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
736 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000737 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +0000738
739 case Instruction::Sub:
740 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
741 if (Tmp2 == 1) return 1;
742
743 // Handle NEG.
744 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
745 if (CLHS->isNullValue()) {
746 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
747 APInt Mask = APInt::getAllOnesValue(TyBits);
748 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
749 TD, Depth+1);
750 // If the input is known to be 0 or 1, the output is 0/-1, which is all
751 // sign bits set.
752 if ((KnownZero | APInt(TyBits, 1)) == Mask)
753 return TyBits;
754
755 // If the input is known to be positive (the sign bit is known clear),
756 // the output of the NEG has the same number of sign bits as the input.
757 if (KnownZero.isNegative())
758 return Tmp2;
759
760 // Otherwise, we treat this like a SUB.
761 }
762
763 // Sub can have at most one carry bit. Thus we know that the output
764 // is, at worst, one more bit than the inputs.
765 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
766 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000767 return std::min(Tmp, Tmp2)-1;
768
769 case Instruction::PHI: {
770 PHINode *PN = cast<PHINode>(U);
771 // Don't analyze large in-degree PHIs.
772 if (PN->getNumIncomingValues() > 4) break;
773
774 // Take the minimum of all incoming values. This can't infinitely loop
775 // because of our depth threshold.
776 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
777 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
778 if (Tmp == 1) return Tmp;
779 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +0000780 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000781 }
782 return Tmp;
783 }
784
Chris Lattner173234a2008-06-02 01:18:21 +0000785 case Instruction::Trunc:
786 // FIXME: it's tricky to do anything useful for this, but it is an important
787 // case for targets like X86.
788 break;
789 }
790
791 // Finally, if we can prove that the top bits of the result are 0's or 1's,
792 // use this information.
793 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
794 APInt Mask = APInt::getAllOnesValue(TyBits);
795 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
796
797 if (KnownZero.isNegative()) { // sign bit is 0
798 Mask = KnownZero;
799 } else if (KnownOne.isNegative()) { // sign bit is 1;
800 Mask = KnownOne;
801 } else {
802 // Nothing known.
803 return FirstAnswer;
804 }
805
806 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
807 // the number of identical bits in the top of the input value.
808 Mask = ~Mask;
809 Mask <<= Mask.getBitWidth()-TyBits;
810 // Return # leading zeros. We use 'min' here in case Val was zero before
811 // shifting. We don't want to return '64' as for an i32 "0".
812 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
813}
Chris Lattner833f25d2008-06-02 01:29:46 +0000814
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000815/// ComputeMultiple - This function computes the integer multiple of Base that
816/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000817/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000818/// through SExt instructions only if LookThroughSExt is true.
819bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000820 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000821 const unsigned MaxDepth = 6;
822
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000823 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000824 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000825 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000826
827 const Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000828
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000829 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000830
831 if (Base == 0)
832 return false;
833
834 if (Base == 1) {
835 Multiple = V;
836 return true;
837 }
838
839 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
840 Constant *BaseVal = ConstantInt::get(T, Base);
841 if (CO && CO == BaseVal) {
842 // Multiple is 1.
843 Multiple = ConstantInt::get(T, 1);
844 return true;
845 }
846
847 if (CI && CI->getZExtValue() % Base == 0) {
848 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
849 return true;
850 }
851
852 if (Depth == MaxDepth) return false; // Limit search depth.
853
854 Operator *I = dyn_cast<Operator>(V);
855 if (!I) return false;
856
857 switch (I->getOpcode()) {
858 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +0000859 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000860 if (!LookThroughSExt) return false;
861 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +0000862 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000863 return ComputeMultiple(I->getOperand(0), Base, Multiple,
864 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000865 case Instruction::Shl:
866 case Instruction::Mul: {
867 Value *Op0 = I->getOperand(0);
868 Value *Op1 = I->getOperand(1);
869
870 if (I->getOpcode() == Instruction::Shl) {
871 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
872 if (!Op1CI) return false;
873 // Turn Op0 << Op1 into Op0 * 2^Op1
874 APInt Op1Int = Op1CI->getValue();
875 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +0000876 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +0000877 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +0000878 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000879 }
880
881 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +0000882 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
883 if (Constant *Op1C = dyn_cast<Constant>(Op1))
884 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
885 if (Op1C->getType()->getPrimitiveSizeInBits() <
886 MulC->getType()->getPrimitiveSizeInBits())
887 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
888 if (Op1C->getType()->getPrimitiveSizeInBits() >
889 MulC->getType()->getPrimitiveSizeInBits())
890 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
891
892 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
893 Multiple = ConstantExpr::getMul(MulC, Op1C);
894 return true;
895 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000896
897 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
898 if (Mul0CI->getValue() == 1) {
899 // V == Base * Op1, so return Op1
900 Multiple = Op1;
901 return true;
902 }
903 }
904
Chris Lattnere9711312010-09-05 17:20:46 +0000905 Value *Mul1 = NULL;
906 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
907 if (Constant *Op0C = dyn_cast<Constant>(Op0))
908 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
909 if (Op0C->getType()->getPrimitiveSizeInBits() <
910 MulC->getType()->getPrimitiveSizeInBits())
911 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
912 if (Op0C->getType()->getPrimitiveSizeInBits() >
913 MulC->getType()->getPrimitiveSizeInBits())
914 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
915
916 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
917 Multiple = ConstantExpr::getMul(MulC, Op0C);
918 return true;
919 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000920
921 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
922 if (Mul1CI->getValue() == 1) {
923 // V == Base * Op0, so return Op0
924 Multiple = Op0;
925 return true;
926 }
927 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000928 }
929 }
930
931 // We could not determine if V is a multiple of Base.
932 return false;
933}
934
Chris Lattner833f25d2008-06-02 01:29:46 +0000935/// CannotBeNegativeZero - Return true if we can prove that the specified FP
936/// value is never equal to -0.0.
937///
938/// NOTE: this function will need to be revisited when we support non-default
939/// rounding modes!
940///
941bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
942 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
943 return !CFP->getValueAPF().isNegZero();
944
945 if (Depth == 6)
946 return 1; // Limit search depth.
947
Dan Gohmanca178902009-07-17 20:47:02 +0000948 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +0000949 if (I == 0) return false;
950
951 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000952 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +0000953 isa<ConstantFP>(I->getOperand(1)) &&
954 cast<ConstantFP>(I->getOperand(1))->isNullValue())
955 return true;
956
957 // sitofp and uitofp turn into +0.0 for zero.
958 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
959 return true;
960
961 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
962 // sqrt(-0.0) = -0.0, no other negative results are possible.
963 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +0000964 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +0000965
966 if (const CallInst *CI = dyn_cast<CallInst>(I))
967 if (const Function *F = CI->getCalledFunction()) {
968 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000969 // abs(x) != -0.0
970 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +0000971 // fabs[lf](x) != -0.0
972 if (F->getName() == "fabs") return true;
973 if (F->getName() == "fabsf") return true;
974 if (F->getName() == "fabsl") return true;
975 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
976 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +0000977 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +0000978 }
979 }
980
981 return false;
982}
983
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000984// This is the recursive version of BuildSubAggregate. It takes a few different
985// arguments. Idxs is the index within the nested struct From that we are
986// looking at now (which is of type IndexedType). IdxSkip is the number of
987// indices from Idxs that should be left out when inserting into the resulting
988// struct. To is the result struct built so far, new insertvalue instructions
989// build on that.
Dan Gohman7db949d2009-08-07 01:32:21 +0000990static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
991 SmallVector<unsigned, 10> &Idxs,
992 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +0000993 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000994 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
995 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000996 // Save the original To argument so we can modify it
997 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000998 // General case, the type indexed by Idxs is a struct
999 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1000 // Process each struct element recursively
1001 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001002 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001003 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001004 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001005 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001006 if (!To) {
1007 // Couldn't find any inserted value for this index? Cleanup
1008 while (PrevTo != OrigTo) {
1009 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1010 PrevTo = Del->getAggregateOperand();
1011 Del->eraseFromParent();
1012 }
1013 // Stop processing elements
1014 break;
1015 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001016 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001017 // If we succesfully found a value for each of our subaggregates
1018 if (To)
1019 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001020 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001021 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1022 // the struct's elements had a value that was inserted directly. In the latter
1023 // case, perhaps we can't determine each of the subelements individually, but
1024 // we might be able to find the complete struct somewhere.
1025
1026 // Find the value that is at that particular spot
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001027 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001028
1029 if (!V)
1030 return NULL;
1031
1032 // Insert the value in the new (sub) aggregrate
1033 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
1034 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001035}
1036
1037// This helper takes a nested struct and extracts a part of it (which is again a
1038// struct) into a new value. For example, given the struct:
1039// { a, { b, { c, d }, e } }
1040// and the indices "1, 1" this returns
1041// { c, d }.
1042//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001043// It does this by inserting an insertvalue for each element in the resulting
1044// struct, as opposed to just inserting a single struct. This will only work if
1045// each of the elements of the substruct are known (ie, inserted into From by an
1046// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001047//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001048// All inserted insertvalue instructions are inserted before InsertBefore
Dan Gohman7db949d2009-08-07 01:32:21 +00001049static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001050 const unsigned *idx_end,
Dan Gohman7db949d2009-08-07 01:32:21 +00001051 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001052 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001053 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1054 idx_begin,
1055 idx_end);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001056 Value *To = UndefValue::get(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001057 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
1058 unsigned IdxSkip = Idxs.size();
1059
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001060 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001061}
1062
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001063/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1064/// the scalar value indexed is already around as a register, for example if it
1065/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001066///
1067/// If InsertBefore is not null, this function will duplicate (modified)
1068/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001069Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001070 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001071 // Nothing to index? Just return V then (this is useful at the end of our
1072 // recursion)
1073 if (idx_begin == idx_end)
1074 return V;
1075 // We have indices, so V should have an indexable type
Duncan Sands1df98592010-02-16 11:11:14 +00001076 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001077 && "Not looking at a struct or array?");
1078 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
1079 && "Invalid indices for type?");
1080 const CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +00001081
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001082 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001083 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001084 idx_begin,
1085 idx_end));
1086 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00001087 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Owen Anderson76f600b2009-07-06 22:37:39 +00001088 idx_begin,
1089 idx_end));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001090 else if (Constant *C = dyn_cast<Constant>(V)) {
1091 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1092 // Recursively process this constant
Owen Anderson76f600b2009-07-06 22:37:39 +00001093 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001094 idx_end, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001095 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1096 // Loop the indices for the insertvalue instruction in parallel with the
1097 // requested indices
1098 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001099 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1100 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +00001101 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001102 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001103 // The requested index identifies a part of a nested aggregate. Handle
1104 // this specially. For example,
1105 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1106 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1107 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1108 // This can be changed into
1109 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1110 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1111 // which allows the unused 0,0 element from the nested struct to be
1112 // removed.
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001113 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +00001114 else
1115 // We can't handle this without inserting insertvalues
1116 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +00001117 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001118
1119 // This insert value inserts something else than what we are looking for.
1120 // See if the (aggregrate) value inserted into has the value we are
1121 // looking for, then.
1122 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001123 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001124 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001125 }
1126 // If we end up here, the indices of the insertvalue match with those
1127 // requested (though possibly only partially). Now we recursively look at
1128 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001129 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001130 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001131 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1132 // If we're extracting a value from an aggregrate that was extracted from
1133 // something else, we can extract from that something else directly instead.
1134 // However, we will need to chain I's indices with the requested indices.
1135
1136 // Calculate the number of indices required
1137 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
1138 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001139 SmallVector<unsigned, 5> Idxs;
1140 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001141 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001142 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001143 i != e; ++i)
1144 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001145
1146 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001147 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1148 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001149
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001150 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001151 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001152
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001153 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001154 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001155 }
1156 // Otherwise, we don't know (such as, extracting from a function return value
1157 // or load instruction)
1158 return 0;
1159}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001160
Chris Lattnered58a6f2010-11-30 22:25:26 +00001161/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1162/// it can be expressed as a base pointer plus a constant offset. Return the
1163/// base and offset to the caller.
1164Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1165 const TargetData &TD) {
1166 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1167 if (PtrOp == 0) return Ptr;
1168
1169 // Just look through bitcasts.
1170 if (PtrOp->getOpcode() == Instruction::BitCast)
1171 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1172
1173 // If this is a GEP with constant indices, we can look through it.
1174 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1175 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1176
1177 gep_type_iterator GTI = gep_type_begin(GEP);
1178 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1179 ++I, ++GTI) {
1180 ConstantInt *OpC = cast<ConstantInt>(*I);
1181 if (OpC->isZero()) continue;
1182
1183 // Handle a struct and array indices which add their offset to the pointer.
1184 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1185 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1186 } else {
1187 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1188 Offset += OpC->getSExtValue()*Size;
1189 }
1190 }
1191
1192 // Re-sign extend from the pointer size if needed to get overflow edge cases
1193 // right.
1194 unsigned PtrSize = TD.getPointerSizeInBits();
1195 if (PtrSize < 64)
1196 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1197
1198 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1199}
1200
1201
Evan Cheng0ff39b32008-06-30 07:31:25 +00001202/// GetConstantStringInfo - This function computes the length of a
1203/// null-terminated C string pointed to by V. If successful, it returns true
1204/// and returns the string in Str. If unsuccessful, it returns false.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001205bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1206 uint64_t Offset,
Bill Wendling0582ae92009-03-13 04:39:26 +00001207 bool StopAtNul) {
1208 // If V is NULL then return false;
1209 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001210
1211 // Look through bitcast instructions.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001212 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001213 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1214
Evan Cheng0ff39b32008-06-30 07:31:25 +00001215 // If the value is not a GEP instruction nor a constant expression with a
1216 // GEP instruction, then return false because ConstantArray can't occur
1217 // any other way
Dan Gohman0a60fa32010-04-14 22:20:45 +00001218 const User *GEP = 0;
1219 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001220 GEP = GEPI;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001221 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001222 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001223 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1224 if (CE->getOpcode() != Instruction::GetElementPtr)
1225 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001226 GEP = CE;
1227 }
1228
1229 if (GEP) {
1230 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001231 if (GEP->getNumOperands() != 3)
1232 return false;
1233
Evan Cheng0ff39b32008-06-30 07:31:25 +00001234 // Make sure the index-ee is a pointer to array of i8.
1235 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1236 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001237 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001238 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001239
1240 // Check to make sure that the first operand of the GEP is an integer and
1241 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001242 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001243 if (FirstIdx == 0 || !FirstIdx->isZero())
1244 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001245
1246 // If the second index isn't a ConstantInt, then this is a variable index
1247 // into the array. If this occurs, we can't say anything meaningful about
1248 // the string.
1249 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001250 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001251 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001252 else
1253 return false;
1254 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001255 StopAtNul);
1256 }
1257
1258 // The GEP instruction, constant or instruction, must reference a global
1259 // variable that is a constant and is initialized. The referenced constant
1260 // initializer is the array that we'll use for optimization.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001261 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001262 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001263 return false;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001264 const Constant *GlobalInit = GV->getInitializer();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001265
1266 // Handle the ConstantAggregateZero case
Bill Wendling0582ae92009-03-13 04:39:26 +00001267 if (isa<ConstantAggregateZero>(GlobalInit)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001268 // This is a degenerate case. The initializer is constant zero so the
1269 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001270 Str.clear();
1271 return true;
1272 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001273
1274 // Must be a Constant Array
Dan Gohman0a60fa32010-04-14 22:20:45 +00001275 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001276 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001277 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001278
1279 // Get the number of elements in the array
1280 uint64_t NumElts = Array->getType()->getNumElements();
1281
Bill Wendling0582ae92009-03-13 04:39:26 +00001282 if (Offset > NumElts)
1283 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001284
1285 // Traverse the constant array from 'Offset' which is the place the GEP refers
1286 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001287 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001288 for (unsigned i = Offset; i != NumElts; ++i) {
Dan Gohman0a60fa32010-04-14 22:20:45 +00001289 const Constant *Elt = Array->getOperand(i);
1290 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001291 if (!CI) // This array isn't suitable, non-int initializer.
1292 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001293 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001294 return true; // we found end of string, success!
1295 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001296 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001297
Evan Cheng0ff39b32008-06-30 07:31:25 +00001298 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001299 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001300}
Eric Christopher25ec4832010-03-05 06:58:57 +00001301
1302// These next two are very similar to the above, but also look through PHI
1303// nodes.
1304// TODO: See if we can integrate these two together.
1305
1306/// GetStringLengthH - If we can compute the length of the string pointed to by
1307/// the specified pointer, return 'len+1'. If we can't, return 0.
1308static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1309 // Look through noop bitcast instructions.
1310 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1311 return GetStringLengthH(BCI->getOperand(0), PHIs);
1312
1313 // If this is a PHI node, there are two cases: either we have already seen it
1314 // or we haven't.
1315 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1316 if (!PHIs.insert(PN))
1317 return ~0ULL; // already in the set.
1318
1319 // If it was new, see if all the input strings are the same length.
1320 uint64_t LenSoFar = ~0ULL;
1321 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1322 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1323 if (Len == 0) return 0; // Unknown length -> unknown.
1324
1325 if (Len == ~0ULL) continue;
1326
1327 if (Len != LenSoFar && LenSoFar != ~0ULL)
1328 return 0; // Disagree -> unknown.
1329 LenSoFar = Len;
1330 }
1331
1332 // Success, all agree.
1333 return LenSoFar;
1334 }
1335
1336 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1337 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1338 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1339 if (Len1 == 0) return 0;
1340 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1341 if (Len2 == 0) return 0;
1342 if (Len1 == ~0ULL) return Len2;
1343 if (Len2 == ~0ULL) return Len1;
1344 if (Len1 != Len2) return 0;
1345 return Len1;
1346 }
1347
1348 // If the value is not a GEP instruction nor a constant expression with a
1349 // GEP instruction, then return unknown.
1350 User *GEP = 0;
1351 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1352 GEP = GEPI;
1353 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1354 if (CE->getOpcode() != Instruction::GetElementPtr)
1355 return 0;
1356 GEP = CE;
1357 } else {
1358 return 0;
1359 }
1360
1361 // Make sure the GEP has exactly three arguments.
1362 if (GEP->getNumOperands() != 3)
1363 return 0;
1364
1365 // Check to make sure that the first operand of the GEP is an integer and
1366 // has value 0 so that we are sure we're indexing into the initializer.
1367 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1368 if (!Idx->isZero())
1369 return 0;
1370 } else
1371 return 0;
1372
1373 // If the second index isn't a ConstantInt, then this is a variable index
1374 // into the array. If this occurs, we can't say anything meaningful about
1375 // the string.
1376 uint64_t StartIdx = 0;
1377 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1378 StartIdx = CI->getZExtValue();
1379 else
1380 return 0;
1381
1382 // The GEP instruction, constant or instruction, must reference a global
1383 // variable that is a constant and is initialized. The referenced constant
1384 // initializer is the array that we'll use for optimization.
1385 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1386 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1387 GV->mayBeOverridden())
1388 return 0;
1389 Constant *GlobalInit = GV->getInitializer();
1390
1391 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1392 // initializer is constant zero so the length of the string must be zero.
1393 if (isa<ConstantAggregateZero>(GlobalInit))
1394 return 1; // Len = 0 offset by 1.
1395
1396 // Must be a Constant Array
1397 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1398 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1399 return false;
1400
1401 // Get the number of elements in the array
1402 uint64_t NumElts = Array->getType()->getNumElements();
1403
1404 // Traverse the constant array from StartIdx (derived above) which is
1405 // the place the GEP refers to in the array.
1406 for (unsigned i = StartIdx; i != NumElts; ++i) {
1407 Constant *Elt = Array->getOperand(i);
1408 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1409 if (!CI) // This array isn't suitable, non-int initializer.
1410 return 0;
1411 if (CI->isZero())
1412 return i-StartIdx+1; // We found end of string, success!
1413 }
1414
1415 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1416}
1417
1418/// GetStringLength - If we can compute the length of the string pointed to by
1419/// the specified pointer, return 'len+1'. If we can't, return 0.
1420uint64_t llvm::GetStringLength(Value *V) {
1421 if (!V->getType()->isPointerTy()) return 0;
1422
1423 SmallPtrSet<PHINode*, 32> PHIs;
1424 uint64_t Len = GetStringLengthH(V, PHIs);
1425 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1426 // an empty string as a length.
1427 return Len == ~0ULL ? 1 : Len;
1428}
Dan Gohman5034dd32010-12-15 20:02:24 +00001429
1430Value *llvm::GetUnderlyingObject(Value *V, unsigned MaxLookup) {
1431 if (!V->getType()->isPointerTy())
1432 return V;
1433 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1434 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1435 V = GEP->getPointerOperand();
1436 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1437 V = cast<Operator>(V)->getOperand(0);
1438 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1439 if (GA->mayBeOverridden())
1440 return V;
1441 V = GA->getAliasee();
1442 } else {
1443 return V;
1444 }
1445 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1446 }
1447 return V;
1448}