blob: 78bb3dbc65d4244a97a67fd519a05e942c1c00a7 [file] [log] [blame]
Chris Lattner173234a2008-06-02 01:18:21 +00001//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains routines that help analyze properties that chains of
11// computations have.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ValueTracking.h"
16#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000018#include "llvm/GlobalVariable.h"
Chris Lattner173234a2008-06-02 01:18:21 +000019#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000020#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000021#include "llvm/Operator.h"
Bill Wendling0582ae92009-03-13 04:39:26 +000022#include "llvm/Target/TargetData.h"
Chris Lattner173234a2008-06-02 01:18:21 +000023#include "llvm/Support/GetElementPtrTypeIterator.h"
24#include "llvm/Support/MathExtras.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000025#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000026using namespace llvm;
27
Chris Lattner173234a2008-06-02 01:18:21 +000028/// ComputeMaskedBits - Determine which of the bits specified in Mask are
29/// known to be either zero or one and return them in the KnownZero/KnownOne
30/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
31/// processing.
32/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
33/// we cannot optimize based on the assumption that it is zero without changing
34/// it to be an explicit zero. If we don't change it to zero, other code could
35/// optimized based on the contradictory assumption that it is non-zero.
36/// Because instcombine aggressively folds operations with undef args anyway,
37/// this won't lose us code quality.
Chris Lattnercf5128e2009-09-08 00:06:16 +000038///
39/// This function is defined on values with integer type, values with pointer
40/// type (but only if TD is non-null), and vectors of integers. In the case
41/// where V is a vector, the mask, known zero, and known one values are the
42/// same width as the vector element, and the bit is set only if it is true
43/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +000044void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
45 APInt &KnownZero, APInt &KnownOne,
Dan Gohman846a2f22009-08-27 17:51:25 +000046 const TargetData *TD, unsigned Depth) {
Dan Gohman9004c8a2009-05-21 02:28:33 +000047 const unsigned MaxDepth = 6;
Chris Lattner173234a2008-06-02 01:18:21 +000048 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +000049 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +000050 unsigned BitWidth = Mask.getBitWidth();
Dan Gohman6de29f82009-06-15 22:12:54 +000051 assert((V->getType()->isIntOrIntVector() || isa<PointerType>(V->getType())) &&
Chris Lattner173234a2008-06-02 01:18:21 +000052 "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +000053 assert((!TD ||
54 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
55 (!V->getType()->isIntOrIntVector() ||
56 V->getType()->getScalarSizeInBits() == BitWidth) &&
Chris Lattner173234a2008-06-02 01:18:21 +000057 KnownZero.getBitWidth() == BitWidth &&
58 KnownOne.getBitWidth() == BitWidth &&
59 "V, Mask, KnownOne and KnownZero should have same BitWidth");
60
61 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
62 // We know all of the bits for a constant!
63 KnownOne = CI->getValue() & Mask;
64 KnownZero = ~KnownOne & Mask;
65 return;
66 }
Dan Gohman6de29f82009-06-15 22:12:54 +000067 // Null and aggregate-zero are all-zeros.
68 if (isa<ConstantPointerNull>(V) ||
69 isa<ConstantAggregateZero>(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +000070 KnownOne.clear();
71 KnownZero = Mask;
72 return;
73 }
Dan Gohman6de29f82009-06-15 22:12:54 +000074 // Handle a constant vector by taking the intersection of the known bits of
75 // each element.
76 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
77 KnownZero.set(); KnownOne.set();
78 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
79 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
80 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
81 TD, Depth);
82 KnownZero &= KnownZero2;
83 KnownOne &= KnownOne2;
84 }
85 return;
86 }
Chris Lattner173234a2008-06-02 01:18:21 +000087 // The address of an aligned GlobalValue has trailing zeros.
88 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
89 unsigned Align = GV->getAlignment();
Dan Gohman00407252009-08-11 15:50:03 +000090 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
91 const Type *ObjectType = GV->getType()->getElementType();
92 // If the object is defined in the current Module, we'll be giving
93 // it the preferred alignment. Otherwise, we have to assume that it
94 // may only have the minimum ABI alignment.
95 if (!GV->isDeclaration() && !GV->mayBeOverridden())
96 Align = TD->getPrefTypeAlignment(ObjectType);
97 else
98 Align = TD->getABITypeAlignment(ObjectType);
99 }
Chris Lattner173234a2008-06-02 01:18:21 +0000100 if (Align > 0)
101 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
102 CountTrailingZeros_32(Align));
103 else
104 KnownZero.clear();
105 KnownOne.clear();
106 return;
107 }
108
109 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
110
Dan Gohman9004c8a2009-05-21 02:28:33 +0000111 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000112 return; // Limit search depth.
113
Dan Gohmanca178902009-07-17 20:47:02 +0000114 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000115 if (!I) return;
116
117 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000118 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000119 default: break;
120 case Instruction::And: {
121 // If either the LHS or the RHS are Zero, the result is zero.
122 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
123 APInt Mask2(Mask & ~KnownZero);
124 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
125 Depth+1);
126 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
127 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
128
129 // Output known-1 bits are only known if set in both the LHS & RHS.
130 KnownOne &= KnownOne2;
131 // Output known-0 are known to be clear if zero in either the LHS | RHS.
132 KnownZero |= KnownZero2;
133 return;
134 }
135 case Instruction::Or: {
136 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
137 APInt Mask2(Mask & ~KnownOne);
138 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
139 Depth+1);
140 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
141 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
142
143 // Output known-0 bits are only known if clear in both the LHS & RHS.
144 KnownZero &= KnownZero2;
145 // Output known-1 are known to be set if set in either the LHS | RHS.
146 KnownOne |= KnownOne2;
147 return;
148 }
149 case Instruction::Xor: {
150 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
151 ComputeMaskedBits(I->getOperand(0), Mask, 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 known if clear or set in both the LHS & RHS.
157 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
158 // Output known-1 are known to be set if set in only one of the LHS, RHS.
159 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
160 KnownZero = KnownZeroOut;
161 return;
162 }
163 case Instruction::Mul: {
164 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
165 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
166 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
167 Depth+1);
168 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
169 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
170
171 // If low bits are zero in either operand, output low known-0 bits.
172 // Also compute a conserative estimate for high known-0 bits.
173 // More trickiness is possible, but this is sufficient for the
174 // interesting case of alignment computation.
175 KnownOne.clear();
176 unsigned TrailZ = KnownZero.countTrailingOnes() +
177 KnownZero2.countTrailingOnes();
178 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
179 KnownZero2.countLeadingOnes(),
180 BitWidth) - BitWidth;
181
182 TrailZ = std::min(TrailZ, BitWidth);
183 LeadZ = std::min(LeadZ, BitWidth);
184 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
185 APInt::getHighBitsSet(BitWidth, LeadZ);
186 KnownZero &= Mask;
187 return;
188 }
189 case Instruction::UDiv: {
190 // For the purposes of computing leading zeros we can conservatively
191 // treat a udiv as a logical right shift by the power of 2 known to
192 // be less than the denominator.
193 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
194 ComputeMaskedBits(I->getOperand(0),
195 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
196 unsigned LeadZ = KnownZero2.countLeadingOnes();
197
198 KnownOne2.clear();
199 KnownZero2.clear();
200 ComputeMaskedBits(I->getOperand(1),
201 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
202 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
203 if (RHSUnknownLeadingOnes != BitWidth)
204 LeadZ = std::min(BitWidth,
205 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
206
207 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
208 return;
209 }
210 case Instruction::Select:
211 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
212 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
213 Depth+1);
214 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
215 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
216
217 // Only known if known in both the LHS and RHS.
218 KnownOne &= KnownOne2;
219 KnownZero &= KnownZero2;
220 return;
221 case Instruction::FPTrunc:
222 case Instruction::FPExt:
223 case Instruction::FPToUI:
224 case Instruction::FPToSI:
225 case Instruction::SIToFP:
226 case Instruction::UIToFP:
227 return; // Can't work with floating point.
228 case Instruction::PtrToInt:
229 case Instruction::IntToPtr:
230 // We can't handle these if we don't know the pointer size.
231 if (!TD) return;
232 // FALL THROUGH and handle them the same as zext/trunc.
233 case Instruction::ZExt:
234 case Instruction::Trunc: {
235 // Note that we handle pointer operands here because of inttoptr/ptrtoint
236 // which fall through here.
237 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner79abedb2009-01-20 18:22:57 +0000238 unsigned SrcBitWidth = TD ?
Chris Lattner173234a2008-06-02 01:18:21 +0000239 TD->getTypeSizeInBits(SrcTy) :
Dan Gohman6de29f82009-06-15 22:12:54 +0000240 SrcTy->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000241 APInt MaskIn(Mask);
242 MaskIn.zextOrTrunc(SrcBitWidth);
243 KnownZero.zextOrTrunc(SrcBitWidth);
244 KnownOne.zextOrTrunc(SrcBitWidth);
245 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
246 Depth+1);
247 KnownZero.zextOrTrunc(BitWidth);
248 KnownOne.zextOrTrunc(BitWidth);
249 // Any top bits are known to be zero.
250 if (BitWidth > SrcBitWidth)
251 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
252 return;
253 }
254 case Instruction::BitCast: {
255 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000256 if ((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
257 // TODO: For now, not handling conversions like:
258 // (bitcast i64 %x to <2 x i32>)
259 !isa<VectorType>(I->getType())) {
Chris Lattner173234a2008-06-02 01:18:21 +0000260 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
261 Depth+1);
262 return;
263 }
264 break;
265 }
266 case Instruction::SExt: {
267 // Compute the bits in the result that are not present in the input.
268 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Chris Lattner79abedb2009-01-20 18:22:57 +0000269 unsigned SrcBitWidth = SrcTy->getBitWidth();
Chris Lattner173234a2008-06-02 01:18:21 +0000270
271 APInt MaskIn(Mask);
272 MaskIn.trunc(SrcBitWidth);
273 KnownZero.trunc(SrcBitWidth);
274 KnownOne.trunc(SrcBitWidth);
275 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
276 Depth+1);
277 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
278 KnownZero.zext(BitWidth);
279 KnownOne.zext(BitWidth);
280
281 // If the sign bit of the input is known set or clear, then we know the
282 // top bits of the result.
283 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
284 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
285 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
286 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
287 return;
288 }
289 case Instruction::Shl:
290 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
292 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
293 APInt Mask2(Mask.lshr(ShiftAmt));
294 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
295 Depth+1);
296 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
297 KnownZero <<= ShiftAmt;
298 KnownOne <<= ShiftAmt;
299 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
300 return;
301 }
302 break;
303 case Instruction::LShr:
304 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
305 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
306 // Compute the new bits that are at the top now.
307 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
308
309 // Unsigned shift right.
310 APInt Mask2(Mask.shl(ShiftAmt));
311 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
312 Depth+1);
313 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
314 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
315 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
316 // high bits known zero.
317 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
318 return;
319 }
320 break;
321 case Instruction::AShr:
322 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
323 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
324 // Compute the new bits that are at the top now.
325 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
326
327 // Signed shift right.
328 APInt Mask2(Mask.shl(ShiftAmt));
329 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
330 Depth+1);
331 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
332 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
333 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
334
335 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
336 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
337 KnownZero |= HighBits;
338 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
339 KnownOne |= HighBits;
340 return;
341 }
342 break;
343 case Instruction::Sub: {
344 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
345 // We know that the top bits of C-X are clear if X contains less bits
346 // than C (i.e. no wrap-around can happen). For example, 20-X is
347 // positive if we can prove that X is >= 0 and < 16.
348 if (!CLHS->getValue().isNegative()) {
349 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
350 // NLZ can't be BitWidth with no sign bit
351 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
352 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
353 TD, Depth+1);
354
355 // If all of the MaskV bits are known to be zero, then we know the
356 // output top bits are zero, because we now know that the output is
357 // from [0-C].
358 if ((KnownZero2 & MaskV) == MaskV) {
359 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
360 // Top bits known zero.
361 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
362 }
363 }
364 }
365 }
366 // fall through
367 case Instruction::Add: {
Dan Gohman39250432009-05-24 18:02:35 +0000368 // If one of the operands has trailing zeros, than the bits that the
369 // other operand has in those bit positions will be preserved in the
370 // result. For an add, this works with either operand. For a subtract,
371 // this only works if the known zeros are in the right operand.
372 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
373 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
374 BitWidth - Mask.countLeadingZeros());
375 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000376 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000377 assert((LHSKnownZero & LHSKnownOne) == 0 &&
378 "Bits known to be one AND zero?");
379 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000380
381 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
382 Depth+1);
383 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000384 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000385
Dan Gohman39250432009-05-24 18:02:35 +0000386 // Determine which operand has more trailing zeros, and use that
387 // many bits from the other operand.
388 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000389 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000390 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
391 KnownZero |= KnownZero2 & Mask;
392 KnownOne |= KnownOne2 & Mask;
393 } else {
394 // If the known zeros are in the left operand for a subtract,
395 // fall back to the minimum known zeros in both operands.
396 KnownZero |= APInt::getLowBitsSet(BitWidth,
397 std::min(LHSKnownZeroOut,
398 RHSKnownZeroOut));
399 }
400 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
401 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
402 KnownZero |= LHSKnownZero & Mask;
403 KnownOne |= LHSKnownOne & Mask;
404 }
Chris Lattner173234a2008-06-02 01:18:21 +0000405 return;
406 }
407 case Instruction::SRem:
408 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
409 APInt RA = Rem->getValue();
410 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
411 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
412 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
413 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
414 Depth+1);
415
Dan Gohmana60832b2008-08-13 23:12:35 +0000416 // If the sign bit of the first operand is zero, the sign bit of
417 // the result is zero. If the first operand has no one bits below
418 // the second operand's single 1 bit, its sign will be zero.
Chris Lattner173234a2008-06-02 01:18:21 +0000419 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
420 KnownZero2 |= ~LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000421
422 KnownZero |= KnownZero2 & Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000423
424 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
425 }
426 }
427 break;
428 case Instruction::URem: {
429 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
430 APInt RA = Rem->getValue();
431 if (RA.isPowerOf2()) {
432 APInt LowBits = (RA - 1);
433 APInt Mask2 = LowBits & Mask;
434 KnownZero |= ~LowBits & Mask;
435 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
436 Depth+1);
437 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
438 break;
439 }
440 }
441
442 // Since the result is less than or equal to either operand, any leading
443 // zero bits in either operand must also exist in the result.
444 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
445 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
446 TD, Depth+1);
447 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
448 TD, Depth+1);
449
Chris Lattner79abedb2009-01-20 18:22:57 +0000450 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000451 KnownZero2.countLeadingOnes());
452 KnownOne.clear();
453 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
454 break;
455 }
456
457 case Instruction::Alloca:
458 case Instruction::Malloc: {
459 AllocationInst *AI = cast<AllocationInst>(V);
460 unsigned Align = AI->getAlignment();
461 if (Align == 0 && TD) {
462 if (isa<AllocaInst>(AI))
Chris Lattner0f2831c2009-01-08 19:28:38 +0000463 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000464 else if (isa<MallocInst>(AI)) {
465 // Malloc returns maximally aligned memory.
466 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
467 Align =
468 std::max(Align,
Owen Anderson1d0be152009-08-13 21:58:54 +0000469 (unsigned)TD->getABITypeAlignment(
470 Type::getDoubleTy(V->getContext())));
Chris Lattner173234a2008-06-02 01:18:21 +0000471 Align =
472 std::max(Align,
Owen Anderson1d0be152009-08-13 21:58:54 +0000473 (unsigned)TD->getABITypeAlignment(
474 Type::getInt64Ty(V->getContext())));
Chris Lattner173234a2008-06-02 01:18:21 +0000475 }
476 }
477
478 if (Align > 0)
479 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
480 CountTrailingZeros_32(Align));
481 break;
482 }
483 case Instruction::GetElementPtr: {
484 // Analyze all of the subscripts of this getelementptr instruction
485 // to determine if we can prove known low zero bits.
486 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
487 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
488 ComputeMaskedBits(I->getOperand(0), LocalMask,
489 LocalKnownZero, LocalKnownOne, TD, Depth+1);
490 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
491
492 gep_type_iterator GTI = gep_type_begin(I);
493 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
494 Value *Index = I->getOperand(i);
495 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
496 // Handle struct member offset arithmetic.
497 if (!TD) return;
498 const StructLayout *SL = TD->getStructLayout(STy);
499 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
500 uint64_t Offset = SL->getElementOffset(Idx);
501 TrailZ = std::min(TrailZ,
502 CountTrailingZeros_64(Offset));
503 } else {
504 // Handle array index arithmetic.
505 const Type *IndexedTy = GTI.getIndexedType();
506 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000507 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000508 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000509 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
510 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
511 ComputeMaskedBits(Index, LocalMask,
512 LocalKnownZero, LocalKnownOne, TD, Depth+1);
513 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000514 unsigned(CountTrailingZeros_64(TypeSize) +
515 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000516 }
517 }
518
519 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
520 break;
521 }
522 case Instruction::PHI: {
523 PHINode *P = cast<PHINode>(I);
524 // Handle the case of a simple two-predecessor recurrence PHI.
525 // There's a lot more that could theoretically be done here, but
526 // this is sufficient to catch some interesting cases.
527 if (P->getNumIncomingValues() == 2) {
528 for (unsigned i = 0; i != 2; ++i) {
529 Value *L = P->getIncomingValue(i);
530 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000531 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000532 if (!LU)
533 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000534 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000535 // Check for operations that have the property that if
536 // both their operands have low zero bits, the result
537 // will have low zero bits.
538 if (Opcode == Instruction::Add ||
539 Opcode == Instruction::Sub ||
540 Opcode == Instruction::And ||
541 Opcode == Instruction::Or ||
542 Opcode == Instruction::Mul) {
543 Value *LL = LU->getOperand(0);
544 Value *LR = LU->getOperand(1);
545 // Find a recurrence.
546 if (LL == I)
547 L = LR;
548 else if (LR == I)
549 L = LL;
550 else
551 break;
552 // Ok, we have a PHI of the form L op= R. Check for low
553 // zero bits.
554 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
555 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
556 Mask2 = APInt::getLowBitsSet(BitWidth,
557 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000558
559 // We need to take the minimum number of known bits
560 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
561 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
562
Chris Lattner173234a2008-06-02 01:18:21 +0000563 KnownZero = Mask &
564 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000565 std::min(KnownZero2.countTrailingOnes(),
566 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000567 break;
568 }
569 }
570 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000571
572 // Otherwise take the unions of the known bit sets of the operands,
573 // taking conservative care to avoid excessive recursion.
574 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
575 KnownZero = APInt::getAllOnesValue(BitWidth);
576 KnownOne = APInt::getAllOnesValue(BitWidth);
577 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
578 // Skip direct self references.
579 if (P->getIncomingValue(i) == P) continue;
580
581 KnownZero2 = APInt(BitWidth, 0);
582 KnownOne2 = APInt(BitWidth, 0);
583 // Recurse, but cap the recursion to one level, because we don't
584 // want to waste time spinning around in loops.
585 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
586 KnownZero2, KnownOne2, TD, MaxDepth-1);
587 KnownZero &= KnownZero2;
588 KnownOne &= KnownOne2;
589 // If all bits have been ruled out, there's no need to check
590 // more operands.
591 if (!KnownZero && !KnownOne)
592 break;
593 }
594 }
Chris Lattner173234a2008-06-02 01:18:21 +0000595 break;
596 }
597 case Instruction::Call:
598 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
599 switch (II->getIntrinsicID()) {
600 default: break;
601 case Intrinsic::ctpop:
602 case Intrinsic::ctlz:
603 case Intrinsic::cttz: {
604 unsigned LowBits = Log2_32(BitWidth)+1;
605 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
606 break;
607 }
608 }
609 }
610 break;
611 }
612}
613
614/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
615/// this predicate to simplify operations downstream. Mask is known to be zero
616/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000617///
618/// This function is defined on values with integer type, values with pointer
619/// type (but only if TD is non-null), and vectors of integers. In the case
620/// where V is a vector, the mask, known zero, and known one values are the
621/// same width as the vector element, and the bit is set only if it is true
622/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000623bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000624 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000625 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
626 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
628 return (KnownZero & Mask) == Mask;
629}
630
631
632
633/// ComputeNumSignBits - Return the number of times the sign bit of the
634/// register is replicated into the other bits. We know that at least 1 bit
635/// is always equal to the sign bit (itself), but other cases can give us
636/// information. For example, immediately after an "ashr X, 2", we know that
637/// the top 3 bits are all equal to each other, so we return 3.
638///
639/// 'Op' must have a scalar integer type.
640///
Dan Gohman846a2f22009-08-27 17:51:25 +0000641unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
642 unsigned Depth) {
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000643 assert((TD || V->getType()->isIntOrIntVector()) &&
644 "ComputeNumSignBits requires a TargetData object to operate "
645 "on non-integer values!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000646 const Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000647 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
648 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000649 unsigned Tmp, Tmp2;
650 unsigned FirstAnswer = 1;
651
Chris Lattnerd82e5112008-06-02 18:39:07 +0000652 // Note that ConstantInt is handled by the general ComputeMaskedBits case
653 // below.
654
Chris Lattner173234a2008-06-02 01:18:21 +0000655 if (Depth == 6)
656 return 1; // Limit search depth.
657
Dan Gohmanca178902009-07-17 20:47:02 +0000658 Operator *U = dyn_cast<Operator>(V);
659 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000660 default: break;
661 case Instruction::SExt:
662 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
663 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
664
665 case Instruction::AShr:
666 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
667 // ashr X, C -> adds C sign bits.
668 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
669 Tmp += C->getZExtValue();
670 if (Tmp > TyBits) Tmp = TyBits;
671 }
672 return Tmp;
673 case Instruction::Shl:
674 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
675 // shl destroys sign bits.
676 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
677 if (C->getZExtValue() >= TyBits || // Bad shift.
678 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
679 return Tmp - C->getZExtValue();
680 }
681 break;
682 case Instruction::And:
683 case Instruction::Or:
684 case Instruction::Xor: // NOT is handled here.
685 // Logical binary ops preserve the number of sign bits at the worst.
686 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
687 if (Tmp != 1) {
688 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
689 FirstAnswer = std::min(Tmp, Tmp2);
690 // We computed what we know about the sign bits as our first
691 // answer. Now proceed to the generic code that uses
692 // ComputeMaskedBits, and pick whichever answer is better.
693 }
694 break;
695
696 case Instruction::Select:
697 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
698 if (Tmp == 1) return 1; // Early out.
699 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
700 return std::min(Tmp, Tmp2);
701
702 case Instruction::Add:
703 // Add can have at most one carry bit. Thus we know that the output
704 // is, at worst, one more bit than the inputs.
705 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
706 if (Tmp == 1) return 1; // Early out.
707
708 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +0000709 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +0000710 if (CRHS->isAllOnesValue()) {
711 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
712 APInt Mask = APInt::getAllOnesValue(TyBits);
713 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
714 Depth+1);
715
716 // If the input is known to be 0 or 1, the output is 0/-1, which is all
717 // sign bits set.
718 if ((KnownZero | APInt(TyBits, 1)) == Mask)
719 return TyBits;
720
721 // If we are subtracting one from a positive number, there is no carry
722 // out of the result.
723 if (KnownZero.isNegative())
724 return Tmp;
725 }
726
727 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
728 if (Tmp2 == 1) return 1;
729 return std::min(Tmp, Tmp2)-1;
730 break;
731
732 case Instruction::Sub:
733 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
734 if (Tmp2 == 1) return 1;
735
736 // Handle NEG.
737 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
738 if (CLHS->isNullValue()) {
739 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
740 APInt Mask = APInt::getAllOnesValue(TyBits);
741 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
742 TD, Depth+1);
743 // If the input is known to be 0 or 1, the output is 0/-1, which is all
744 // sign bits set.
745 if ((KnownZero | APInt(TyBits, 1)) == Mask)
746 return TyBits;
747
748 // If the input is known to be positive (the sign bit is known clear),
749 // the output of the NEG has the same number of sign bits as the input.
750 if (KnownZero.isNegative())
751 return Tmp2;
752
753 // Otherwise, we treat this like a SUB.
754 }
755
756 // Sub can have at most one carry bit. Thus we know that the output
757 // is, at worst, one more bit than the inputs.
758 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
759 if (Tmp == 1) return 1; // Early out.
760 return std::min(Tmp, Tmp2)-1;
761 break;
762 case Instruction::Trunc:
763 // FIXME: it's tricky to do anything useful for this, but it is an important
764 // case for targets like X86.
765 break;
766 }
767
768 // Finally, if we can prove that the top bits of the result are 0's or 1's,
769 // use this information.
770 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
771 APInt Mask = APInt::getAllOnesValue(TyBits);
772 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
773
774 if (KnownZero.isNegative()) { // sign bit is 0
775 Mask = KnownZero;
776 } else if (KnownOne.isNegative()) { // sign bit is 1;
777 Mask = KnownOne;
778 } else {
779 // Nothing known.
780 return FirstAnswer;
781 }
782
783 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
784 // the number of identical bits in the top of the input value.
785 Mask = ~Mask;
786 Mask <<= Mask.getBitWidth()-TyBits;
787 // Return # leading zeros. We use 'min' here in case Val was zero before
788 // shifting. We don't want to return '64' as for an i32 "0".
789 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
790}
Chris Lattner833f25d2008-06-02 01:29:46 +0000791
792/// CannotBeNegativeZero - Return true if we can prove that the specified FP
793/// value is never equal to -0.0.
794///
795/// NOTE: this function will need to be revisited when we support non-default
796/// rounding modes!
797///
798bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
799 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
800 return !CFP->getValueAPF().isNegZero();
801
802 if (Depth == 6)
803 return 1; // Limit search depth.
804
Dan Gohmanca178902009-07-17 20:47:02 +0000805 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +0000806 if (I == 0) return false;
807
808 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000809 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +0000810 isa<ConstantFP>(I->getOperand(1)) &&
811 cast<ConstantFP>(I->getOperand(1))->isNullValue())
812 return true;
813
814 // sitofp and uitofp turn into +0.0 for zero.
815 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
816 return true;
817
818 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
819 // sqrt(-0.0) = -0.0, no other negative results are possible.
820 if (II->getIntrinsicID() == Intrinsic::sqrt)
821 return CannotBeNegativeZero(II->getOperand(1), Depth+1);
822
823 if (const CallInst *CI = dyn_cast<CallInst>(I))
824 if (const Function *F = CI->getCalledFunction()) {
825 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000826 // abs(x) != -0.0
827 if (F->getName() == "abs") return true;
828 // abs[lf](x) != -0.0
829 if (F->getName() == "absf") return true;
830 if (F->getName() == "absl") return true;
Chris Lattner833f25d2008-06-02 01:29:46 +0000831 }
832 }
833
834 return false;
835}
836
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000837// This is the recursive version of BuildSubAggregate. It takes a few different
838// arguments. Idxs is the index within the nested struct From that we are
839// looking at now (which is of type IndexedType). IdxSkip is the number of
840// indices from Idxs that should be left out when inserting into the resulting
841// struct. To is the result struct built so far, new insertvalue instructions
842// build on that.
Dan Gohman7db949d2009-08-07 01:32:21 +0000843static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
844 SmallVector<unsigned, 10> &Idxs,
845 unsigned IdxSkip,
846 LLVMContext &Context,
847 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000848 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
849 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000850 // Save the original To argument so we can modify it
851 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000852 // General case, the type indexed by Idxs is a struct
853 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
854 // Process each struct element recursively
855 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000856 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000857 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Owen Anderson76f600b2009-07-06 22:37:39 +0000858 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000859 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000860 if (!To) {
861 // Couldn't find any inserted value for this index? Cleanup
862 while (PrevTo != OrigTo) {
863 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
864 PrevTo = Del->getAggregateOperand();
865 Del->eraseFromParent();
866 }
867 // Stop processing elements
868 break;
869 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000870 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000871 // If we succesfully found a value for each of our subaggregates
872 if (To)
873 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000874 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000875 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
876 // the struct's elements had a value that was inserted directly. In the latter
877 // case, perhaps we can't determine each of the subelements individually, but
878 // we might be able to find the complete struct somewhere.
879
880 // Find the value that is at that particular spot
Owen Anderson76f600b2009-07-06 22:37:39 +0000881 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end(), Context);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000882
883 if (!V)
884 return NULL;
885
886 // Insert the value in the new (sub) aggregrate
887 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
888 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000889}
890
891// This helper takes a nested struct and extracts a part of it (which is again a
892// struct) into a new value. For example, given the struct:
893// { a, { b, { c, d }, e } }
894// and the indices "1, 1" this returns
895// { c, d }.
896//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000897// It does this by inserting an insertvalue for each element in the resulting
898// struct, as opposed to just inserting a single struct. This will only work if
899// each of the elements of the substruct are known (ie, inserted into From by an
900// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000901//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000902// All inserted insertvalue instructions are inserted before InsertBefore
Dan Gohman7db949d2009-08-07 01:32:21 +0000903static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
904 const unsigned *idx_end, LLVMContext &Context,
905 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000906 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000907 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
908 idx_begin,
909 idx_end);
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000910 Value *To = UndefValue::get(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000911 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
912 unsigned IdxSkip = Idxs.size();
913
Owen Anderson76f600b2009-07-06 22:37:39 +0000914 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip,
915 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000916}
917
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000918/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
919/// the scalar value indexed is already around as a register, for example if it
920/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000921///
922/// If InsertBefore is not null, this function will duplicate (modified)
923/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000924Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Owen Andersone922c022009-07-22 00:24:57 +0000925 const unsigned *idx_end, LLVMContext &Context,
Owen Anderson76f600b2009-07-06 22:37:39 +0000926 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000927 // Nothing to index? Just return V then (this is useful at the end of our
928 // recursion)
929 if (idx_begin == idx_end)
930 return V;
931 // We have indices, so V should have an indexable type
932 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
933 && "Not looking at a struct or array?");
934 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
935 && "Invalid indices for type?");
936 const CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +0000937
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000938 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000939 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000940 idx_begin,
941 idx_end));
942 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +0000943 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Owen Anderson76f600b2009-07-06 22:37:39 +0000944 idx_begin,
945 idx_end));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000946 else if (Constant *C = dyn_cast<Constant>(V)) {
947 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
948 // Recursively process this constant
Owen Anderson76f600b2009-07-06 22:37:39 +0000949 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
950 idx_end, Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000951 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
952 // Loop the indices for the insertvalue instruction in parallel with the
953 // requested indices
954 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000955 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
956 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +0000957 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000958 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000959 // The requested index identifies a part of a nested aggregate. Handle
960 // this specially. For example,
961 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
962 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
963 // %C = extractvalue {i32, { i32, i32 } } %B, 1
964 // This can be changed into
965 // %A = insertvalue {i32, i32 } undef, i32 10, 0
966 // %C = insertvalue {i32, i32 } %A, i32 11, 1
967 // which allows the unused 0,0 element from the nested struct to be
968 // removed.
Owen Anderson76f600b2009-07-06 22:37:39 +0000969 return BuildSubAggregate(V, idx_begin, req_idx,
970 Context, InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +0000971 else
972 // We can't handle this without inserting insertvalues
973 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +0000974 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000975
976 // This insert value inserts something else than what we are looking for.
977 // See if the (aggregrate) value inserted into has the value we are
978 // looking for, then.
979 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000980 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
Owen Anderson76f600b2009-07-06 22:37:39 +0000981 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000982 }
983 // If we end up here, the indices of the insertvalue match with those
984 // requested (though possibly only partially). Now we recursively look at
985 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000986 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
Owen Anderson76f600b2009-07-06 22:37:39 +0000987 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000988 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
989 // If we're extracting a value from an aggregrate that was extracted from
990 // something else, we can extract from that something else directly instead.
991 // However, we will need to chain I's indices with the requested indices.
992
993 // Calculate the number of indices required
994 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
995 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000996 SmallVector<unsigned, 5> Idxs;
997 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000998 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000999 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001000 i != e; ++i)
1001 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001002
1003 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001004 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1005 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001006
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001007 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001008 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001009
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001010 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Owen Anderson76f600b2009-07-06 22:37:39 +00001011 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001012 }
1013 // Otherwise, we don't know (such as, extracting from a function return value
1014 // or load instruction)
1015 return 0;
1016}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001017
1018/// GetConstantStringInfo - This function computes the length of a
1019/// null-terminated C string pointed to by V. If successful, it returns true
1020/// and returns the string in Str. If unsuccessful, it returns false.
Bill Wendling0582ae92009-03-13 04:39:26 +00001021bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
1022 bool StopAtNul) {
1023 // If V is NULL then return false;
1024 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001025
1026 // Look through bitcast instructions.
1027 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001028 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1029
Evan Cheng0ff39b32008-06-30 07:31:25 +00001030 // If the value is not a GEP instruction nor a constant expression with a
1031 // GEP instruction, then return false because ConstantArray can't occur
1032 // any other way
1033 User *GEP = 0;
1034 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1035 GEP = GEPI;
1036 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1037 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001038 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1039 if (CE->getOpcode() != Instruction::GetElementPtr)
1040 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001041 GEP = CE;
1042 }
1043
1044 if (GEP) {
1045 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001046 if (GEP->getNumOperands() != 3)
1047 return false;
1048
Evan Cheng0ff39b32008-06-30 07:31:25 +00001049 // Make sure the index-ee is a pointer to array of i8.
1050 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1051 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001052 if (AT == 0 || AT->getElementType() != Type::getInt8Ty(V->getContext()))
Bill Wendling0582ae92009-03-13 04:39:26 +00001053 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001054
1055 // Check to make sure that the first operand of the GEP is an integer and
1056 // has value 0 so that we are sure we're indexing into the initializer.
1057 ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001058 if (FirstIdx == 0 || !FirstIdx->isZero())
1059 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001060
1061 // If the second index isn't a ConstantInt, then this is a variable index
1062 // into the array. If this occurs, we can't say anything meaningful about
1063 // the string.
1064 uint64_t StartIdx = 0;
Bill Wendling0582ae92009-03-13 04:39:26 +00001065 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001066 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001067 else
1068 return false;
1069 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001070 StopAtNul);
1071 }
1072
Torok Edwin148843b2009-09-02 11:13:56 +00001073 if (MDString *MDStr = dyn_cast<MDString>(V)) {
1074 Str = MDStr->getString();
1075 return true;
1076 }
1077
Evan Cheng0ff39b32008-06-30 07:31:25 +00001078 // The GEP instruction, constant or instruction, must reference a global
1079 // variable that is a constant and is initialized. The referenced constant
1080 // initializer is the array that we'll use for optimization.
1081 GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001082 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001083 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001084 Constant *GlobalInit = GV->getInitializer();
1085
1086 // Handle the ConstantAggregateZero case
Bill Wendling0582ae92009-03-13 04:39:26 +00001087 if (isa<ConstantAggregateZero>(GlobalInit)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001088 // This is a degenerate case. The initializer is constant zero so the
1089 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001090 Str.clear();
1091 return true;
1092 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001093
1094 // Must be a Constant Array
1095 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Owen Anderson1d0be152009-08-13 21:58:54 +00001096 if (Array == 0 ||
1097 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
Bill Wendling0582ae92009-03-13 04:39:26 +00001098 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001099
1100 // Get the number of elements in the array
1101 uint64_t NumElts = Array->getType()->getNumElements();
1102
Bill Wendling0582ae92009-03-13 04:39:26 +00001103 if (Offset > NumElts)
1104 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001105
1106 // Traverse the constant array from 'Offset' which is the place the GEP refers
1107 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001108 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001109 for (unsigned i = Offset; i != NumElts; ++i) {
1110 Constant *Elt = Array->getOperand(i);
1111 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001112 if (!CI) // This array isn't suitable, non-int initializer.
1113 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001114 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001115 return true; // we found end of string, success!
1116 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001117 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001118
Evan Cheng0ff39b32008-06-30 07:31:25 +00001119 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001120 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001121}