blob: 17bad941e50a2f0fbd44e5c5d452a60464ae73b7 [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"
Dan Gohman24371272010-12-15 20:10:26 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner173234a2008-06-02 01:18:21 +000017#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000019#include "llvm/GlobalVariable.h"
Dan Gohman307a7c42009-09-15 16:14:44 +000020#include "llvm/GlobalAlias.h"
Chris Lattner173234a2008-06-02 01:18:21 +000021#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000022#include "llvm/LLVMContext.h"
Rafael Espindola7c7121e2012-03-30 15:52:11 +000023#include "llvm/Metadata.h"
Dan Gohmanca178902009-07-17 20:47:02 +000024#include "llvm/Operator.h"
Bill Wendling0582ae92009-03-13 04:39:26 +000025#include "llvm/Target/TargetData.h"
Rafael Espindola7c7121e2012-03-30 15:52:11 +000026#include "llvm/Support/ConstantRange.h"
Chris Lattner173234a2008-06-02 01:18:21 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
28#include "llvm/Support/MathExtras.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000029#include "llvm/Support/PatternMatch.h"
Eric Christopher25ec4832010-03-05 06:58:57 +000030#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000031#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000032using namespace llvm;
Duncan Sandsd70d1a52011-01-25 09:38:29 +000033using namespace llvm::PatternMatch;
34
35const unsigned MaxDepth = 6;
36
37/// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
38/// unknown returns 0). For vector types, returns the element type's bitwidth.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000039static unsigned getBitWidth(Type *Ty, const TargetData *TD) {
Duncan Sandsd70d1a52011-01-25 09:38:29 +000040 if (unsigned BitWidth = Ty->getScalarSizeInBits())
41 return BitWidth;
42 assert(isa<PointerType>(Ty) && "Expected a pointer type!");
43 return TD ? TD->getPointerSizeInBits() : 0;
44}
Chris Lattner173234a2008-06-02 01:18:21 +000045
Nick Lewycky00cbccc2012-03-09 09:23:50 +000046static void ComputeMaskedBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
47 const APInt &Mask,
48 APInt &KnownZero, APInt &KnownOne,
49 APInt &KnownZero2, APInt &KnownOne2,
50 const TargetData *TD, unsigned Depth) {
51 if (!Add) {
52 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
53 // We know that the top bits of C-X are clear if X contains less bits
54 // than C (i.e. no wrap-around can happen). For example, 20-X is
55 // positive if we can prove that X is >= 0 and < 16.
56 if (!CLHS->getValue().isNegative()) {
57 unsigned BitWidth = Mask.getBitWidth();
58 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
59 // NLZ can't be BitWidth with no sign bit
60 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
61 llvm::ComputeMaskedBits(Op1, MaskV, KnownZero2, KnownOne2, TD, Depth+1);
62
63 // If all of the MaskV bits are known to be zero, then we know the
64 // output top bits are zero, because we now know that the output is
65 // from [0-C].
66 if ((KnownZero2 & MaskV) == MaskV) {
67 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
68 // Top bits known zero.
69 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
70 }
71 }
72 }
73 }
74
75 unsigned BitWidth = Mask.getBitWidth();
76
77 // If one of the operands has trailing zeros, then the bits that the
78 // other operand has in those bit positions will be preserved in the
79 // result. For an add, this works with either operand. For a subtract,
80 // this only works if the known zeros are in the right operand.
81 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
82 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
83 BitWidth - Mask.countLeadingZeros());
84 llvm::ComputeMaskedBits(Op0, Mask2, LHSKnownZero, LHSKnownOne, TD, Depth+1);
85 assert((LHSKnownZero & LHSKnownOne) == 0 &&
86 "Bits known to be one AND zero?");
87 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
88
89 llvm::ComputeMaskedBits(Op1, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
90 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
91 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
92
93 // Determine which operand has more trailing zeros, and use that
94 // many bits from the other operand.
95 if (LHSKnownZeroOut > RHSKnownZeroOut) {
96 if (Add) {
97 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
98 KnownZero |= KnownZero2 & Mask;
99 KnownOne |= KnownOne2 & Mask;
100 } else {
101 // If the known zeros are in the left operand for a subtract,
102 // fall back to the minimum known zeros in both operands.
103 KnownZero |= APInt::getLowBitsSet(BitWidth,
104 std::min(LHSKnownZeroOut,
105 RHSKnownZeroOut));
106 }
107 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
108 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
109 KnownZero |= LHSKnownZero & Mask;
110 KnownOne |= LHSKnownOne & Mask;
111 }
112
113 // Are we still trying to solve for the sign bit?
114 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()) {
115 if (NSW) {
116 if (Add) {
117 // Adding two positive numbers can't wrap into negative
118 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
119 KnownZero |= APInt::getSignBit(BitWidth);
120 // and adding two negative numbers can't wrap into positive.
121 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
122 KnownOne |= APInt::getSignBit(BitWidth);
123 } else {
124 // Subtracting a negative number from a positive one can't wrap
125 if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
126 KnownZero |= APInt::getSignBit(BitWidth);
127 // neither can subtracting a positive number from a negative one.
128 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
129 KnownOne |= APInt::getSignBit(BitWidth);
130 }
131 }
132 }
133}
134
Nick Lewyckyf201a062012-03-18 23:28:48 +0000135static void ComputeMaskedBitsMul(Value *Op0, Value *Op1, bool NSW,
136 const APInt &Mask,
137 APInt &KnownZero, APInt &KnownOne,
138 APInt &KnownZero2, APInt &KnownOne2,
139 const TargetData *TD, unsigned Depth) {
140 unsigned BitWidth = Mask.getBitWidth();
141 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
142 ComputeMaskedBits(Op1, Mask2, KnownZero, KnownOne, TD, Depth+1);
143 ComputeMaskedBits(Op0, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
144 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
145 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
146
147 bool isKnownNegative = false;
148 bool isKnownNonNegative = false;
149 // If the multiplication is known not to overflow, compute the sign bit.
150 if (Mask.isNegative() && NSW) {
151 if (Op0 == Op1) {
152 // The product of a number with itself is non-negative.
153 isKnownNonNegative = true;
154 } else {
155 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
156 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
157 bool isKnownNegativeOp1 = KnownOne.isNegative();
158 bool isKnownNegativeOp0 = KnownOne2.isNegative();
159 // The product of two numbers with the same sign is non-negative.
160 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
161 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
162 // The product of a negative number and a non-negative number is either
163 // negative or zero.
164 if (!isKnownNonNegative)
165 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
166 isKnownNonZero(Op0, TD, Depth)) ||
167 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
168 isKnownNonZero(Op1, TD, Depth));
169 }
170 }
171
172 // If low bits are zero in either operand, output low known-0 bits.
173 // Also compute a conserative estimate for high known-0 bits.
174 // More trickiness is possible, but this is sufficient for the
175 // interesting case of alignment computation.
176 KnownOne.clearAllBits();
177 unsigned TrailZ = KnownZero.countTrailingOnes() +
178 KnownZero2.countTrailingOnes();
179 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
180 KnownZero2.countLeadingOnes(),
181 BitWidth) - BitWidth;
182
183 TrailZ = std::min(TrailZ, BitWidth);
184 LeadZ = std::min(LeadZ, BitWidth);
185 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
186 APInt::getHighBitsSet(BitWidth, LeadZ);
187 KnownZero &= Mask;
188
189 // Only make use of no-wrap flags if we failed to compute the sign bit
190 // directly. This matters if the multiplication always overflows, in
191 // which case we prefer to follow the result of the direct computation,
192 // though as the program is invoking undefined behaviour we can choose
193 // whatever we like here.
194 if (isKnownNonNegative && !KnownOne.isNegative())
195 KnownZero.setBit(BitWidth - 1);
196 else if (isKnownNegative && !KnownZero.isNegative())
197 KnownOne.setBit(BitWidth - 1);
198}
199
Rafael Espindola7c7121e2012-03-30 15:52:11 +0000200static void computeMaskedBitsLoad(const MDNode &Ranges, const APInt &Mask,
201 APInt &KnownZero) {
202 unsigned BitWidth = Mask.getBitWidth();
203 unsigned NumRanges = Ranges.getNumOperands() / 2;
204 assert(NumRanges >= 1);
205
206 // Use the high end of the ranges to find leading zeros.
207 unsigned MinLeadingZeros = BitWidth;
208 for (unsigned i = 0; i < NumRanges; ++i) {
209 ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
210 ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
211 ConstantRange Range(Lower->getValue(), Upper->getValue());
212 if (Range.isWrappedSet())
213 MinLeadingZeros = 0; // -1 has no zeros
214 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
215 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
216 }
217
218 KnownZero = Mask & APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
219}
Chris Lattner173234a2008-06-02 01:18:21 +0000220/// ComputeMaskedBits - Determine which of the bits specified in Mask are
221/// known to be either zero or one and return them in the KnownZero/KnownOne
222/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
223/// processing.
224/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
225/// we cannot optimize based on the assumption that it is zero without changing
226/// it to be an explicit zero. If we don't change it to zero, other code could
227/// optimized based on the contradictory assumption that it is non-zero.
228/// Because instcombine aggressively folds operations with undef args anyway,
229/// this won't lose us code quality.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000230///
231/// This function is defined on values with integer type, values with pointer
232/// type (but only if TD is non-null), and vectors of integers. In the case
233/// where V is a vector, the mask, known zero, and known one values are the
234/// same width as the vector element, and the bit is set only if it is true
235/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000236void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
237 APInt &KnownZero, APInt &KnownOne,
Dan Gohman846a2f22009-08-27 17:51:25 +0000238 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000239 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +0000240 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +0000241 unsigned BitWidth = Mask.getBitWidth();
Nadav Rotem16087692011-12-05 06:29:09 +0000242 assert((V->getType()->isIntOrIntVectorTy() ||
243 V->getType()->getScalarType()->isPointerTy()) &&
244 "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000245 assert((!TD ||
246 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000247 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman6de29f82009-06-15 22:12:54 +0000248 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem16087692011-12-05 06:29:09 +0000249 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner173234a2008-06-02 01:18:21 +0000250 KnownOne.getBitWidth() == BitWidth &&
251 "V, Mask, KnownOne and KnownZero should have same BitWidth");
252
253 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
254 // We know all of the bits for a constant!
255 KnownOne = CI->getValue() & Mask;
256 KnownZero = ~KnownOne & Mask;
257 return;
258 }
Dan Gohman6de29f82009-06-15 22:12:54 +0000259 // Null and aggregate-zero are all-zeros.
260 if (isa<ConstantPointerNull>(V) ||
261 isa<ConstantAggregateZero>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000262 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000263 KnownZero = Mask;
264 return;
265 }
Dan Gohman6de29f82009-06-15 22:12:54 +0000266 // Handle a constant vector by taking the intersection of the known bits of
Chris Lattner7302d802012-02-06 21:56:39 +0000267 // each element. There is no real need to handle ConstantVector here, because
268 // we don't handle undef in any particularly useful way.
Chris Lattnerdf390282012-01-24 07:54:10 +0000269 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
270 // We know that CDS must be a vector of integers. Take the intersection of
271 // each element.
272 KnownZero.setAllBits(); KnownOne.setAllBits();
273 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner0f193b82012-01-25 01:27:20 +0000274 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerdf390282012-01-24 07:54:10 +0000275 Elt = CDS->getElementAsInteger(i);
276 KnownZero &= ~Elt;
277 KnownOne &= Elt;
278 }
279 return;
280 }
281
Chris Lattner173234a2008-06-02 01:18:21 +0000282 // The address of an aligned GlobalValue has trailing zeros.
283 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
284 unsigned Align = GV->getAlignment();
Nick Lewycky891495e2012-03-07 02:27:53 +0000285 if (Align == 0 && TD) {
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000286 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
287 Type *ObjectType = GVar->getType()->getElementType();
Nick Lewycky891495e2012-03-07 02:27:53 +0000288 if (ObjectType->isSized()) {
289 // If the object is defined in the current Module, we'll be giving
290 // it the preferred alignment. Otherwise, we have to assume that it
291 // may only have the minimum ABI alignment.
292 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
293 Align = TD->getPreferredAlignment(GVar);
294 else
295 Align = TD->getABITypeAlignment(ObjectType);
296 }
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000297 }
Dan Gohman00407252009-08-11 15:50:03 +0000298 }
Chris Lattner173234a2008-06-02 01:18:21 +0000299 if (Align > 0)
300 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
301 CountTrailingZeros_32(Align));
302 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000303 KnownZero.clearAllBits();
304 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000305 return;
306 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000307 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
308 // the bits of its aliasee.
309 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
310 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000311 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000312 } else {
313 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
314 TD, Depth+1);
315 }
316 return;
317 }
Chris Lattnerb3f06732011-05-23 00:03:39 +0000318
319 if (Argument *A = dyn_cast<Argument>(V)) {
320 // Get alignment information off byval arguments if specified in the IR.
321 if (A->hasByValAttr())
322 if (unsigned Align = A->getParamAlignment())
323 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
324 CountTrailingZeros_32(Align));
325 return;
326 }
Chris Lattner173234a2008-06-02 01:18:21 +0000327
Chris Lattnerb3f06732011-05-23 00:03:39 +0000328 // Start out not knowing anything.
329 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000330
Dan Gohman9004c8a2009-05-21 02:28:33 +0000331 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000332 return; // Limit search depth.
333
Dan Gohmanca178902009-07-17 20:47:02 +0000334 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000335 if (!I) return;
336
337 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000338 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000339 default: break;
Rafael Espindola7c7121e2012-03-30 15:52:11 +0000340 case Instruction::Load:
341 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
342 computeMaskedBitsLoad(*MD, Mask, KnownZero);
343 return;
Chris Lattner173234a2008-06-02 01:18:21 +0000344 case Instruction::And: {
345 // If either the LHS or the RHS are Zero, the result is zero.
346 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
347 APInt Mask2(Mask & ~KnownZero);
348 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
349 Depth+1);
350 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
351 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
352
353 // Output known-1 bits are only known if set in both the LHS & RHS.
354 KnownOne &= KnownOne2;
355 // Output known-0 are known to be clear if zero in either the LHS | RHS.
356 KnownZero |= KnownZero2;
357 return;
358 }
359 case Instruction::Or: {
360 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
361 APInt Mask2(Mask & ~KnownOne);
362 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
363 Depth+1);
364 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
365 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
366
367 // Output known-0 bits are only known if clear in both the LHS & RHS.
368 KnownZero &= KnownZero2;
369 // Output known-1 are known to be set if set in either the LHS | RHS.
370 KnownOne |= KnownOne2;
371 return;
372 }
373 case Instruction::Xor: {
374 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
375 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
376 Depth+1);
377 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
378 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
379
380 // Output known-0 bits are known if clear or set in both the LHS & RHS.
381 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
382 // Output known-1 are known to be set if set in only one of the LHS, RHS.
383 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
384 KnownZero = KnownZeroOut;
385 return;
386 }
387 case Instruction::Mul: {
Nick Lewyckyf201a062012-03-18 23:28:48 +0000388 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
389 ComputeMaskedBitsMul(I->getOperand(0), I->getOperand(1), NSW,
390 Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
391 TD, Depth);
392 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000393 }
394 case Instruction::UDiv: {
395 // For the purposes of computing leading zeros we can conservatively
396 // treat a udiv as a logical right shift by the power of 2 known to
397 // be less than the denominator.
398 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
399 ComputeMaskedBits(I->getOperand(0),
400 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
401 unsigned LeadZ = KnownZero2.countLeadingOnes();
402
Jay Foad7a874dd2010-12-01 08:53:58 +0000403 KnownOne2.clearAllBits();
404 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000405 ComputeMaskedBits(I->getOperand(1),
406 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
407 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
408 if (RHSUnknownLeadingOnes != BitWidth)
409 LeadZ = std::min(BitWidth,
410 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
411
412 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
413 return;
414 }
415 case Instruction::Select:
416 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
417 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
418 Depth+1);
419 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
420 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
421
422 // Only known if known in both the LHS and RHS.
423 KnownOne &= KnownOne2;
424 KnownZero &= KnownZero2;
425 return;
426 case Instruction::FPTrunc:
427 case Instruction::FPExt:
428 case Instruction::FPToUI:
429 case Instruction::FPToSI:
430 case Instruction::SIToFP:
431 case Instruction::UIToFP:
432 return; // Can't work with floating point.
433 case Instruction::PtrToInt:
434 case Instruction::IntToPtr:
435 // We can't handle these if we don't know the pointer size.
436 if (!TD) return;
437 // FALL THROUGH and handle them the same as zext/trunc.
438 case Instruction::ZExt:
439 case Instruction::Trunc: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000440 Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000441
442 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000443 // Note that we handle pointer operands here because of inttoptr/ptrtoint
444 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000445 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000446 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
447 else
448 SrcBitWidth = SrcTy->getScalarSizeInBits();
449
Jay Foad40f8f622010-12-07 08:25:19 +0000450 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
451 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
452 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000453 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
454 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000455 KnownZero = KnownZero.zextOrTrunc(BitWidth);
456 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000457 // Any top bits are known to be zero.
458 if (BitWidth > SrcBitWidth)
459 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
460 return;
461 }
462 case Instruction::BitCast: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000463 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000464 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000465 // TODO: For now, not handling conversions like:
466 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000467 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000468 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
469 Depth+1);
470 return;
471 }
472 break;
473 }
474 case Instruction::SExt: {
475 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000476 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000477
Jay Foad40f8f622010-12-07 08:25:19 +0000478 APInt MaskIn = Mask.trunc(SrcBitWidth);
479 KnownZero = KnownZero.trunc(SrcBitWidth);
480 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000481 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
482 Depth+1);
483 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000484 KnownZero = KnownZero.zext(BitWidth);
485 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000486
487 // If the sign bit of the input is known set or clear, then we know the
488 // top bits of the result.
489 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
490 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
491 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
492 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
493 return;
494 }
495 case Instruction::Shl:
496 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
497 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
498 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
499 APInt Mask2(Mask.lshr(ShiftAmt));
500 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
501 Depth+1);
502 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
503 KnownZero <<= ShiftAmt;
504 KnownOne <<= ShiftAmt;
505 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
506 return;
507 }
508 break;
509 case Instruction::LShr:
510 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
511 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
512 // Compute the new bits that are at the top now.
513 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
514
515 // Unsigned shift right.
516 APInt Mask2(Mask.shl(ShiftAmt));
517 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
518 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000519 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000520 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
521 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
522 // high bits known zero.
523 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
524 return;
525 }
526 break;
527 case Instruction::AShr:
528 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
529 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
530 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000531 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000532
533 // Signed shift right.
534 APInt Mask2(Mask.shl(ShiftAmt));
535 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
536 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000537 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000538 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
539 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
540
541 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
542 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
543 KnownZero |= HighBits;
544 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
545 KnownOne |= HighBits;
546 return;
547 }
548 break;
549 case Instruction::Sub: {
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000550 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
551 ComputeMaskedBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
552 Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
553 TD, Depth);
554 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000555 }
Chris Lattner173234a2008-06-02 01:18:21 +0000556 case Instruction::Add: {
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000557 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
558 ComputeMaskedBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
559 Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
560 TD, Depth);
561 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000562 }
563 case Instruction::SRem:
564 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000565 APInt RA = Rem->getValue().abs();
566 if (RA.isPowerOf2()) {
567 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000568 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
569 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
570 Depth+1);
571
Duncan Sandscfd54182010-01-29 06:18:37 +0000572 // The low bits of the first operand are unchanged by the srem.
573 KnownZero = KnownZero2 & LowBits;
574 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000575
Duncan Sandscfd54182010-01-29 06:18:37 +0000576 // If the first operand is non-negative or has all low bits zero, then
577 // the upper bits are all zero.
578 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
579 KnownZero |= ~LowBits;
580
581 // If the first operand is negative and not all low bits are zero, then
582 // the upper bits are all one.
583 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
584 KnownOne |= ~LowBits;
585
586 KnownZero &= Mask;
587 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000588
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000589 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000590 }
591 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000592
593 // The sign bit is the LHS's sign bit, except when the result of the
594 // remainder is zero.
595 if (Mask.isNegative() && KnownZero.isNonNegative()) {
596 APInt Mask2 = APInt::getSignBit(BitWidth);
597 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
598 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
599 Depth+1);
600 // If it's known zero, our sign bit is also zero.
601 if (LHSKnownZero.isNegative())
602 KnownZero |= LHSKnownZero;
603 }
604
Chris Lattner173234a2008-06-02 01:18:21 +0000605 break;
606 case Instruction::URem: {
607 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
608 APInt RA = Rem->getValue();
609 if (RA.isPowerOf2()) {
610 APInt LowBits = (RA - 1);
611 APInt Mask2 = LowBits & Mask;
612 KnownZero |= ~LowBits & Mask;
613 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
614 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000616 break;
617 }
618 }
619
620 // Since the result is less than or equal to either operand, any leading
621 // zero bits in either operand must also exist in the result.
622 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
623 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
624 TD, Depth+1);
625 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
626 TD, Depth+1);
627
Chris Lattner79abedb2009-01-20 18:22:57 +0000628 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000629 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000630 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000631 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
632 break;
633 }
634
Victor Hernandeza276c602009-10-17 01:18:07 +0000635 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000636 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000637 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000638 if (Align == 0 && TD)
639 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000640
641 if (Align > 0)
642 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
643 CountTrailingZeros_32(Align));
644 break;
645 }
646 case Instruction::GetElementPtr: {
647 // Analyze all of the subscripts of this getelementptr instruction
648 // to determine if we can prove known low zero bits.
649 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
650 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
651 ComputeMaskedBits(I->getOperand(0), LocalMask,
652 LocalKnownZero, LocalKnownOne, TD, Depth+1);
653 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
654
655 gep_type_iterator GTI = gep_type_begin(I);
656 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
657 Value *Index = I->getOperand(i);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000658 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000659 // Handle struct member offset arithmetic.
660 if (!TD) return;
661 const StructLayout *SL = TD->getStructLayout(STy);
662 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
663 uint64_t Offset = SL->getElementOffset(Idx);
664 TrailZ = std::min(TrailZ,
665 CountTrailingZeros_64(Offset));
666 } else {
667 // Handle array index arithmetic.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000668 Type *IndexedTy = GTI.getIndexedType();
Chris Lattner173234a2008-06-02 01:18:21 +0000669 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000670 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000671 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000672 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
673 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
674 ComputeMaskedBits(Index, LocalMask,
675 LocalKnownZero, LocalKnownOne, TD, Depth+1);
676 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000677 unsigned(CountTrailingZeros_64(TypeSize) +
678 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000679 }
680 }
681
682 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
683 break;
684 }
685 case Instruction::PHI: {
686 PHINode *P = cast<PHINode>(I);
687 // Handle the case of a simple two-predecessor recurrence PHI.
688 // There's a lot more that could theoretically be done here, but
689 // this is sufficient to catch some interesting cases.
690 if (P->getNumIncomingValues() == 2) {
691 for (unsigned i = 0; i != 2; ++i) {
692 Value *L = P->getIncomingValue(i);
693 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000694 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000695 if (!LU)
696 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000697 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000698 // Check for operations that have the property that if
699 // both their operands have low zero bits, the result
700 // will have low zero bits.
701 if (Opcode == Instruction::Add ||
702 Opcode == Instruction::Sub ||
703 Opcode == Instruction::And ||
704 Opcode == Instruction::Or ||
705 Opcode == Instruction::Mul) {
706 Value *LL = LU->getOperand(0);
707 Value *LR = LU->getOperand(1);
708 // Find a recurrence.
709 if (LL == I)
710 L = LR;
711 else if (LR == I)
712 L = LL;
713 else
714 break;
715 // Ok, we have a PHI of the form L op= R. Check for low
716 // zero bits.
717 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
718 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
719 Mask2 = APInt::getLowBitsSet(BitWidth,
720 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000721
722 // We need to take the minimum number of known bits
723 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
724 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
725
Chris Lattner173234a2008-06-02 01:18:21 +0000726 KnownZero = Mask &
727 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000728 std::min(KnownZero2.countTrailingOnes(),
729 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000730 break;
731 }
732 }
733 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000734
Nick Lewycky3b739d22011-02-10 23:54:10 +0000735 // Unreachable blocks may have zero-operand PHI nodes.
736 if (P->getNumIncomingValues() == 0)
737 return;
738
Dan Gohman9004c8a2009-05-21 02:28:33 +0000739 // Otherwise take the unions of the known bit sets of the operands,
740 // taking conservative care to avoid excessive recursion.
741 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000742 // Skip if every incoming value references to ourself.
743 if (P->hasConstantValue() == P)
744 break;
745
Eli Friedman049d08f2012-03-05 23:09:40 +0000746 KnownZero = Mask;
747 KnownOne = Mask;
Dan Gohman9004c8a2009-05-21 02:28:33 +0000748 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
749 // Skip direct self references.
750 if (P->getIncomingValue(i) == P) continue;
751
752 KnownZero2 = APInt(BitWidth, 0);
753 KnownOne2 = APInt(BitWidth, 0);
754 // Recurse, but cap the recursion to one level, because we don't
755 // want to waste time spinning around in loops.
756 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
757 KnownZero2, KnownOne2, TD, MaxDepth-1);
758 KnownZero &= KnownZero2;
759 KnownOne &= KnownOne2;
760 // If all bits have been ruled out, there's no need to check
761 // more operands.
762 if (!KnownZero && !KnownOne)
763 break;
764 }
765 }
Chris Lattner173234a2008-06-02 01:18:21 +0000766 break;
767 }
768 case Instruction::Call:
769 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
770 switch (II->getIntrinsicID()) {
771 default: break;
Chris Lattner173234a2008-06-02 01:18:21 +0000772 case Intrinsic::ctlz:
773 case Intrinsic::cttz: {
774 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer009da052011-12-24 17:31:46 +0000775 // If this call is undefined for 0, the result will be less than 2^n.
776 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
777 LowBits -= 1;
Eli Friedman923bb412012-03-05 23:22:40 +0000778 KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer009da052011-12-24 17:31:46 +0000779 break;
780 }
781 case Intrinsic::ctpop: {
782 unsigned LowBits = Log2_32(BitWidth)+1;
Eli Friedman923bb412012-03-05 23:22:40 +0000783 KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Chris Lattner173234a2008-06-02 01:18:21 +0000784 break;
785 }
Chad Rosier62660312011-05-26 23:13:19 +0000786 case Intrinsic::x86_sse42_crc32_64_8:
787 case Intrinsic::x86_sse42_crc32_64_64:
Eli Friedman923bb412012-03-05 23:22:40 +0000788 KnownZero = Mask & APInt::getHighBitsSet(64, 32);
Evan Chengcb559c12011-05-22 18:25:30 +0000789 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000790 }
791 }
792 break;
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000793 case Instruction::ExtractValue:
794 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
795 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
796 if (EVI->getNumIndices() != 1) break;
797 if (EVI->getIndices()[0] == 0) {
798 switch (II->getIntrinsicID()) {
799 default: break;
800 case Intrinsic::uadd_with_overflow:
801 case Intrinsic::sadd_with_overflow:
802 ComputeMaskedBitsAddSub(true, II->getArgOperand(0),
803 II->getArgOperand(1), false, Mask,
804 KnownZero, KnownOne, KnownZero2, KnownOne2,
805 TD, Depth);
806 break;
807 case Intrinsic::usub_with_overflow:
808 case Intrinsic::ssub_with_overflow:
809 ComputeMaskedBitsAddSub(false, II->getArgOperand(0),
810 II->getArgOperand(1), false, Mask,
811 KnownZero, KnownOne, KnownZero2, KnownOne2,
812 TD, Depth);
813 break;
Nick Lewyckyf201a062012-03-18 23:28:48 +0000814 case Intrinsic::umul_with_overflow:
815 case Intrinsic::smul_with_overflow:
816 ComputeMaskedBitsMul(II->getArgOperand(0), II->getArgOperand(1),
817 false, Mask, KnownZero, KnownOne,
818 KnownZero2, KnownOne2, TD, Depth);
819 break;
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000820 }
821 }
822 }
Chris Lattner173234a2008-06-02 01:18:21 +0000823 }
824}
825
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000826/// ComputeSignBit - Determine whether the sign bit is known to be zero or
827/// one. Convenience wrapper around ComputeMaskedBits.
828void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
829 const TargetData *TD, unsigned Depth) {
830 unsigned BitWidth = getBitWidth(V->getType(), TD);
831 if (!BitWidth) {
832 KnownZero = false;
833 KnownOne = false;
834 return;
835 }
836 APInt ZeroBits(BitWidth, 0);
837 APInt OneBits(BitWidth, 0);
838 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
839 Depth);
840 KnownOne = OneBits[BitWidth - 1];
841 KnownZero = ZeroBits[BitWidth - 1];
842}
843
844/// isPowerOfTwo - Return true if the given value is known to have exactly one
845/// bit set when defined. For vectors return true if every element is known to
846/// be a power of two when defined. Supports values with integer or pointer
847/// types and vectors of integers.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000848bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
849 unsigned Depth) {
850 if (Constant *C = dyn_cast<Constant>(V)) {
851 if (C->isNullValue())
852 return OrZero;
853 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
854 return CI->getValue().isPowerOf2();
855 // TODO: Handle vector constants.
856 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000857
858 // 1 << X is clearly a power of two if the one is not shifted off the end. If
859 // it is shifted off the end then the result is undefined.
860 if (match(V, m_Shl(m_One(), m_Value())))
861 return true;
862
863 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
864 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000865 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000866 return true;
867
868 // The remaining tests are all recursive, so bail out if we hit the limit.
869 if (Depth++ == MaxDepth)
870 return false;
871
Duncan Sands4604fc72011-10-28 18:30:05 +0000872 Value *X = 0, *Y = 0;
873 // A shift of a power of two is a power of two or zero.
874 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
875 match(V, m_Shr(m_Value(X), m_Value()))))
876 return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
877
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000878 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000879 return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000880
881 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000882 return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
883 isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
884
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000885 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
886 // A power of two and'd with anything is a power of two or zero.
887 if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
888 isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
889 return true;
890 // X & (-X) is always a power of two or zero.
891 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
892 return true;
893 return false;
894 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000895
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000896 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewycky1f7bc702011-03-21 21:40:32 +0000897 // is a power of two only if the first operand is a power of two and not
898 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000899 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
900 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
901 return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000902 }
903
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000904 return false;
905}
906
907/// isKnownNonZero - Return true if the given value is known to be non-zero
908/// when defined. For vectors return true if every element is known to be
909/// non-zero when defined. Supports values with integer or pointer type and
910/// vectors of integers.
911bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
912 if (Constant *C = dyn_cast<Constant>(V)) {
913 if (C->isNullValue())
914 return false;
915 if (isa<ConstantInt>(C))
916 // Must be non-zero due to null test above.
917 return true;
918 // TODO: Handle vectors
919 return false;
920 }
921
922 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000923 if (Depth++ >= MaxDepth)
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000924 return false;
925
926 unsigned BitWidth = getBitWidth(V->getType(), TD);
927
928 // X | Y != 0 if X != 0 or Y != 0.
929 Value *X = 0, *Y = 0;
930 if (match(V, m_Or(m_Value(X), m_Value(Y))))
931 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
932
933 // ext X != 0 if X != 0.
934 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
935 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
936
Duncan Sands91367822011-01-29 13:27:00 +0000937 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000938 // if the lowest bit is shifted off the end.
939 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000940 // shl nuw can't remove any non-zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000941 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000942 if (BO->hasNoUnsignedWrap())
943 return isKnownNonZero(X, TD, Depth);
944
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000945 APInt KnownZero(BitWidth, 0);
946 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000947 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000948 if (KnownOne[0])
949 return true;
950 }
Duncan Sands91367822011-01-29 13:27:00 +0000951 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000952 // defined if the sign bit is shifted off the end.
953 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000954 // shr exact can only shift out zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000955 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000956 if (BO->isExact())
957 return isKnownNonZero(X, TD, Depth);
958
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000959 bool XKnownNonNegative, XKnownNegative;
960 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
961 if (XKnownNegative)
962 return true;
963 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000964 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000965 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
966 return isKnownNonZero(X, TD, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000967 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000968 // X + Y.
969 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
970 bool XKnownNonNegative, XKnownNegative;
971 bool YKnownNonNegative, YKnownNegative;
972 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
973 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
974
975 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000976 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000977 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000978 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
979 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000980
981 // If X and Y are both negative (as signed values) then their sum is not
982 // zero unless both X and Y equal INT_MIN.
983 if (BitWidth && XKnownNegative && YKnownNegative) {
984 APInt KnownZero(BitWidth, 0);
985 APInt KnownOne(BitWidth, 0);
986 APInt Mask = APInt::getSignedMaxValue(BitWidth);
987 // The sign bit of X is set. If some other bit is set then X is not equal
988 // to INT_MIN.
989 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
990 if ((KnownOne & Mask) != 0)
991 return true;
992 // The sign bit of Y is set. If some other bit is set then Y is not equal
993 // to INT_MIN.
994 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
995 if ((KnownOne & Mask) != 0)
996 return true;
997 }
998
999 // The sum of a non-negative number and a power of two is not zero.
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001000 if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001001 return true;
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001002 if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001003 return true;
1004 }
Duncan Sands32a43cc2011-10-27 19:16:21 +00001005 // X * Y.
1006 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1007 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1008 // If X and Y are non-zero then so is X * Y as long as the multiplication
1009 // does not overflow.
1010 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1011 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
1012 return true;
1013 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001014 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1015 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1016 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
1017 isKnownNonZero(SI->getFalseValue(), TD, Depth))
1018 return true;
1019 }
1020
1021 if (!BitWidth) return false;
1022 APInt KnownZero(BitWidth, 0);
1023 APInt KnownOne(BitWidth, 0);
1024 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
1025 TD, Depth);
1026 return KnownOne != 0;
1027}
1028
Chris Lattner173234a2008-06-02 01:18:21 +00001029/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1030/// this predicate to simplify operations downstream. Mask is known to be zero
1031/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +00001032///
1033/// This function is defined on values with integer type, values with pointer
1034/// type (but only if TD is non-null), and vectors of integers. In the case
1035/// where V is a vector, the mask, known zero, and known one values are the
1036/// same width as the vector element, and the bit is set only if it is true
1037/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +00001038bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +00001039 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +00001040 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1041 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1042 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1043 return (KnownZero & Mask) == Mask;
1044}
1045
1046
1047
1048/// ComputeNumSignBits - Return the number of times the sign bit of the
1049/// register is replicated into the other bits. We know that at least 1 bit
1050/// is always equal to the sign bit (itself), but other cases can give us
1051/// information. For example, immediately after an "ashr X, 2", we know that
1052/// the top 3 bits are all equal to each other, so we return 3.
1053///
1054/// 'Op' must have a scalar integer type.
1055///
Dan Gohman846a2f22009-08-27 17:51:25 +00001056unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
1057 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001058 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +00001059 "ComputeNumSignBits requires a TargetData object to operate "
1060 "on non-integer values!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001061 Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +00001062 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1063 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +00001064 unsigned Tmp, Tmp2;
1065 unsigned FirstAnswer = 1;
1066
Chris Lattnerd82e5112008-06-02 18:39:07 +00001067 // Note that ConstantInt is handled by the general ComputeMaskedBits case
1068 // below.
1069
Chris Lattner173234a2008-06-02 01:18:21 +00001070 if (Depth == 6)
1071 return 1; // Limit search depth.
1072
Dan Gohmanca178902009-07-17 20:47:02 +00001073 Operator *U = dyn_cast<Operator>(V);
1074 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +00001075 default: break;
1076 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +00001077 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +00001078 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
1079
Chris Lattner6b0dc922012-01-26 21:37:55 +00001080 case Instruction::AShr: {
Chris Lattner173234a2008-06-02 01:18:21 +00001081 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001082 // ashr X, C -> adds C sign bits. Vectors too.
1083 const APInt *ShAmt;
1084 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1085 Tmp += ShAmt->getZExtValue();
Chris Lattner173234a2008-06-02 01:18:21 +00001086 if (Tmp > TyBits) Tmp = TyBits;
1087 }
1088 return Tmp;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001089 }
1090 case Instruction::Shl: {
1091 const APInt *ShAmt;
1092 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner173234a2008-06-02 01:18:21 +00001093 // shl destroys sign bits.
1094 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001095 Tmp2 = ShAmt->getZExtValue();
1096 if (Tmp2 >= TyBits || // Bad shift.
1097 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1098 return Tmp - Tmp2;
Chris Lattner173234a2008-06-02 01:18:21 +00001099 }
1100 break;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001101 }
Chris Lattner173234a2008-06-02 01:18:21 +00001102 case Instruction::And:
1103 case Instruction::Or:
1104 case Instruction::Xor: // NOT is handled here.
1105 // Logical binary ops preserve the number of sign bits at the worst.
1106 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1107 if (Tmp != 1) {
1108 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1109 FirstAnswer = std::min(Tmp, Tmp2);
1110 // We computed what we know about the sign bits as our first
1111 // answer. Now proceed to the generic code that uses
1112 // ComputeMaskedBits, and pick whichever answer is better.
1113 }
1114 break;
1115
1116 case Instruction::Select:
1117 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1118 if (Tmp == 1) return 1; // Early out.
1119 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1120 return std::min(Tmp, Tmp2);
1121
1122 case Instruction::Add:
1123 // Add can have at most one carry bit. Thus we know that the output
1124 // is, at worst, one more bit than the inputs.
1125 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1126 if (Tmp == 1) return 1; // Early out.
1127
1128 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +00001129 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +00001130 if (CRHS->isAllOnesValue()) {
1131 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1132 APInt Mask = APInt::getAllOnesValue(TyBits);
1133 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1134 Depth+1);
1135
1136 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1137 // sign bits set.
1138 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1139 return TyBits;
1140
1141 // If we are subtracting one from a positive number, there is no carry
1142 // out of the result.
1143 if (KnownZero.isNegative())
1144 return Tmp;
1145 }
1146
1147 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1148 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001149 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +00001150
1151 case Instruction::Sub:
1152 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1153 if (Tmp2 == 1) return 1;
1154
1155 // Handle NEG.
1156 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1157 if (CLHS->isNullValue()) {
1158 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1159 APInt Mask = APInt::getAllOnesValue(TyBits);
1160 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
1161 TD, Depth+1);
1162 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1163 // sign bits set.
1164 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1165 return TyBits;
1166
1167 // If the input is known to be positive (the sign bit is known clear),
1168 // the output of the NEG has the same number of sign bits as the input.
1169 if (KnownZero.isNegative())
1170 return Tmp2;
1171
1172 // Otherwise, we treat this like a SUB.
1173 }
1174
1175 // Sub can have at most one carry bit. Thus we know that the output
1176 // is, at worst, one more bit than the inputs.
1177 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1178 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001179 return std::min(Tmp, Tmp2)-1;
1180
1181 case Instruction::PHI: {
1182 PHINode *PN = cast<PHINode>(U);
1183 // Don't analyze large in-degree PHIs.
1184 if (PN->getNumIncomingValues() > 4) break;
1185
1186 // Take the minimum of all incoming values. This can't infinitely loop
1187 // because of our depth threshold.
1188 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1189 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1190 if (Tmp == 1) return Tmp;
1191 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +00001192 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001193 }
1194 return Tmp;
1195 }
1196
Chris Lattner173234a2008-06-02 01:18:21 +00001197 case Instruction::Trunc:
1198 // FIXME: it's tricky to do anything useful for this, but it is an important
1199 // case for targets like X86.
1200 break;
1201 }
1202
1203 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1204 // use this information.
1205 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1206 APInt Mask = APInt::getAllOnesValue(TyBits);
1207 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1208
1209 if (KnownZero.isNegative()) { // sign bit is 0
1210 Mask = KnownZero;
1211 } else if (KnownOne.isNegative()) { // sign bit is 1;
1212 Mask = KnownOne;
1213 } else {
1214 // Nothing known.
1215 return FirstAnswer;
1216 }
1217
1218 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1219 // the number of identical bits in the top of the input value.
1220 Mask = ~Mask;
1221 Mask <<= Mask.getBitWidth()-TyBits;
1222 // Return # leading zeros. We use 'min' here in case Val was zero before
1223 // shifting. We don't want to return '64' as for an i32 "0".
1224 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1225}
Chris Lattner833f25d2008-06-02 01:29:46 +00001226
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001227/// ComputeMultiple - This function computes the integer multiple of Base that
1228/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001229/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001230/// through SExt instructions only if LookThroughSExt is true.
1231bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001232 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001233 const unsigned MaxDepth = 6;
1234
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001235 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001236 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001237 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001238
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001239 Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001240
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001241 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001242
1243 if (Base == 0)
1244 return false;
1245
1246 if (Base == 1) {
1247 Multiple = V;
1248 return true;
1249 }
1250
1251 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1252 Constant *BaseVal = ConstantInt::get(T, Base);
1253 if (CO && CO == BaseVal) {
1254 // Multiple is 1.
1255 Multiple = ConstantInt::get(T, 1);
1256 return true;
1257 }
1258
1259 if (CI && CI->getZExtValue() % Base == 0) {
1260 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1261 return true;
1262 }
1263
1264 if (Depth == MaxDepth) return false; // Limit search depth.
1265
1266 Operator *I = dyn_cast<Operator>(V);
1267 if (!I) return false;
1268
1269 switch (I->getOpcode()) {
1270 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001271 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001272 if (!LookThroughSExt) return false;
1273 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001274 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001275 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1276 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001277 case Instruction::Shl:
1278 case Instruction::Mul: {
1279 Value *Op0 = I->getOperand(0);
1280 Value *Op1 = I->getOperand(1);
1281
1282 if (I->getOpcode() == Instruction::Shl) {
1283 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1284 if (!Op1CI) return false;
1285 // Turn Op0 << Op1 into Op0 * 2^Op1
1286 APInt Op1Int = Op1CI->getValue();
1287 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001288 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001289 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001290 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001291 }
1292
1293 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001294 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1295 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1296 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1297 if (Op1C->getType()->getPrimitiveSizeInBits() <
1298 MulC->getType()->getPrimitiveSizeInBits())
1299 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1300 if (Op1C->getType()->getPrimitiveSizeInBits() >
1301 MulC->getType()->getPrimitiveSizeInBits())
1302 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1303
1304 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1305 Multiple = ConstantExpr::getMul(MulC, Op1C);
1306 return true;
1307 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001308
1309 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1310 if (Mul0CI->getValue() == 1) {
1311 // V == Base * Op1, so return Op1
1312 Multiple = Op1;
1313 return true;
1314 }
1315 }
1316
Chris Lattnere9711312010-09-05 17:20:46 +00001317 Value *Mul1 = NULL;
1318 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1319 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1320 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1321 if (Op0C->getType()->getPrimitiveSizeInBits() <
1322 MulC->getType()->getPrimitiveSizeInBits())
1323 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1324 if (Op0C->getType()->getPrimitiveSizeInBits() >
1325 MulC->getType()->getPrimitiveSizeInBits())
1326 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1327
1328 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1329 Multiple = ConstantExpr::getMul(MulC, Op0C);
1330 return true;
1331 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001332
1333 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1334 if (Mul1CI->getValue() == 1) {
1335 // V == Base * Op0, so return Op0
1336 Multiple = Op0;
1337 return true;
1338 }
1339 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001340 }
1341 }
1342
1343 // We could not determine if V is a multiple of Base.
1344 return false;
1345}
1346
Chris Lattner833f25d2008-06-02 01:29:46 +00001347/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1348/// value is never equal to -0.0.
1349///
1350/// NOTE: this function will need to be revisited when we support non-default
1351/// rounding modes!
1352///
1353bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1354 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1355 return !CFP->getValueAPF().isNegZero();
1356
1357 if (Depth == 6)
1358 return 1; // Limit search depth.
1359
Dan Gohmanca178902009-07-17 20:47:02 +00001360 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001361 if (I == 0) return false;
1362
1363 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001364 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001365 isa<ConstantFP>(I->getOperand(1)) &&
1366 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1367 return true;
1368
1369 // sitofp and uitofp turn into +0.0 for zero.
1370 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1371 return true;
1372
1373 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1374 // sqrt(-0.0) = -0.0, no other negative results are possible.
1375 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001376 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001377
1378 if (const CallInst *CI = dyn_cast<CallInst>(I))
1379 if (const Function *F = CI->getCalledFunction()) {
1380 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001381 // abs(x) != -0.0
1382 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001383 // fabs[lf](x) != -0.0
1384 if (F->getName() == "fabs") return true;
1385 if (F->getName() == "fabsf") return true;
1386 if (F->getName() == "fabsl") return true;
1387 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1388 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001389 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001390 }
1391 }
1392
1393 return false;
1394}
1395
Chris Lattnerbb897102010-12-26 20:15:01 +00001396/// isBytewiseValue - If the specified value can be set by repeating the same
1397/// byte in memory, return the i8 value that it is represented with. This is
1398/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1399/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1400/// byte store (e.g. i16 0x1234), return null.
1401Value *llvm::isBytewiseValue(Value *V) {
1402 // All byte-wide stores are splatable, even of arbitrary variables.
1403 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001404
1405 // Handle 'null' ConstantArrayZero etc.
1406 if (Constant *C = dyn_cast<Constant>(V))
1407 if (C->isNullValue())
1408 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001409
1410 // Constant float and double values can be handled as integer values if the
1411 // corresponding integer value is "byteable". An important case is 0.0.
1412 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1413 if (CFP->getType()->isFloatTy())
1414 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1415 if (CFP->getType()->isDoubleTy())
1416 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1417 // Don't handle long double formats, which have strange constraints.
1418 }
1419
1420 // We can handle constant integers that are power of two in size and a
1421 // multiple of 8 bits.
1422 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1423 unsigned Width = CI->getBitWidth();
1424 if (isPowerOf2_32(Width) && Width > 8) {
1425 // We can handle this value if the recursive binary decomposition is the
1426 // same at all levels.
1427 APInt Val = CI->getValue();
1428 APInt Val2;
1429 while (Val.getBitWidth() != 8) {
1430 unsigned NextWidth = Val.getBitWidth()/2;
1431 Val2 = Val.lshr(NextWidth);
1432 Val2 = Val2.trunc(Val.getBitWidth()/2);
1433 Val = Val.trunc(Val.getBitWidth()/2);
1434
1435 // If the top/bottom halves aren't the same, reject it.
1436 if (Val != Val2)
1437 return 0;
1438 }
1439 return ConstantInt::get(V->getContext(), Val);
1440 }
1441 }
1442
Chris Lattner18c7f802012-02-05 02:29:43 +00001443 // A ConstantDataArray/Vector is splatable if all its members are equal and
1444 // also splatable.
1445 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1446 Value *Elt = CA->getElementAsConstant(0);
1447 Value *Val = isBytewiseValue(Elt);
Chris Lattnerbb897102010-12-26 20:15:01 +00001448 if (!Val)
1449 return 0;
1450
Chris Lattner18c7f802012-02-05 02:29:43 +00001451 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1452 if (CA->getElementAsConstant(I) != Elt)
Chris Lattnerbb897102010-12-26 20:15:01 +00001453 return 0;
1454
1455 return Val;
1456 }
Chad Rosierdce42b72011-12-06 00:19:08 +00001457
Chris Lattnerbb897102010-12-26 20:15:01 +00001458 // Conceptually, we could handle things like:
1459 // %a = zext i8 %X to i16
1460 // %b = shl i16 %a, 8
1461 // %c = or i16 %a, %b
1462 // but until there is an example that actually needs this, it doesn't seem
1463 // worth worrying about.
1464 return 0;
1465}
1466
1467
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001468// This is the recursive version of BuildSubAggregate. It takes a few different
1469// arguments. Idxs is the index within the nested struct From that we are
1470// looking at now (which is of type IndexedType). IdxSkip is the number of
1471// indices from Idxs that should be left out when inserting into the resulting
1472// struct. To is the result struct built so far, new insertvalue instructions
1473// build on that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001474static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Dan Gohman7db949d2009-08-07 01:32:21 +00001475 SmallVector<unsigned, 10> &Idxs,
1476 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001477 Instruction *InsertBefore) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001478 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001479 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001480 // Save the original To argument so we can modify it
1481 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001482 // General case, the type indexed by Idxs is a struct
1483 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1484 // Process each struct element recursively
1485 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001486 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001487 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001488 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001489 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001490 if (!To) {
1491 // Couldn't find any inserted value for this index? Cleanup
1492 while (PrevTo != OrigTo) {
1493 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1494 PrevTo = Del->getAggregateOperand();
1495 Del->eraseFromParent();
1496 }
1497 // Stop processing elements
1498 break;
1499 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001500 }
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001501 // If we successfully found a value for each of our subaggregates
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001502 if (To)
1503 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001504 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001505 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1506 // the struct's elements had a value that was inserted directly. In the latter
1507 // case, perhaps we can't determine each of the subelements individually, but
1508 // we might be able to find the complete struct somewhere.
1509
1510 // Find the value that is at that particular spot
Jay Foadfc6d3a42011-07-13 10:26:04 +00001511 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001512
1513 if (!V)
1514 return NULL;
1515
1516 // Insert the value in the new (sub) aggregrate
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001517 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001518 "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001519}
1520
1521// This helper takes a nested struct and extracts a part of it (which is again a
1522// struct) into a new value. For example, given the struct:
1523// { a, { b, { c, d }, e } }
1524// and the indices "1, 1" this returns
1525// { c, d }.
1526//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001527// It does this by inserting an insertvalue for each element in the resulting
1528// struct, as opposed to just inserting a single struct. This will only work if
1529// each of the elements of the substruct are known (ie, inserted into From by an
1530// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001531//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001532// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foadfc6d3a42011-07-13 10:26:04 +00001533static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohman7db949d2009-08-07 01:32:21 +00001534 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001535 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001536 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001537 idx_range);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001538 Value *To = UndefValue::get(IndexedType);
Jay Foadfc6d3a42011-07-13 10:26:04 +00001539 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001540 unsigned IdxSkip = Idxs.size();
1541
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001542 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001543}
1544
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001545/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1546/// the scalar value indexed is already around as a register, for example if it
1547/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001548///
1549/// If InsertBefore is not null, this function will duplicate (modified)
1550/// insertvalues when a part of a nested struct is extracted.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001551Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1552 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001553 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerdf390282012-01-24 07:54:10 +00001554 // recursion).
Jay Foadfc6d3a42011-07-13 10:26:04 +00001555 if (idx_range.empty())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001556 return V;
Chris Lattnerdf390282012-01-24 07:54:10 +00001557 // We have indices, so V should have an indexable type.
1558 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1559 "Not looking at a struct or array?");
1560 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1561 "Invalid indices for type?");
Owen Anderson76f600b2009-07-06 22:37:39 +00001562
Chris Lattnera1f00f42012-01-25 06:48:06 +00001563 if (Constant *C = dyn_cast<Constant>(V)) {
1564 C = C->getAggregateElement(idx_range[0]);
1565 if (C == 0) return 0;
1566 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1567 }
Chris Lattnerdf390282012-01-24 07:54:10 +00001568
1569 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001570 // Loop the indices for the insertvalue instruction in parallel with the
1571 // requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001572 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001573 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1574 i != e; ++i, ++req_idx) {
Jay Foadfc6d3a42011-07-13 10:26:04 +00001575 if (req_idx == idx_range.end()) {
Chris Lattnerdf390282012-01-24 07:54:10 +00001576 // We can't handle this without inserting insertvalues
1577 if (!InsertBefore)
Matthijs Kooijman97728912008-06-16 13:28:31 +00001578 return 0;
Chris Lattnerdf390282012-01-24 07:54:10 +00001579
1580 // The requested index identifies a part of a nested aggregate. Handle
1581 // this specially. For example,
1582 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1583 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1584 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1585 // This can be changed into
1586 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1587 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1588 // which allows the unused 0,0 element from the nested struct to be
1589 // removed.
1590 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1591 InsertBefore);
Duncan Sands9954c762008-06-19 08:47:31 +00001592 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001593
1594 // This insert value inserts something else than what we are looking for.
1595 // See if the (aggregrate) value inserted into has the value we are
1596 // looking for, then.
1597 if (*req_idx != *i)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001598 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001599 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001600 }
1601 // If we end up here, the indices of the insertvalue match with those
1602 // requested (though possibly only partially). Now we recursively look at
1603 // the inserted value, passing any remaining indices.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001604 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001605 makeArrayRef(req_idx, idx_range.end()),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001606 InsertBefore);
Chris Lattnerdf390282012-01-24 07:54:10 +00001607 }
1608
1609 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001610 // If we're extracting a value from an aggregrate that was extracted from
1611 // something else, we can extract from that something else directly instead.
1612 // However, we will need to chain I's indices with the requested indices.
1613
1614 // Calculate the number of indices required
Jay Foadfc6d3a42011-07-13 10:26:04 +00001615 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001616 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001617 SmallVector<unsigned, 5> Idxs;
1618 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001619 // Add indices from the extract value instruction
Jay Foadfc6d3a42011-07-13 10:26:04 +00001620 Idxs.append(I->idx_begin(), I->idx_end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001621
1622 // Add requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001623 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001624
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001625 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001626 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001627
Jay Foadfc6d3a42011-07-13 10:26:04 +00001628 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001629 }
1630 // Otherwise, we don't know (such as, extracting from a function return value
1631 // or load instruction)
1632 return 0;
1633}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001634
Chris Lattnered58a6f2010-11-30 22:25:26 +00001635/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1636/// it can be expressed as a base pointer plus a constant offset. Return the
1637/// base and offset to the caller.
1638Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1639 const TargetData &TD) {
1640 Operator *PtrOp = dyn_cast<Operator>(Ptr);
Nadav Rotem16087692011-12-05 06:29:09 +00001641 if (PtrOp == 0 || Ptr->getType()->isVectorTy())
1642 return Ptr;
Chris Lattnered58a6f2010-11-30 22:25:26 +00001643
1644 // Just look through bitcasts.
1645 if (PtrOp->getOpcode() == Instruction::BitCast)
1646 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1647
1648 // If this is a GEP with constant indices, we can look through it.
1649 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1650 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1651
1652 gep_type_iterator GTI = gep_type_begin(GEP);
1653 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1654 ++I, ++GTI) {
1655 ConstantInt *OpC = cast<ConstantInt>(*I);
1656 if (OpC->isZero()) continue;
1657
1658 // Handle a struct and array indices which add their offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001659 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattnered58a6f2010-11-30 22:25:26 +00001660 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1661 } else {
1662 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1663 Offset += OpC->getSExtValue()*Size;
1664 }
1665 }
1666
1667 // Re-sign extend from the pointer size if needed to get overflow edge cases
1668 // right.
1669 unsigned PtrSize = TD.getPointerSizeInBits();
1670 if (PtrSize < 64)
1671 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1672
1673 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1674}
1675
1676
Chris Lattner18c7f802012-02-05 02:29:43 +00001677/// getConstantStringInfo - This function computes the length of a
Evan Cheng0ff39b32008-06-30 07:31:25 +00001678/// null-terminated C string pointed to by V. If successful, it returns true
1679/// and returns the string in Str. If unsuccessful, it returns false.
Chris Lattner18c7f802012-02-05 02:29:43 +00001680bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
1681 uint64_t Offset, bool TrimAtNul) {
1682 assert(V);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001683
Chris Lattner18c7f802012-02-05 02:29:43 +00001684 // Look through bitcast instructions and geps.
1685 V = V->stripPointerCasts();
Bill Wendling0582ae92009-03-13 04:39:26 +00001686
Chris Lattner18c7f802012-02-05 02:29:43 +00001687 // If the value is a GEP instructionor constant expression, treat it as an
1688 // offset.
1689 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001690 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001691 if (GEP->getNumOperands() != 3)
1692 return false;
1693
Evan Cheng0ff39b32008-06-30 07:31:25 +00001694 // Make sure the index-ee is a pointer to array of i8.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001695 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1696 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001697 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001698 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001699
1700 // Check to make sure that the first operand of the GEP is an integer and
1701 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001702 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001703 if (FirstIdx == 0 || !FirstIdx->isZero())
1704 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001705
1706 // If the second index isn't a ConstantInt, then this is a variable index
1707 // into the array. If this occurs, we can't say anything meaningful about
1708 // the string.
1709 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001710 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001711 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001712 else
1713 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001714 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001715 }
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001716
Evan Cheng0ff39b32008-06-30 07:31:25 +00001717 // The GEP instruction, constant or instruction, must reference a global
1718 // variable that is a constant and is initialized. The referenced constant
1719 // initializer is the array that we'll use for optimization.
Chris Lattner18c7f802012-02-05 02:29:43 +00001720 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001721 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001722 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001723
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001724 // Handle the all-zeros case
Chris Lattner18c7f802012-02-05 02:29:43 +00001725 if (GV->getInitializer()->isNullValue()) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001726 // This is a degenerate case. The initializer is constant zero so the
1727 // length of the string must be zero.
Chris Lattner18c7f802012-02-05 02:29:43 +00001728 Str = "";
Bill Wendling0582ae92009-03-13 04:39:26 +00001729 return true;
1730 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001731
1732 // Must be a Constant Array
Chris Lattner18c7f802012-02-05 02:29:43 +00001733 const ConstantDataArray *Array =
1734 dyn_cast<ConstantDataArray>(GV->getInitializer());
1735 if (Array == 0 || !Array->isString())
Bill Wendling0582ae92009-03-13 04:39:26 +00001736 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001737
1738 // Get the number of elements in the array
Chris Lattner18c7f802012-02-05 02:29:43 +00001739 uint64_t NumElts = Array->getType()->getArrayNumElements();
1740
1741 // Start out with the entire array in the StringRef.
1742 Str = Array->getAsString();
1743
Bill Wendling0582ae92009-03-13 04:39:26 +00001744 if (Offset > NumElts)
1745 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001746
Chris Lattner18c7f802012-02-05 02:29:43 +00001747 // Skip over 'offset' bytes.
1748 Str = Str.substr(Offset);
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001749
Chris Lattner18c7f802012-02-05 02:29:43 +00001750 if (TrimAtNul) {
1751 // Trim off the \0 and anything after it. If the array is not nul
1752 // terminated, we just return the whole end of string. The client may know
1753 // some other way that the string is length-bound.
1754 Str = Str.substr(0, Str.find('\0'));
1755 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001756 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001757}
Eric Christopher25ec4832010-03-05 06:58:57 +00001758
1759// These next two are very similar to the above, but also look through PHI
1760// nodes.
1761// TODO: See if we can integrate these two together.
1762
1763/// GetStringLengthH - If we can compute the length of the string pointed to by
1764/// the specified pointer, return 'len+1'. If we can't, return 0.
1765static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1766 // Look through noop bitcast instructions.
Chris Lattner18c7f802012-02-05 02:29:43 +00001767 V = V->stripPointerCasts();
Eric Christopher25ec4832010-03-05 06:58:57 +00001768
1769 // If this is a PHI node, there are two cases: either we have already seen it
1770 // or we haven't.
1771 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1772 if (!PHIs.insert(PN))
1773 return ~0ULL; // already in the set.
1774
1775 // If it was new, see if all the input strings are the same length.
1776 uint64_t LenSoFar = ~0ULL;
1777 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1778 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1779 if (Len == 0) return 0; // Unknown length -> unknown.
1780
1781 if (Len == ~0ULL) continue;
1782
1783 if (Len != LenSoFar && LenSoFar != ~0ULL)
1784 return 0; // Disagree -> unknown.
1785 LenSoFar = Len;
1786 }
1787
1788 // Success, all agree.
1789 return LenSoFar;
1790 }
1791
1792 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1793 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1794 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1795 if (Len1 == 0) return 0;
1796 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1797 if (Len2 == 0) return 0;
1798 if (Len1 == ~0ULL) return Len2;
1799 if (Len2 == ~0ULL) return Len1;
1800 if (Len1 != Len2) return 0;
1801 return Len1;
1802 }
Chris Lattner18c7f802012-02-05 02:29:43 +00001803
1804 // Otherwise, see if we can read the string.
1805 StringRef StrData;
1806 if (!getConstantStringInfo(V, StrData))
Eric Christopher25ec4832010-03-05 06:58:57 +00001807 return 0;
1808
Chris Lattner18c7f802012-02-05 02:29:43 +00001809 return StrData.size()+1;
Eric Christopher25ec4832010-03-05 06:58:57 +00001810}
1811
1812/// GetStringLength - If we can compute the length of the string pointed to by
1813/// the specified pointer, return 'len+1'. If we can't, return 0.
1814uint64_t llvm::GetStringLength(Value *V) {
1815 if (!V->getType()->isPointerTy()) return 0;
1816
1817 SmallPtrSet<PHINode*, 32> PHIs;
1818 uint64_t Len = GetStringLengthH(V, PHIs);
1819 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1820 // an empty string as a length.
1821 return Len == ~0ULL ? 1 : Len;
1822}
Dan Gohman5034dd32010-12-15 20:02:24 +00001823
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001824Value *
1825llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001826 if (!V->getType()->isPointerTy())
1827 return V;
1828 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1829 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1830 V = GEP->getPointerOperand();
1831 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1832 V = cast<Operator>(V)->getOperand(0);
1833 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1834 if (GA->mayBeOverridden())
1835 return V;
1836 V = GA->getAliasee();
1837 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001838 // See if InstructionSimplify knows any relevant tricks.
1839 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001840 // TODO: Acquire a DominatorTree and use it.
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001841 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001842 V = Simplified;
1843 continue;
1844 }
1845
Dan Gohman5034dd32010-12-15 20:02:24 +00001846 return V;
1847 }
1848 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1849 }
1850 return V;
1851}
Nick Lewycky99e0b2a2011-06-27 04:20:45 +00001852
1853/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1854/// are lifetime markers.
1855///
1856bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1857 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1858 UI != UE; ++UI) {
1859 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1860 if (!II) return false;
1861
1862 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1863 II->getIntrinsicID() != Intrinsic::lifetime_end)
1864 return false;
1865 }
1866 return true;
1867}
Dan Gohmanf0426602011-12-14 23:49:11 +00001868
Dan Gohmanfebaf842012-01-04 23:01:09 +00001869bool llvm::isSafeToSpeculativelyExecute(const Value *V,
Dan Gohmanf0426602011-12-14 23:49:11 +00001870 const TargetData *TD) {
Dan Gohmanfebaf842012-01-04 23:01:09 +00001871 const Operator *Inst = dyn_cast<Operator>(V);
1872 if (!Inst)
1873 return false;
1874
Dan Gohmanf0426602011-12-14 23:49:11 +00001875 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1876 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1877 if (C->canTrap())
1878 return false;
1879
1880 switch (Inst->getOpcode()) {
1881 default:
1882 return true;
1883 case Instruction::UDiv:
1884 case Instruction::URem:
1885 // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1886 return isKnownNonZero(Inst->getOperand(1), TD);
1887 case Instruction::SDiv:
1888 case Instruction::SRem: {
1889 Value *Op = Inst->getOperand(1);
1890 // x / y is undefined if y == 0
1891 if (!isKnownNonZero(Op, TD))
1892 return false;
1893 // x / y might be undefined if y == -1
1894 unsigned BitWidth = getBitWidth(Op->getType(), TD);
1895 if (BitWidth == 0)
1896 return false;
1897 APInt KnownZero(BitWidth, 0);
1898 APInt KnownOne(BitWidth, 0);
1899 ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth),
1900 KnownZero, KnownOne, TD);
1901 return !!KnownZero;
1902 }
1903 case Instruction::Load: {
1904 const LoadInst *LI = cast<LoadInst>(Inst);
1905 if (!LI->isUnordered())
1906 return false;
1907 return LI->getPointerOperand()->isDereferenceablePointer();
1908 }
Nick Lewycky83696872011-12-21 05:52:02 +00001909 case Instruction::Call: {
1910 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1911 switch (II->getIntrinsicID()) {
1912 case Intrinsic::bswap:
1913 case Intrinsic::ctlz:
1914 case Intrinsic::ctpop:
1915 case Intrinsic::cttz:
1916 case Intrinsic::objectsize:
1917 case Intrinsic::sadd_with_overflow:
1918 case Intrinsic::smul_with_overflow:
1919 case Intrinsic::ssub_with_overflow:
1920 case Intrinsic::uadd_with_overflow:
1921 case Intrinsic::umul_with_overflow:
1922 case Intrinsic::usub_with_overflow:
1923 return true;
1924 // TODO: some fp intrinsics are marked as having the same error handling
1925 // as libm. They're safe to speculate when they won't error.
1926 // TODO: are convert_{from,to}_fp16 safe?
1927 // TODO: can we list target-specific intrinsics here?
1928 default: break;
1929 }
1930 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001931 return false; // The called function could have undefined behavior or
Nick Lewycky83696872011-12-21 05:52:02 +00001932 // side-effects, even if marked readnone nounwind.
1933 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001934 case Instruction::VAArg:
1935 case Instruction::Alloca:
1936 case Instruction::Invoke:
1937 case Instruction::PHI:
1938 case Instruction::Store:
1939 case Instruction::Ret:
1940 case Instruction::Br:
1941 case Instruction::IndirectBr:
1942 case Instruction::Switch:
Dan Gohmanf0426602011-12-14 23:49:11 +00001943 case Instruction::Unreachable:
1944 case Instruction::Fence:
1945 case Instruction::LandingPad:
1946 case Instruction::AtomicRMW:
1947 case Instruction::AtomicCmpXchg:
1948 case Instruction::Resume:
1949 return false; // Misc instructions which have effects
1950 }
1951}