1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines that help analyze properties that chains of
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Analysis/AssumptionTracker.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/MemoryBuiltins.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/MathExtras.h"
38 using namespace llvm::PatternMatch;
40 const unsigned MaxDepth = 6;
42 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
43 /// unknown returns 0). For vector types, returns the element type's bitwidth.
44 static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
45 if (unsigned BitWidth = Ty->getScalarSizeInBits())
48 return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
51 // Many of these functions have internal versions that take an assumption
52 // exclusion set. This is because of the potential for mutual recursion to
53 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
54 // classic case of this is assume(x = y), which will attempt to determine
55 // bits in x from bits in y, which will attempt to determine bits in y from
56 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
57 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
58 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
59 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
61 // Simplifying using an assume can only be done in a particular control-flow
62 // context (the context instruction provides that context). If an assume and
63 // the context instruction are not in the same block then the DT helps in
64 // figuring out if we can use it.
67 AssumptionTracker *AT;
68 const Instruction *CxtI;
69 const DominatorTree *DT;
71 Query(AssumptionTracker *AT = nullptr, const Instruction *CxtI = nullptr,
72 const DominatorTree *DT = nullptr)
73 : AT(AT), CxtI(CxtI), DT(DT) {}
75 Query(const Query &Q, const Value *NewExcl)
76 : ExclInvs(Q.ExclInvs), AT(Q.AT), CxtI(Q.CxtI), DT(Q.DT) {
77 ExclInvs.insert(NewExcl);
81 // Given the provided Value and, potentially, a context instruction, returned
82 // the preferred context instruction (if any).
83 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
84 // If we've been provided with a context instruction, then use that (provided
85 // it has been inserted).
86 if (CxtI && CxtI->getParent())
89 // If the value is really an already-inserted instruction, then use that.
90 CxtI = dyn_cast<Instruction>(V);
91 if (CxtI && CxtI->getParent())
97 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
98 const DataLayout *TD, unsigned Depth,
101 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
102 const DataLayout *TD, unsigned Depth,
103 AssumptionTracker *AT, const Instruction *CxtI,
104 const DominatorTree *DT) {
105 ::computeKnownBits(V, KnownZero, KnownOne, TD, Depth,
106 Query(AT, safeCxtI(V, CxtI), DT));
109 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
110 const DataLayout *TD, unsigned Depth,
113 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
114 const DataLayout *TD, unsigned Depth,
115 AssumptionTracker *AT, const Instruction *CxtI,
116 const DominatorTree *DT) {
117 ::ComputeSignBit(V, KnownZero, KnownOne, TD, Depth,
118 Query(AT, safeCxtI(V, CxtI), DT));
121 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
124 bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
125 AssumptionTracker *AT,
126 const Instruction *CxtI,
127 const DominatorTree *DT) {
128 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
129 Query(AT, safeCxtI(V, CxtI), DT));
132 static bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
135 bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
136 AssumptionTracker *AT, const Instruction *CxtI,
137 const DominatorTree *DT) {
138 return ::isKnownNonZero(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
141 static bool MaskedValueIsZero(Value *V, const APInt &Mask,
142 const DataLayout *TD, unsigned Depth,
145 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
146 const DataLayout *TD, unsigned Depth,
147 AssumptionTracker *AT, const Instruction *CxtI,
148 const DominatorTree *DT) {
149 return ::MaskedValueIsZero(V, Mask, TD, Depth,
150 Query(AT, safeCxtI(V, CxtI), DT));
153 static unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
154 unsigned Depth, const Query &Q);
156 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
157 unsigned Depth, AssumptionTracker *AT,
158 const Instruction *CxtI,
159 const DominatorTree *DT) {
160 return ::ComputeNumSignBits(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
163 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
164 APInt &KnownZero, APInt &KnownOne,
165 APInt &KnownZero2, APInt &KnownOne2,
166 const DataLayout *TD, unsigned Depth,
169 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
170 // We know that the top bits of C-X are clear if X contains less bits
171 // than C (i.e. no wrap-around can happen). For example, 20-X is
172 // positive if we can prove that X is >= 0 and < 16.
173 if (!CLHS->getValue().isNegative()) {
174 unsigned BitWidth = KnownZero.getBitWidth();
175 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
176 // NLZ can't be BitWidth with no sign bit
177 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
178 computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
180 // If all of the MaskV bits are known to be zero, then we know the
181 // output top bits are zero, because we now know that the output is
183 if ((KnownZero2 & MaskV) == MaskV) {
184 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
185 // Top bits known zero.
186 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
192 unsigned BitWidth = KnownZero.getBitWidth();
194 // If an initial sequence of bits in the result is not needed, the
195 // corresponding bits in the operands are not needed.
196 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
197 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1, Q);
198 computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
200 // Carry in a 1 for a subtract, rather than a 0.
201 APInt CarryIn(BitWidth, 0);
203 // Sum = LHS + ~RHS + 1
204 std::swap(KnownZero2, KnownOne2);
208 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
209 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
211 // Compute known bits of the carry.
212 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
213 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
215 // Compute set of known bits (where all three relevant bits are known).
216 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
217 APInt RHSKnown = KnownZero2 | KnownOne2;
218 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
219 APInt Known = LHSKnown & RHSKnown & CarryKnown;
221 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
222 "known bits of sum differ");
224 // Compute known bits of the result.
225 KnownZero = ~PossibleSumOne & Known;
226 KnownOne = PossibleSumOne & Known;
228 // Are we still trying to solve for the sign bit?
229 if (!Known.isNegative()) {
231 // Adding two non-negative numbers, or subtracting a negative number from
232 // a non-negative one, can't wrap into negative.
233 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
234 KnownZero |= APInt::getSignBit(BitWidth);
235 // Adding two negative numbers, or subtracting a non-negative number from
236 // a negative one, can't wrap into non-negative.
237 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
238 KnownOne |= APInt::getSignBit(BitWidth);
243 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
244 APInt &KnownZero, APInt &KnownOne,
245 APInt &KnownZero2, APInt &KnownOne2,
246 const DataLayout *TD, unsigned Depth,
248 unsigned BitWidth = KnownZero.getBitWidth();
249 computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1, Q);
250 computeKnownBits(Op0, KnownZero2, KnownOne2, TD, Depth+1, Q);
252 bool isKnownNegative = false;
253 bool isKnownNonNegative = false;
254 // If the multiplication is known not to overflow, compute the sign bit.
257 // The product of a number with itself is non-negative.
258 isKnownNonNegative = true;
260 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
261 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
262 bool isKnownNegativeOp1 = KnownOne.isNegative();
263 bool isKnownNegativeOp0 = KnownOne2.isNegative();
264 // The product of two numbers with the same sign is non-negative.
265 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
266 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
267 // The product of a negative number and a non-negative number is either
269 if (!isKnownNonNegative)
270 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
271 isKnownNonZero(Op0, TD, Depth, Q)) ||
272 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
273 isKnownNonZero(Op1, TD, Depth, Q));
277 // If low bits are zero in either operand, output low known-0 bits.
278 // Also compute a conserative estimate for high known-0 bits.
279 // More trickiness is possible, but this is sufficient for the
280 // interesting case of alignment computation.
281 KnownOne.clearAllBits();
282 unsigned TrailZ = KnownZero.countTrailingOnes() +
283 KnownZero2.countTrailingOnes();
284 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
285 KnownZero2.countLeadingOnes(),
286 BitWidth) - BitWidth;
288 TrailZ = std::min(TrailZ, BitWidth);
289 LeadZ = std::min(LeadZ, BitWidth);
290 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
291 APInt::getHighBitsSet(BitWidth, LeadZ);
293 // Only make use of no-wrap flags if we failed to compute the sign bit
294 // directly. This matters if the multiplication always overflows, in
295 // which case we prefer to follow the result of the direct computation,
296 // though as the program is invoking undefined behaviour we can choose
297 // whatever we like here.
298 if (isKnownNonNegative && !KnownOne.isNegative())
299 KnownZero.setBit(BitWidth - 1);
300 else if (isKnownNegative && !KnownZero.isNegative())
301 KnownOne.setBit(BitWidth - 1);
304 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
306 unsigned BitWidth = KnownZero.getBitWidth();
307 unsigned NumRanges = Ranges.getNumOperands() / 2;
308 assert(NumRanges >= 1);
310 // Use the high end of the ranges to find leading zeros.
311 unsigned MinLeadingZeros = BitWidth;
312 for (unsigned i = 0; i < NumRanges; ++i) {
313 ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
314 ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
315 ConstantRange Range(Lower->getValue(), Upper->getValue());
316 if (Range.isWrappedSet())
317 MinLeadingZeros = 0; // -1 has no zeros
318 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
319 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
322 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
325 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
326 SmallVector<const Value *, 16> WorkSet(1, I);
327 SmallPtrSet<const Value *, 32> Visited;
328 SmallPtrSet<const Value *, 16> EphValues;
330 while (!WorkSet.empty()) {
331 const Value *V = WorkSet.pop_back_val();
332 if (!Visited.insert(V))
335 // If all uses of this value are ephemeral, then so is this value.
336 bool FoundNEUse = false;
337 for (const User *I : V->users())
338 if (!EphValues.count(I)) {
348 if (const User *U = dyn_cast<User>(V))
349 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
351 if (isSafeToSpeculativelyExecute(*J))
352 WorkSet.push_back(*J);
360 // Is this an intrinsic that cannot be speculated but also cannot trap?
361 static bool isAssumeLikeIntrinsic(const Instruction *I) {
362 if (const CallInst *CI = dyn_cast<CallInst>(I))
363 if (Function *F = CI->getCalledFunction())
364 switch (F->getIntrinsicID()) {
366 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
367 case Intrinsic::assume:
368 case Intrinsic::dbg_declare:
369 case Intrinsic::dbg_value:
370 case Intrinsic::invariant_start:
371 case Intrinsic::invariant_end:
372 case Intrinsic::lifetime_start:
373 case Intrinsic::lifetime_end:
374 case Intrinsic::objectsize:
375 case Intrinsic::ptr_annotation:
376 case Intrinsic::var_annotation:
383 static bool isValidAssumeForContext(Value *V, const Query &Q,
384 const DataLayout *DL) {
385 Instruction *Inv = cast<Instruction>(V);
387 // There are two restrictions on the use of an assume:
388 // 1. The assume must dominate the context (or the control flow must
389 // reach the assume whenever it reaches the context).
390 // 2. The context must not be in the assume's set of ephemeral values
391 // (otherwise we will use the assume to prove that the condition
392 // feeding the assume is trivially true, thus causing the removal of
396 if (Q.DT->dominates(Inv, Q.CxtI)) {
398 } else if (Inv->getParent() == Q.CxtI->getParent()) {
399 // The context comes first, but they're both in the same block. Make sure
400 // there is nothing in between that might interrupt the control flow.
401 for (BasicBlock::const_iterator I =
402 std::next(BasicBlock::const_iterator(Q.CxtI)),
403 IE(Inv); I != IE; ++I)
404 if (!isSafeToSpeculativelyExecute(I, DL) &&
405 !isAssumeLikeIntrinsic(I))
408 return !isEphemeralValueOf(Inv, Q.CxtI);
414 // When we don't have a DT, we do a limited search...
415 if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
417 } else if (Inv->getParent() == Q.CxtI->getParent()) {
418 // Search forward from the assume until we reach the context (or the end
419 // of the block); the common case is that the assume will come first.
420 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
421 IE = Inv->getParent()->end(); I != IE; ++I)
425 // The context must come first...
426 for (BasicBlock::const_iterator I =
427 std::next(BasicBlock::const_iterator(Q.CxtI)),
428 IE(Inv); I != IE; ++I)
429 if (!isSafeToSpeculativelyExecute(I, DL) &&
430 !isAssumeLikeIntrinsic(I))
433 return !isEphemeralValueOf(Inv, Q.CxtI);
439 bool llvm::isValidAssumeForContext(const Instruction *I,
440 const Instruction *CxtI,
441 const DataLayout *DL,
442 const DominatorTree *DT) {
443 return ::isValidAssumeForContext(const_cast<Instruction*>(I),
444 Query(nullptr, CxtI, DT), DL);
447 template<typename LHS, typename RHS>
448 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
449 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
450 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
451 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
454 template<typename LHS, typename RHS>
455 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
456 BinaryOp_match<RHS, LHS, Instruction::And>>
457 m_c_And(const LHS &L, const RHS &R) {
458 return m_CombineOr(m_And(L, R), m_And(R, L));
461 template<typename LHS, typename RHS>
462 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
463 BinaryOp_match<RHS, LHS, Instruction::Or>>
464 m_c_Or(const LHS &L, const RHS &R) {
465 return m_CombineOr(m_Or(L, R), m_Or(R, L));
468 template<typename LHS, typename RHS>
469 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
470 BinaryOp_match<RHS, LHS, Instruction::Xor>>
471 m_c_Xor(const LHS &L, const RHS &R) {
472 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
475 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
477 const DataLayout *DL,
478 unsigned Depth, const Query &Q) {
479 // Use of assumptions is context-sensitive. If we don't have a context, we
481 if (!Q.AT || !Q.CxtI)
484 unsigned BitWidth = KnownZero.getBitWidth();
486 Function *F = const_cast<Function*>(Q.CxtI->getParent()->getParent());
487 for (auto &CI : Q.AT->assumptions(F)) {
489 if (Q.ExclInvs.count(I))
492 if (match(I, m_Intrinsic<Intrinsic::assume>(m_Specific(V))) &&
493 isValidAssumeForContext(I, Q, DL)) {
494 assert(BitWidth == 1 && "assume operand is not i1?");
495 KnownZero.clearAllBits();
496 KnownOne.setAllBits();
501 auto m_V = m_CombineOr(m_Specific(V),
502 m_CombineOr(m_PtrToInt(m_Specific(V)),
503 m_BitCast(m_Specific(V))));
505 CmpInst::Predicate Pred;
508 if (match(I, m_Intrinsic<Intrinsic::assume>(
509 m_c_ICmp(Pred, m_V, m_Value(A)))) &&
510 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
511 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
512 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
513 KnownZero |= RHSKnownZero;
514 KnownOne |= RHSKnownOne;
516 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
517 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A)))) &&
518 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
519 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
520 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
521 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
522 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
524 // For those bits in the mask that are known to be one, we can propagate
525 // known bits from the RHS to V.
526 KnownZero |= RHSKnownZero & MaskKnownOne;
527 KnownOne |= RHSKnownOne & MaskKnownOne;
528 // assume(~(v & b) = a)
529 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
530 m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
532 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
533 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
534 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
535 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
536 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
538 // For those bits in the mask that are known to be one, we can propagate
539 // inverted known bits from the RHS to V.
540 KnownZero |= RHSKnownOne & MaskKnownOne;
541 KnownOne |= RHSKnownZero & MaskKnownOne;
543 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
544 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A)))) &&
545 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
546 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
547 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
548 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
549 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
551 // For those bits in B that are known to be zero, we can propagate known
552 // bits from the RHS to V.
553 KnownZero |= RHSKnownZero & BKnownZero;
554 KnownOne |= RHSKnownOne & BKnownZero;
555 // assume(~(v | b) = a)
556 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
557 m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
559 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
560 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
561 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
562 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
563 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
565 // For those bits in B that are known to be zero, we can propagate
566 // inverted known bits from the RHS to V.
567 KnownZero |= RHSKnownOne & BKnownZero;
568 KnownOne |= RHSKnownZero & BKnownZero;
570 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
571 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A)))) &&
572 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
573 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
574 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
575 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
576 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
578 // For those bits in B that are known to be zero, we can propagate known
579 // bits from the RHS to V. For those bits in B that are known to be one,
580 // we can propagate inverted known bits from the RHS to V.
581 KnownZero |= RHSKnownZero & BKnownZero;
582 KnownOne |= RHSKnownOne & BKnownZero;
583 KnownZero |= RHSKnownOne & BKnownOne;
584 KnownOne |= RHSKnownZero & BKnownOne;
585 // assume(~(v ^ b) = a)
586 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
587 m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
589 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
590 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
591 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
592 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
593 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
595 // For those bits in B that are known to be zero, we can propagate
596 // inverted known bits from the RHS to V. For those bits in B that are
597 // known to be one, we can propagate known bits from the RHS to V.
598 KnownZero |= RHSKnownOne & BKnownZero;
599 KnownOne |= RHSKnownZero & BKnownZero;
600 KnownZero |= RHSKnownZero & BKnownOne;
601 KnownOne |= RHSKnownOne & BKnownOne;
602 // assume(v << c = a)
603 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
604 m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
606 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
607 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
608 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
609 // For those bits in RHS that are known, we can propagate them to known
610 // bits in V shifted to the right by C.
611 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
612 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
613 // assume(~(v << c) = a)
614 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
615 m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
617 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
618 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
619 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
620 // For those bits in RHS that are known, we can propagate them inverted
621 // to known bits in V shifted to the right by C.
622 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
623 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
624 // assume(v >> c = a)
625 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
626 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
630 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
631 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
632 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
633 // For those bits in RHS that are known, we can propagate them to known
634 // bits in V shifted to the right by C.
635 KnownZero |= RHSKnownZero << C->getZExtValue();
636 KnownOne |= RHSKnownOne << C->getZExtValue();
637 // assume(~(v >> c) = a)
638 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
639 m_c_ICmp(Pred, m_Not(m_CombineOr(
640 m_LShr(m_V, m_ConstantInt(C)),
641 m_AShr(m_V, m_ConstantInt(C)))),
643 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
644 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
645 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
646 // For those bits in RHS that are known, we can propagate them inverted
647 // to known bits in V shifted to the right by C.
648 KnownZero |= RHSKnownOne << C->getZExtValue();
649 KnownOne |= RHSKnownZero << C->getZExtValue();
650 // assume(v >=_s c) where c is non-negative
651 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
652 m_ICmp(Pred, m_V, m_Value(A)))) &&
653 Pred == ICmpInst::ICMP_SGE &&
654 isValidAssumeForContext(I, Q, DL)) {
655 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
656 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
658 if (RHSKnownZero.isNegative()) {
659 // We know that the sign bit is zero.
660 KnownZero |= APInt::getSignBit(BitWidth);
662 // assume(v >_s c) where c is at least -1.
663 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
664 m_ICmp(Pred, m_V, m_Value(A)))) &&
665 Pred == ICmpInst::ICMP_SGT &&
666 isValidAssumeForContext(I, Q, DL)) {
667 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
668 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
670 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
671 // We know that the sign bit is zero.
672 KnownZero |= APInt::getSignBit(BitWidth);
674 // assume(v <=_s c) where c is negative
675 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
676 m_ICmp(Pred, m_V, m_Value(A)))) &&
677 Pred == ICmpInst::ICMP_SLE &&
678 isValidAssumeForContext(I, Q, DL)) {
679 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
680 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
682 if (RHSKnownOne.isNegative()) {
683 // We know that the sign bit is one.
684 KnownOne |= APInt::getSignBit(BitWidth);
686 // assume(v <_s c) where c is non-positive
687 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
688 m_ICmp(Pred, m_V, m_Value(A)))) &&
689 Pred == ICmpInst::ICMP_SLT &&
690 isValidAssumeForContext(I, Q, DL)) {
691 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
692 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
694 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
695 // We know that the sign bit is one.
696 KnownOne |= APInt::getSignBit(BitWidth);
699 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
700 m_ICmp(Pred, m_V, m_Value(A)))) &&
701 Pred == ICmpInst::ICMP_ULE &&
702 isValidAssumeForContext(I, Q, DL)) {
703 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
704 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
706 // Whatever high bits in c are zero are known to be zero.
708 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
710 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
711 m_ICmp(Pred, m_V, m_Value(A)))) &&
712 Pred == ICmpInst::ICMP_ULT &&
713 isValidAssumeForContext(I, Q, DL)) {
714 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
715 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
717 // Whatever high bits in c are zero are known to be zero (if c is a power
718 // of 2, then one more).
719 if (isKnownToBeAPowerOfTwo(A, false, Depth+1, Query(Q, I)))
721 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
724 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
729 /// Determine which bits of V are known to be either zero or one and return
730 /// them in the KnownZero/KnownOne bit sets.
732 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
733 /// we cannot optimize based on the assumption that it is zero without changing
734 /// it to be an explicit zero. If we don't change it to zero, other code could
735 /// optimized based on the contradictory assumption that it is non-zero.
736 /// Because instcombine aggressively folds operations with undef args anyway,
737 /// this won't lose us code quality.
739 /// This function is defined on values with integer type, values with pointer
740 /// type (but only if TD is non-null), and vectors of integers. In the case
741 /// where V is a vector, known zero, and known one values are the
742 /// same width as the vector element, and the bit is set only if it is true
743 /// for all of the elements in the vector.
744 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
745 const DataLayout *TD, unsigned Depth,
747 assert(V && "No Value?");
748 assert(Depth <= MaxDepth && "Limit Search Depth");
749 unsigned BitWidth = KnownZero.getBitWidth();
751 assert((V->getType()->isIntOrIntVectorTy() ||
752 V->getType()->getScalarType()->isPointerTy()) &&
753 "Not integer or pointer type!");
755 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
756 (!V->getType()->isIntOrIntVectorTy() ||
757 V->getType()->getScalarSizeInBits() == BitWidth) &&
758 KnownZero.getBitWidth() == BitWidth &&
759 KnownOne.getBitWidth() == BitWidth &&
760 "V, KnownOne and KnownZero should have same BitWidth");
762 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
763 // We know all of the bits for a constant!
764 KnownOne = CI->getValue();
765 KnownZero = ~KnownOne;
768 // Null and aggregate-zero are all-zeros.
769 if (isa<ConstantPointerNull>(V) ||
770 isa<ConstantAggregateZero>(V)) {
771 KnownOne.clearAllBits();
772 KnownZero = APInt::getAllOnesValue(BitWidth);
775 // Handle a constant vector by taking the intersection of the known bits of
776 // each element. There is no real need to handle ConstantVector here, because
777 // we don't handle undef in any particularly useful way.
778 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
779 // We know that CDS must be a vector of integers. Take the intersection of
781 KnownZero.setAllBits(); KnownOne.setAllBits();
782 APInt Elt(KnownZero.getBitWidth(), 0);
783 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
784 Elt = CDS->getElementAsInteger(i);
791 // The address of an aligned GlobalValue has trailing zeros.
792 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
793 unsigned Align = GV->getAlignment();
794 if (Align == 0 && TD) {
795 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
796 Type *ObjectType = GVar->getType()->getElementType();
797 if (ObjectType->isSized()) {
798 // If the object is defined in the current Module, we'll be giving
799 // it the preferred alignment. Otherwise, we have to assume that it
800 // may only have the minimum ABI alignment.
801 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
802 Align = TD->getPreferredAlignment(GVar);
804 Align = TD->getABITypeAlignment(ObjectType);
809 KnownZero = APInt::getLowBitsSet(BitWidth,
810 countTrailingZeros(Align));
812 KnownZero.clearAllBits();
813 KnownOne.clearAllBits();
816 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
817 // the bits of its aliasee.
818 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
819 if (GA->mayBeOverridden()) {
820 KnownZero.clearAllBits(); KnownOne.clearAllBits();
822 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1, Q);
827 if (Argument *A = dyn_cast<Argument>(V)) {
828 unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
830 if (!Align && TD && A->hasStructRetAttr()) {
831 // An sret parameter has at least the ABI alignment of the return type.
832 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
833 if (EltTy->isSized())
834 Align = TD->getABITypeAlignment(EltTy);
838 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
840 // Don't give up yet... there might be an assumption that provides more
842 computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
846 // Start out not knowing anything.
847 KnownZero.clearAllBits(); KnownOne.clearAllBits();
849 if (Depth == MaxDepth)
850 return; // Limit search depth.
852 // Check whether a nearby assume intrinsic can determine some known bits.
853 computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
855 Operator *I = dyn_cast<Operator>(V);
858 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
859 switch (I->getOpcode()) {
861 case Instruction::Load:
862 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
863 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
865 case Instruction::And: {
866 // If either the LHS or the RHS are Zero, the result is zero.
867 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
868 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
870 // Output known-1 bits are only known if set in both the LHS & RHS.
871 KnownOne &= KnownOne2;
872 // Output known-0 are known to be clear if zero in either the LHS | RHS.
873 KnownZero |= KnownZero2;
876 case Instruction::Or: {
877 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
878 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
880 // Output known-0 bits are only known if clear in both the LHS & RHS.
881 KnownZero &= KnownZero2;
882 // Output known-1 are known to be set if set in either the LHS | RHS.
883 KnownOne |= KnownOne2;
886 case Instruction::Xor: {
887 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
888 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
890 // Output known-0 bits are known if clear or set in both the LHS & RHS.
891 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
892 // Output known-1 are known to be set if set in only one of the LHS, RHS.
893 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
894 KnownZero = KnownZeroOut;
897 case Instruction::Mul: {
898 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
899 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
900 KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
904 case Instruction::UDiv: {
905 // For the purposes of computing leading zeros we can conservatively
906 // treat a udiv as a logical right shift by the power of 2 known to
907 // be less than the denominator.
908 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
909 unsigned LeadZ = KnownZero2.countLeadingOnes();
911 KnownOne2.clearAllBits();
912 KnownZero2.clearAllBits();
913 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
914 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
915 if (RHSUnknownLeadingOnes != BitWidth)
916 LeadZ = std::min(BitWidth,
917 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
919 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
922 case Instruction::Select:
923 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
924 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
926 // Only known if known in both the LHS and RHS.
927 KnownOne &= KnownOne2;
928 KnownZero &= KnownZero2;
930 case Instruction::FPTrunc:
931 case Instruction::FPExt:
932 case Instruction::FPToUI:
933 case Instruction::FPToSI:
934 case Instruction::SIToFP:
935 case Instruction::UIToFP:
936 break; // Can't work with floating point.
937 case Instruction::PtrToInt:
938 case Instruction::IntToPtr:
939 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
940 // We can't handle these if we don't know the pointer size.
942 // FALL THROUGH and handle them the same as zext/trunc.
943 case Instruction::ZExt:
944 case Instruction::Trunc: {
945 Type *SrcTy = I->getOperand(0)->getType();
947 unsigned SrcBitWidth;
948 // Note that we handle pointer operands here because of inttoptr/ptrtoint
949 // which fall through here.
951 SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
953 SrcBitWidth = SrcTy->getScalarSizeInBits();
954 if (!SrcBitWidth) break;
957 assert(SrcBitWidth && "SrcBitWidth can't be zero");
958 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
959 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
960 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
961 KnownZero = KnownZero.zextOrTrunc(BitWidth);
962 KnownOne = KnownOne.zextOrTrunc(BitWidth);
963 // Any top bits are known to be zero.
964 if (BitWidth > SrcBitWidth)
965 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
968 case Instruction::BitCast: {
969 Type *SrcTy = I->getOperand(0)->getType();
970 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
971 // TODO: For now, not handling conversions like:
972 // (bitcast i64 %x to <2 x i32>)
973 !I->getType()->isVectorTy()) {
974 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
979 case Instruction::SExt: {
980 // Compute the bits in the result that are not present in the input.
981 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
983 KnownZero = KnownZero.trunc(SrcBitWidth);
984 KnownOne = KnownOne.trunc(SrcBitWidth);
985 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
986 KnownZero = KnownZero.zext(BitWidth);
987 KnownOne = KnownOne.zext(BitWidth);
989 // If the sign bit of the input is known set or clear, then we know the
990 // top bits of the result.
991 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
992 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
993 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
994 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
997 case Instruction::Shl:
998 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
999 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1001 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1002 KnownZero <<= ShiftAmt;
1003 KnownOne <<= ShiftAmt;
1004 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
1008 case Instruction::LShr:
1009 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1010 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1011 // Compute the new bits that are at the top now.
1012 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1014 // Unsigned shift right.
1015 computeKnownBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1, Q);
1016 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1017 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1018 // high bits known zero.
1019 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
1023 case Instruction::AShr:
1024 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1025 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1026 // Compute the new bits that are at the top now.
1027 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
1029 // Signed shift right.
1030 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1031 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1032 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1034 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1035 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
1036 KnownZero |= HighBits;
1037 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
1038 KnownOne |= HighBits;
1042 case Instruction::Sub: {
1043 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1044 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1045 KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
1049 case Instruction::Add: {
1050 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1051 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1052 KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
1056 case Instruction::SRem:
1057 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1058 APInt RA = Rem->getValue().abs();
1059 if (RA.isPowerOf2()) {
1060 APInt LowBits = RA - 1;
1061 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD,
1064 // The low bits of the first operand are unchanged by the srem.
1065 KnownZero = KnownZero2 & LowBits;
1066 KnownOne = KnownOne2 & LowBits;
1068 // If the first operand is non-negative or has all low bits zero, then
1069 // the upper bits are all zero.
1070 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1071 KnownZero |= ~LowBits;
1073 // If the first operand is negative and not all low bits are zero, then
1074 // the upper bits are all one.
1075 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1076 KnownOne |= ~LowBits;
1078 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1082 // The sign bit is the LHS's sign bit, except when the result of the
1083 // remainder is zero.
1084 if (KnownZero.isNonNegative()) {
1085 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1086 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
1088 // If it's known zero, our sign bit is also zero.
1089 if (LHSKnownZero.isNegative())
1090 KnownZero.setBit(BitWidth - 1);
1094 case Instruction::URem: {
1095 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1096 APInt RA = Rem->getValue();
1097 if (RA.isPowerOf2()) {
1098 APInt LowBits = (RA - 1);
1099 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
1101 KnownZero |= ~LowBits;
1102 KnownOne &= LowBits;
1107 // Since the result is less than or equal to either operand, any leading
1108 // zero bits in either operand must also exist in the result.
1109 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1110 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
1112 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1113 KnownZero2.countLeadingOnes());
1114 KnownOne.clearAllBits();
1115 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1119 case Instruction::Alloca: {
1120 AllocaInst *AI = cast<AllocaInst>(V);
1121 unsigned Align = AI->getAlignment();
1122 if (Align == 0 && TD)
1123 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1126 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1129 case Instruction::GetElementPtr: {
1130 // Analyze all of the subscripts of this getelementptr instruction
1131 // to determine if we can prove known low zero bits.
1132 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1133 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
1135 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1137 gep_type_iterator GTI = gep_type_begin(I);
1138 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1139 Value *Index = I->getOperand(i);
1140 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1141 // Handle struct member offset arithmetic.
1147 // Handle case when index is vector zeroinitializer
1148 Constant *CIndex = cast<Constant>(Index);
1149 if (CIndex->isZeroValue())
1152 if (CIndex->getType()->isVectorTy())
1153 Index = CIndex->getSplatValue();
1155 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1156 const StructLayout *SL = TD->getStructLayout(STy);
1157 uint64_t Offset = SL->getElementOffset(Idx);
1158 TrailZ = std::min<unsigned>(TrailZ,
1159 countTrailingZeros(Offset));
1161 // Handle array index arithmetic.
1162 Type *IndexedTy = GTI.getIndexedType();
1163 if (!IndexedTy->isSized()) {
1167 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1168 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
1169 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1170 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1, Q);
1171 TrailZ = std::min(TrailZ,
1172 unsigned(countTrailingZeros(TypeSize) +
1173 LocalKnownZero.countTrailingOnes()));
1177 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1180 case Instruction::PHI: {
1181 PHINode *P = cast<PHINode>(I);
1182 // Handle the case of a simple two-predecessor recurrence PHI.
1183 // There's a lot more that could theoretically be done here, but
1184 // this is sufficient to catch some interesting cases.
1185 if (P->getNumIncomingValues() == 2) {
1186 for (unsigned i = 0; i != 2; ++i) {
1187 Value *L = P->getIncomingValue(i);
1188 Value *R = P->getIncomingValue(!i);
1189 Operator *LU = dyn_cast<Operator>(L);
1192 unsigned Opcode = LU->getOpcode();
1193 // Check for operations that have the property that if
1194 // both their operands have low zero bits, the result
1195 // will have low zero bits.
1196 if (Opcode == Instruction::Add ||
1197 Opcode == Instruction::Sub ||
1198 Opcode == Instruction::And ||
1199 Opcode == Instruction::Or ||
1200 Opcode == Instruction::Mul) {
1201 Value *LL = LU->getOperand(0);
1202 Value *LR = LU->getOperand(1);
1203 // Find a recurrence.
1210 // Ok, we have a PHI of the form L op= R. Check for low
1212 computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1, Q);
1214 // We need to take the minimum number of known bits
1215 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1216 computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1, Q);
1218 KnownZero = APInt::getLowBitsSet(BitWidth,
1219 std::min(KnownZero2.countTrailingOnes(),
1220 KnownZero3.countTrailingOnes()));
1226 // Unreachable blocks may have zero-operand PHI nodes.
1227 if (P->getNumIncomingValues() == 0)
1230 // Otherwise take the unions of the known bit sets of the operands,
1231 // taking conservative care to avoid excessive recursion.
1232 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1233 // Skip if every incoming value references to ourself.
1234 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1237 KnownZero = APInt::getAllOnesValue(BitWidth);
1238 KnownOne = APInt::getAllOnesValue(BitWidth);
1239 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1240 // Skip direct self references.
1241 if (P->getIncomingValue(i) == P) continue;
1243 KnownZero2 = APInt(BitWidth, 0);
1244 KnownOne2 = APInt(BitWidth, 0);
1245 // Recurse, but cap the recursion to one level, because we don't
1246 // want to waste time spinning around in loops.
1247 computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
1249 KnownZero &= KnownZero2;
1250 KnownOne &= KnownOne2;
1251 // If all bits have been ruled out, there's no need to check
1253 if (!KnownZero && !KnownOne)
1259 case Instruction::Call:
1260 case Instruction::Invoke:
1261 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1262 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1263 // If a range metadata is attached to this IntrinsicInst, intersect the
1264 // explicit range specified by the metadata and the implicit range of
1266 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1267 switch (II->getIntrinsicID()) {
1269 case Intrinsic::ctlz:
1270 case Intrinsic::cttz: {
1271 unsigned LowBits = Log2_32(BitWidth)+1;
1272 // If this call is undefined for 0, the result will be less than 2^n.
1273 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1275 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1278 case Intrinsic::ctpop: {
1279 unsigned LowBits = Log2_32(BitWidth)+1;
1280 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1283 case Intrinsic::x86_sse42_crc32_64_64:
1284 KnownZero |= APInt::getHighBitsSet(64, 32);
1289 case Instruction::ExtractValue:
1290 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1291 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1292 if (EVI->getNumIndices() != 1) break;
1293 if (EVI->getIndices()[0] == 0) {
1294 switch (II->getIntrinsicID()) {
1296 case Intrinsic::uadd_with_overflow:
1297 case Intrinsic::sadd_with_overflow:
1298 computeKnownBitsAddSub(true, II->getArgOperand(0),
1299 II->getArgOperand(1), false, KnownZero,
1300 KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
1302 case Intrinsic::usub_with_overflow:
1303 case Intrinsic::ssub_with_overflow:
1304 computeKnownBitsAddSub(false, II->getArgOperand(0),
1305 II->getArgOperand(1), false, KnownZero,
1306 KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
1308 case Intrinsic::umul_with_overflow:
1309 case Intrinsic::smul_with_overflow:
1310 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
1311 false, KnownZero, KnownOne,
1312 KnownZero2, KnownOne2, TD, Depth, Q);
1319 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1322 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
1323 /// one. Convenience wrapper around computeKnownBits.
1324 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1325 const DataLayout *TD, unsigned Depth,
1327 unsigned BitWidth = getBitWidth(V->getType(), TD);
1333 APInt ZeroBits(BitWidth, 0);
1334 APInt OneBits(BitWidth, 0);
1335 computeKnownBits(V, ZeroBits, OneBits, TD, Depth, Q);
1336 KnownOne = OneBits[BitWidth - 1];
1337 KnownZero = ZeroBits[BitWidth - 1];
1340 /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have exactly one
1341 /// bit set when defined. For vectors return true if every element is known to
1342 /// be a power of two when defined. Supports values with integer or pointer
1343 /// types and vectors of integers.
1344 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1346 if (Constant *C = dyn_cast<Constant>(V)) {
1347 if (C->isNullValue())
1349 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1350 return CI->getValue().isPowerOf2();
1351 // TODO: Handle vector constants.
1354 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1355 // it is shifted off the end then the result is undefined.
1356 if (match(V, m_Shl(m_One(), m_Value())))
1359 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1360 // bottom. If it is shifted off the bottom then the result is undefined.
1361 if (match(V, m_LShr(m_SignBit(), m_Value())))
1364 // The remaining tests are all recursive, so bail out if we hit the limit.
1365 if (Depth++ == MaxDepth)
1368 Value *X = nullptr, *Y = nullptr;
1369 // A shift of a power of two is a power of two or zero.
1370 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1371 match(V, m_Shr(m_Value(X), m_Value()))))
1372 return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q);
1374 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1375 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1377 if (SelectInst *SI = dyn_cast<SelectInst>(V))
1379 isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1380 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1382 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1383 // A power of two and'd with anything is a power of two or zero.
1384 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q) ||
1385 isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth, Q))
1387 // X & (-X) is always a power of two or zero.
1388 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1393 // Adding a power-of-two or zero to the same power-of-two or zero yields
1394 // either the original power-of-two, a larger power-of-two or zero.
1395 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1396 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1397 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1398 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1399 match(X, m_And(m_Value(), m_Specific(Y))))
1400 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1402 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1403 match(Y, m_And(m_Value(), m_Specific(X))))
1404 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1407 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1408 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1409 computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth, Q);
1411 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1412 computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth, Q);
1413 // If i8 V is a power of two or zero:
1414 // ZeroBits: 1 1 1 0 1 1 1 1
1415 // ~ZeroBits: 0 0 0 1 0 0 0 0
1416 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1417 // If OrZero isn't set, we cannot give back a zero result.
1418 // Make sure either the LHS or RHS has a bit set.
1419 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1424 // An exact divide or right shift can only shift off zero bits, so the result
1425 // is a power of two only if the first operand is a power of two and not
1426 // copying a sign bit (sdiv int_min, 2).
1427 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1428 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1429 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1436 /// \brief Test whether a GEP's result is known to be non-null.
1438 /// Uses properties inherent in a GEP to try to determine whether it is known
1441 /// Currently this routine does not support vector GEPs.
1442 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
1443 unsigned Depth, const Query &Q) {
1444 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1447 // FIXME: Support vector-GEPs.
1448 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1450 // If the base pointer is non-null, we cannot walk to a null address with an
1451 // inbounds GEP in address space zero.
1452 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
1455 // Past this, if we don't have DataLayout, we can't do much.
1459 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1460 // If so, then the GEP cannot produce a null pointer, as doing so would
1461 // inherently violate the inbounds contract within address space zero.
1462 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1463 GTI != GTE; ++GTI) {
1464 // Struct types are easy -- they must always be indexed by a constant.
1465 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1466 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1467 unsigned ElementIdx = OpC->getZExtValue();
1468 const StructLayout *SL = DL->getStructLayout(STy);
1469 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1470 if (ElementOffset > 0)
1475 // If we have a zero-sized type, the index doesn't matter. Keep looping.
1476 if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
1479 // Fast path the constant operand case both for efficiency and so we don't
1480 // increment Depth when just zipping down an all-constant GEP.
1481 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1487 // We post-increment Depth here because while isKnownNonZero increments it
1488 // as well, when we pop back up that increment won't persist. We don't want
1489 // to recurse 10k times just because we have 10k GEP operands. We don't
1490 // bail completely out because we want to handle constant GEPs regardless
1492 if (Depth++ >= MaxDepth)
1495 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
1502 /// isKnownNonZero - Return true if the given value is known to be non-zero
1503 /// when defined. For vectors return true if every element is known to be
1504 /// non-zero when defined. Supports values with integer or pointer type and
1505 /// vectors of integers.
1506 bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
1508 if (Constant *C = dyn_cast<Constant>(V)) {
1509 if (C->isNullValue())
1511 if (isa<ConstantInt>(C))
1512 // Must be non-zero due to null test above.
1514 // TODO: Handle vectors
1518 // The remaining tests are all recursive, so bail out if we hit the limit.
1519 if (Depth++ >= MaxDepth)
1522 // Check for pointer simplifications.
1523 if (V->getType()->isPointerTy()) {
1524 if (isKnownNonNull(V))
1526 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1527 if (isGEPKnownNonNull(GEP, TD, Depth, Q))
1531 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
1533 // X | Y != 0 if X != 0 or Y != 0.
1534 Value *X = nullptr, *Y = nullptr;
1535 if (match(V, m_Or(m_Value(X), m_Value(Y))))
1536 return isKnownNonZero(X, TD, Depth, Q) ||
1537 isKnownNonZero(Y, TD, Depth, Q);
1539 // ext X != 0 if X != 0.
1540 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1541 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
1543 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
1544 // if the lowest bit is shifted off the end.
1545 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1546 // shl nuw can't remove any non-zero bits.
1547 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1548 if (BO->hasNoUnsignedWrap())
1549 return isKnownNonZero(X, TD, Depth, Q);
1551 APInt KnownZero(BitWidth, 0);
1552 APInt KnownOne(BitWidth, 0);
1553 computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
1557 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
1558 // defined if the sign bit is shifted off the end.
1559 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1560 // shr exact can only shift out zero bits.
1561 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1563 return isKnownNonZero(X, TD, Depth, Q);
1565 bool XKnownNonNegative, XKnownNegative;
1566 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
1570 // div exact can only produce a zero if the dividend is zero.
1571 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1572 return isKnownNonZero(X, TD, Depth, Q);
1575 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1576 bool XKnownNonNegative, XKnownNegative;
1577 bool YKnownNonNegative, YKnownNegative;
1578 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
1579 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
1581 // If X and Y are both non-negative (as signed values) then their sum is not
1582 // zero unless both X and Y are zero.
1583 if (XKnownNonNegative && YKnownNonNegative)
1584 if (isKnownNonZero(X, TD, Depth, Q) ||
1585 isKnownNonZero(Y, TD, Depth, Q))
1588 // If X and Y are both negative (as signed values) then their sum is not
1589 // zero unless both X and Y equal INT_MIN.
1590 if (BitWidth && XKnownNegative && YKnownNegative) {
1591 APInt KnownZero(BitWidth, 0);
1592 APInt KnownOne(BitWidth, 0);
1593 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1594 // The sign bit of X is set. If some other bit is set then X is not equal
1596 computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
1597 if ((KnownOne & Mask) != 0)
1599 // The sign bit of Y is set. If some other bit is set then Y is not equal
1601 computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
1602 if ((KnownOne & Mask) != 0)
1606 // The sum of a non-negative number and a power of two is not zero.
1607 if (XKnownNonNegative &&
1608 isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
1610 if (YKnownNonNegative &&
1611 isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
1615 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1616 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1617 // If X and Y are non-zero then so is X * Y as long as the multiplication
1618 // does not overflow.
1619 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1620 isKnownNonZero(X, TD, Depth, Q) &&
1621 isKnownNonZero(Y, TD, Depth, Q))
1624 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1625 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1626 if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
1627 isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
1631 if (!BitWidth) return false;
1632 APInt KnownZero(BitWidth, 0);
1633 APInt KnownOne(BitWidth, 0);
1634 computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1635 return KnownOne != 0;
1638 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1639 /// this predicate to simplify operations downstream. Mask is known to be zero
1640 /// for bits that V cannot have.
1642 /// This function is defined on values with integer type, values with pointer
1643 /// type (but only if TD is non-null), and vectors of integers. In the case
1644 /// where V is a vector, the mask, known zero, and known one values are the
1645 /// same width as the vector element, and the bit is set only if it is true
1646 /// for all of the elements in the vector.
1647 bool MaskedValueIsZero(Value *V, const APInt &Mask,
1648 const DataLayout *TD, unsigned Depth,
1650 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1651 computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1652 return (KnownZero & Mask) == Mask;
1657 /// ComputeNumSignBits - Return the number of times the sign bit of the
1658 /// register is replicated into the other bits. We know that at least 1 bit
1659 /// is always equal to the sign bit (itself), but other cases can give us
1660 /// information. For example, immediately after an "ashr X, 2", we know that
1661 /// the top 3 bits are all equal to each other, so we return 3.
1663 /// 'Op' must have a scalar integer type.
1665 unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
1666 unsigned Depth, const Query &Q) {
1667 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
1668 "ComputeNumSignBits requires a DataLayout object to operate "
1669 "on non-integer values!");
1670 Type *Ty = V->getType();
1671 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1672 Ty->getScalarSizeInBits();
1674 unsigned FirstAnswer = 1;
1676 // Note that ConstantInt is handled by the general computeKnownBits case
1680 return 1; // Limit search depth.
1682 Operator *U = dyn_cast<Operator>(V);
1683 switch (Operator::getOpcode(V)) {
1685 case Instruction::SExt:
1686 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1687 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
1689 case Instruction::AShr: {
1690 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1691 // ashr X, C -> adds C sign bits. Vectors too.
1693 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1694 Tmp += ShAmt->getZExtValue();
1695 if (Tmp > TyBits) Tmp = TyBits;
1699 case Instruction::Shl: {
1701 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1702 // shl destroys sign bits.
1703 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1704 Tmp2 = ShAmt->getZExtValue();
1705 if (Tmp2 >= TyBits || // Bad shift.
1706 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1711 case Instruction::And:
1712 case Instruction::Or:
1713 case Instruction::Xor: // NOT is handled here.
1714 // Logical binary ops preserve the number of sign bits at the worst.
1715 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1717 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1718 FirstAnswer = std::min(Tmp, Tmp2);
1719 // We computed what we know about the sign bits as our first
1720 // answer. Now proceed to the generic code that uses
1721 // computeKnownBits, and pick whichever answer is better.
1725 case Instruction::Select:
1726 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1727 if (Tmp == 1) return 1; // Early out.
1728 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
1729 return std::min(Tmp, Tmp2);
1731 case Instruction::Add:
1732 // Add can have at most one carry bit. Thus we know that the output
1733 // is, at worst, one more bit than the inputs.
1734 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1735 if (Tmp == 1) return 1; // Early out.
1737 // Special case decrementing a value (ADD X, -1):
1738 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
1739 if (CRHS->isAllOnesValue()) {
1740 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1741 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1743 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1745 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1748 // If we are subtracting one from a positive number, there is no carry
1749 // out of the result.
1750 if (KnownZero.isNegative())
1754 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1755 if (Tmp2 == 1) return 1;
1756 return std::min(Tmp, Tmp2)-1;
1758 case Instruction::Sub:
1759 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1760 if (Tmp2 == 1) return 1;
1763 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1764 if (CLHS->isNullValue()) {
1765 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1766 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
1767 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1769 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1772 // If the input is known to be positive (the sign bit is known clear),
1773 // the output of the NEG has the same number of sign bits as the input.
1774 if (KnownZero.isNegative())
1777 // Otherwise, we treat this like a SUB.
1780 // Sub can have at most one carry bit. Thus we know that the output
1781 // is, at worst, one more bit than the inputs.
1782 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1783 if (Tmp == 1) return 1; // Early out.
1784 return std::min(Tmp, Tmp2)-1;
1786 case Instruction::PHI: {
1787 PHINode *PN = cast<PHINode>(U);
1788 // Don't analyze large in-degree PHIs.
1789 if (PN->getNumIncomingValues() > 4) break;
1791 // Take the minimum of all incoming values. This can't infinitely loop
1792 // because of our depth threshold.
1793 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
1794 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1795 if (Tmp == 1) return Tmp;
1797 ComputeNumSignBits(PN->getIncomingValue(i), TD,
1803 case Instruction::Trunc:
1804 // FIXME: it's tricky to do anything useful for this, but it is an important
1805 // case for targets like X86.
1809 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1810 // use this information.
1811 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1813 computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1815 if (KnownZero.isNegative()) { // sign bit is 0
1817 } else if (KnownOne.isNegative()) { // sign bit is 1;
1824 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1825 // the number of identical bits in the top of the input value.
1827 Mask <<= Mask.getBitWidth()-TyBits;
1828 // Return # leading zeros. We use 'min' here in case Val was zero before
1829 // shifting. We don't want to return '64' as for an i32 "0".
1830 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1833 /// ComputeMultiple - This function computes the integer multiple of Base that
1834 /// equals V. If successful, it returns true and returns the multiple in
1835 /// Multiple. If unsuccessful, it returns false. It looks
1836 /// through SExt instructions only if LookThroughSExt is true.
1837 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
1838 bool LookThroughSExt, unsigned Depth) {
1839 const unsigned MaxDepth = 6;
1841 assert(V && "No Value?");
1842 assert(Depth <= MaxDepth && "Limit Search Depth");
1843 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
1845 Type *T = V->getType();
1847 ConstantInt *CI = dyn_cast<ConstantInt>(V);
1857 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1858 Constant *BaseVal = ConstantInt::get(T, Base);
1859 if (CO && CO == BaseVal) {
1861 Multiple = ConstantInt::get(T, 1);
1865 if (CI && CI->getZExtValue() % Base == 0) {
1866 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1870 if (Depth == MaxDepth) return false; // Limit search depth.
1872 Operator *I = dyn_cast<Operator>(V);
1873 if (!I) return false;
1875 switch (I->getOpcode()) {
1877 case Instruction::SExt:
1878 if (!LookThroughSExt) return false;
1879 // otherwise fall through to ZExt
1880 case Instruction::ZExt:
1881 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1882 LookThroughSExt, Depth+1);
1883 case Instruction::Shl:
1884 case Instruction::Mul: {
1885 Value *Op0 = I->getOperand(0);
1886 Value *Op1 = I->getOperand(1);
1888 if (I->getOpcode() == Instruction::Shl) {
1889 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1890 if (!Op1CI) return false;
1891 // Turn Op0 << Op1 into Op0 * 2^Op1
1892 APInt Op1Int = Op1CI->getValue();
1893 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
1894 APInt API(Op1Int.getBitWidth(), 0);
1895 API.setBit(BitToSet);
1896 Op1 = ConstantInt::get(V->getContext(), API);
1899 Value *Mul0 = nullptr;
1900 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1901 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1902 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1903 if (Op1C->getType()->getPrimitiveSizeInBits() <
1904 MulC->getType()->getPrimitiveSizeInBits())
1905 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1906 if (Op1C->getType()->getPrimitiveSizeInBits() >
1907 MulC->getType()->getPrimitiveSizeInBits())
1908 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1910 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1911 Multiple = ConstantExpr::getMul(MulC, Op1C);
1915 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1916 if (Mul0CI->getValue() == 1) {
1917 // V == Base * Op1, so return Op1
1923 Value *Mul1 = nullptr;
1924 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1925 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1926 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1927 if (Op0C->getType()->getPrimitiveSizeInBits() <
1928 MulC->getType()->getPrimitiveSizeInBits())
1929 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1930 if (Op0C->getType()->getPrimitiveSizeInBits() >
1931 MulC->getType()->getPrimitiveSizeInBits())
1932 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1934 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1935 Multiple = ConstantExpr::getMul(MulC, Op0C);
1939 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1940 if (Mul1CI->getValue() == 1) {
1941 // V == Base * Op0, so return Op0
1949 // We could not determine if V is a multiple of Base.
1953 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
1954 /// value is never equal to -0.0.
1956 /// NOTE: this function will need to be revisited when we support non-default
1959 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1960 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1961 return !CFP->getValueAPF().isNegZero();
1964 return 1; // Limit search depth.
1966 const Operator *I = dyn_cast<Operator>(V);
1967 if (!I) return false;
1969 // Check if the nsz fast-math flag is set
1970 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
1971 if (FPO->hasNoSignedZeros())
1974 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1975 if (I->getOpcode() == Instruction::FAdd)
1976 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
1977 if (CFP->isNullValue())
1980 // sitofp and uitofp turn into +0.0 for zero.
1981 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1984 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1985 // sqrt(-0.0) = -0.0, no other negative results are possible.
1986 if (II->getIntrinsicID() == Intrinsic::sqrt)
1987 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
1989 if (const CallInst *CI = dyn_cast<CallInst>(I))
1990 if (const Function *F = CI->getCalledFunction()) {
1991 if (F->isDeclaration()) {
1993 if (F->getName() == "abs") return true;
1994 // fabs[lf](x) != -0.0
1995 if (F->getName() == "fabs") return true;
1996 if (F->getName() == "fabsf") return true;
1997 if (F->getName() == "fabsl") return true;
1998 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1999 F->getName() == "sqrtl")
2000 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
2007 /// isBytewiseValue - If the specified value can be set by repeating the same
2008 /// byte in memory, return the i8 value that it is represented with. This is
2009 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2010 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2011 /// byte store (e.g. i16 0x1234), return null.
2012 Value *llvm::isBytewiseValue(Value *V) {
2013 // All byte-wide stores are splatable, even of arbitrary variables.
2014 if (V->getType()->isIntegerTy(8)) return V;
2016 // Handle 'null' ConstantArrayZero etc.
2017 if (Constant *C = dyn_cast<Constant>(V))
2018 if (C->isNullValue())
2019 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2021 // Constant float and double values can be handled as integer values if the
2022 // corresponding integer value is "byteable". An important case is 0.0.
2023 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2024 if (CFP->getType()->isFloatTy())
2025 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2026 if (CFP->getType()->isDoubleTy())
2027 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2028 // Don't handle long double formats, which have strange constraints.
2031 // We can handle constant integers that are power of two in size and a
2032 // multiple of 8 bits.
2033 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2034 unsigned Width = CI->getBitWidth();
2035 if (isPowerOf2_32(Width) && Width > 8) {
2036 // We can handle this value if the recursive binary decomposition is the
2037 // same at all levels.
2038 APInt Val = CI->getValue();
2040 while (Val.getBitWidth() != 8) {
2041 unsigned NextWidth = Val.getBitWidth()/2;
2042 Val2 = Val.lshr(NextWidth);
2043 Val2 = Val2.trunc(Val.getBitWidth()/2);
2044 Val = Val.trunc(Val.getBitWidth()/2);
2046 // If the top/bottom halves aren't the same, reject it.
2050 return ConstantInt::get(V->getContext(), Val);
2054 // A ConstantDataArray/Vector is splatable if all its members are equal and
2056 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2057 Value *Elt = CA->getElementAsConstant(0);
2058 Value *Val = isBytewiseValue(Elt);
2062 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2063 if (CA->getElementAsConstant(I) != Elt)
2069 // Conceptually, we could handle things like:
2070 // %a = zext i8 %X to i16
2071 // %b = shl i16 %a, 8
2072 // %c = or i16 %a, %b
2073 // but until there is an example that actually needs this, it doesn't seem
2074 // worth worrying about.
2079 // This is the recursive version of BuildSubAggregate. It takes a few different
2080 // arguments. Idxs is the index within the nested struct From that we are
2081 // looking at now (which is of type IndexedType). IdxSkip is the number of
2082 // indices from Idxs that should be left out when inserting into the resulting
2083 // struct. To is the result struct built so far, new insertvalue instructions
2085 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2086 SmallVectorImpl<unsigned> &Idxs,
2088 Instruction *InsertBefore) {
2089 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2091 // Save the original To argument so we can modify it
2093 // General case, the type indexed by Idxs is a struct
2094 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2095 // Process each struct element recursively
2098 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2102 // Couldn't find any inserted value for this index? Cleanup
2103 while (PrevTo != OrigTo) {
2104 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2105 PrevTo = Del->getAggregateOperand();
2106 Del->eraseFromParent();
2108 // Stop processing elements
2112 // If we successfully found a value for each of our subaggregates
2116 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2117 // the struct's elements had a value that was inserted directly. In the latter
2118 // case, perhaps we can't determine each of the subelements individually, but
2119 // we might be able to find the complete struct somewhere.
2121 // Find the value that is at that particular spot
2122 Value *V = FindInsertedValue(From, Idxs);
2127 // Insert the value in the new (sub) aggregrate
2128 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2129 "tmp", InsertBefore);
2132 // This helper takes a nested struct and extracts a part of it (which is again a
2133 // struct) into a new value. For example, given the struct:
2134 // { a, { b, { c, d }, e } }
2135 // and the indices "1, 1" this returns
2138 // It does this by inserting an insertvalue for each element in the resulting
2139 // struct, as opposed to just inserting a single struct. This will only work if
2140 // each of the elements of the substruct are known (ie, inserted into From by an
2141 // insertvalue instruction somewhere).
2143 // All inserted insertvalue instructions are inserted before InsertBefore
2144 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2145 Instruction *InsertBefore) {
2146 assert(InsertBefore && "Must have someplace to insert!");
2147 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2149 Value *To = UndefValue::get(IndexedType);
2150 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2151 unsigned IdxSkip = Idxs.size();
2153 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2156 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
2157 /// the scalar value indexed is already around as a register, for example if it
2158 /// were inserted directly into the aggregrate.
2160 /// If InsertBefore is not null, this function will duplicate (modified)
2161 /// insertvalues when a part of a nested struct is extracted.
2162 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2163 Instruction *InsertBefore) {
2164 // Nothing to index? Just return V then (this is useful at the end of our
2166 if (idx_range.empty())
2168 // We have indices, so V should have an indexable type.
2169 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2170 "Not looking at a struct or array?");
2171 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2172 "Invalid indices for type?");
2174 if (Constant *C = dyn_cast<Constant>(V)) {
2175 C = C->getAggregateElement(idx_range[0]);
2176 if (!C) return nullptr;
2177 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2180 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2181 // Loop the indices for the insertvalue instruction in parallel with the
2182 // requested indices
2183 const unsigned *req_idx = idx_range.begin();
2184 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2185 i != e; ++i, ++req_idx) {
2186 if (req_idx == idx_range.end()) {
2187 // We can't handle this without inserting insertvalues
2191 // The requested index identifies a part of a nested aggregate. Handle
2192 // this specially. For example,
2193 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2194 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2195 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2196 // This can be changed into
2197 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2198 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2199 // which allows the unused 0,0 element from the nested struct to be
2201 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2205 // This insert value inserts something else than what we are looking for.
2206 // See if the (aggregrate) value inserted into has the value we are
2207 // looking for, then.
2209 return FindInsertedValue(I->getAggregateOperand(), idx_range,
2212 // If we end up here, the indices of the insertvalue match with those
2213 // requested (though possibly only partially). Now we recursively look at
2214 // the inserted value, passing any remaining indices.
2215 return FindInsertedValue(I->getInsertedValueOperand(),
2216 makeArrayRef(req_idx, idx_range.end()),
2220 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2221 // If we're extracting a value from an aggregrate that was extracted from
2222 // something else, we can extract from that something else directly instead.
2223 // However, we will need to chain I's indices with the requested indices.
2225 // Calculate the number of indices required
2226 unsigned size = I->getNumIndices() + idx_range.size();
2227 // Allocate some space to put the new indices in
2228 SmallVector<unsigned, 5> Idxs;
2230 // Add indices from the extract value instruction
2231 Idxs.append(I->idx_begin(), I->idx_end());
2233 // Add requested indices
2234 Idxs.append(idx_range.begin(), idx_range.end());
2236 assert(Idxs.size() == size
2237 && "Number of indices added not correct?");
2239 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2241 // Otherwise, we don't know (such as, extracting from a function return value
2242 // or load instruction)
2246 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
2247 /// it can be expressed as a base pointer plus a constant offset. Return the
2248 /// base and offset to the caller.
2249 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2250 const DataLayout *DL) {
2251 // Without DataLayout, conservatively assume 64-bit offsets, which is
2252 // the widest we support.
2253 unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
2254 APInt ByteOffset(BitWidth, 0);
2256 if (Ptr->getType()->isVectorTy())
2259 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2261 APInt GEPOffset(BitWidth, 0);
2262 if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
2265 ByteOffset += GEPOffset;
2268 Ptr = GEP->getPointerOperand();
2269 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2270 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2271 Ptr = cast<Operator>(Ptr)->getOperand(0);
2272 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2273 if (GA->mayBeOverridden())
2275 Ptr = GA->getAliasee();
2280 Offset = ByteOffset.getSExtValue();
2285 /// getConstantStringInfo - This function computes the length of a
2286 /// null-terminated C string pointed to by V. If successful, it returns true
2287 /// and returns the string in Str. If unsuccessful, it returns false.
2288 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2289 uint64_t Offset, bool TrimAtNul) {
2292 // Look through bitcast instructions and geps.
2293 V = V->stripPointerCasts();
2295 // If the value is a GEP instructionor constant expression, treat it as an
2297 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2298 // Make sure the GEP has exactly three arguments.
2299 if (GEP->getNumOperands() != 3)
2302 // Make sure the index-ee is a pointer to array of i8.
2303 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2304 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
2305 if (!AT || !AT->getElementType()->isIntegerTy(8))
2308 // Check to make sure that the first operand of the GEP is an integer and
2309 // has value 0 so that we are sure we're indexing into the initializer.
2310 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2311 if (!FirstIdx || !FirstIdx->isZero())
2314 // If the second index isn't a ConstantInt, then this is a variable index
2315 // into the array. If this occurs, we can't say anything meaningful about
2317 uint64_t StartIdx = 0;
2318 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2319 StartIdx = CI->getZExtValue();
2322 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
2325 // The GEP instruction, constant or instruction, must reference a global
2326 // variable that is a constant and is initialized. The referenced constant
2327 // initializer is the array that we'll use for optimization.
2328 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2329 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2332 // Handle the all-zeros case
2333 if (GV->getInitializer()->isNullValue()) {
2334 // This is a degenerate case. The initializer is constant zero so the
2335 // length of the string must be zero.
2340 // Must be a Constant Array
2341 const ConstantDataArray *Array =
2342 dyn_cast<ConstantDataArray>(GV->getInitializer());
2343 if (!Array || !Array->isString())
2346 // Get the number of elements in the array
2347 uint64_t NumElts = Array->getType()->getArrayNumElements();
2349 // Start out with the entire array in the StringRef.
2350 Str = Array->getAsString();
2352 if (Offset > NumElts)
2355 // Skip over 'offset' bytes.
2356 Str = Str.substr(Offset);
2359 // Trim off the \0 and anything after it. If the array is not nul
2360 // terminated, we just return the whole end of string. The client may know
2361 // some other way that the string is length-bound.
2362 Str = Str.substr(0, Str.find('\0'));
2367 // These next two are very similar to the above, but also look through PHI
2369 // TODO: See if we can integrate these two together.
2371 /// GetStringLengthH - If we can compute the length of the string pointed to by
2372 /// the specified pointer, return 'len+1'. If we can't, return 0.
2373 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2374 // Look through noop bitcast instructions.
2375 V = V->stripPointerCasts();
2377 // If this is a PHI node, there are two cases: either we have already seen it
2379 if (PHINode *PN = dyn_cast<PHINode>(V)) {
2380 if (!PHIs.insert(PN))
2381 return ~0ULL; // already in the set.
2383 // If it was new, see if all the input strings are the same length.
2384 uint64_t LenSoFar = ~0ULL;
2385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2386 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2387 if (Len == 0) return 0; // Unknown length -> unknown.
2389 if (Len == ~0ULL) continue;
2391 if (Len != LenSoFar && LenSoFar != ~0ULL)
2392 return 0; // Disagree -> unknown.
2396 // Success, all agree.
2400 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2401 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2402 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2403 if (Len1 == 0) return 0;
2404 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2405 if (Len2 == 0) return 0;
2406 if (Len1 == ~0ULL) return Len2;
2407 if (Len2 == ~0ULL) return Len1;
2408 if (Len1 != Len2) return 0;
2412 // Otherwise, see if we can read the string.
2414 if (!getConstantStringInfo(V, StrData))
2417 return StrData.size()+1;
2420 /// GetStringLength - If we can compute the length of the string pointed to by
2421 /// the specified pointer, return 'len+1'. If we can't, return 0.
2422 uint64_t llvm::GetStringLength(Value *V) {
2423 if (!V->getType()->isPointerTy()) return 0;
2425 SmallPtrSet<PHINode*, 32> PHIs;
2426 uint64_t Len = GetStringLengthH(V, PHIs);
2427 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2428 // an empty string as a length.
2429 return Len == ~0ULL ? 1 : Len;
2433 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
2434 if (!V->getType()->isPointerTy())
2436 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2437 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2438 V = GEP->getPointerOperand();
2439 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2440 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
2441 V = cast<Operator>(V)->getOperand(0);
2442 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2443 if (GA->mayBeOverridden())
2445 V = GA->getAliasee();
2447 // See if InstructionSimplify knows any relevant tricks.
2448 if (Instruction *I = dyn_cast<Instruction>(V))
2449 // TODO: Acquire a DominatorTree and AssumptionTracker and use them.
2450 if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
2457 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2463 llvm::GetUnderlyingObjects(Value *V,
2464 SmallVectorImpl<Value *> &Objects,
2465 const DataLayout *TD,
2466 unsigned MaxLookup) {
2467 SmallPtrSet<Value *, 4> Visited;
2468 SmallVector<Value *, 4> Worklist;
2469 Worklist.push_back(V);
2471 Value *P = Worklist.pop_back_val();
2472 P = GetUnderlyingObject(P, TD, MaxLookup);
2474 if (!Visited.insert(P))
2477 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2478 Worklist.push_back(SI->getTrueValue());
2479 Worklist.push_back(SI->getFalseValue());
2483 if (PHINode *PN = dyn_cast<PHINode>(P)) {
2484 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2485 Worklist.push_back(PN->getIncomingValue(i));
2489 Objects.push_back(P);
2490 } while (!Worklist.empty());
2493 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
2494 /// are lifetime markers.
2496 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
2497 for (const User *U : V->users()) {
2498 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2499 if (!II) return false;
2501 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2502 II->getIntrinsicID() != Intrinsic::lifetime_end)
2508 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
2509 const DataLayout *TD) {
2510 const Operator *Inst = dyn_cast<Operator>(V);
2514 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2515 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2519 switch (Inst->getOpcode()) {
2522 case Instruction::UDiv:
2523 case Instruction::URem:
2524 // x / y is undefined if y == 0, but calculations like x / 3 are safe.
2525 return isKnownNonZero(Inst->getOperand(1), TD);
2526 case Instruction::SDiv:
2527 case Instruction::SRem: {
2528 Value *Op = Inst->getOperand(1);
2529 // x / y is undefined if y == 0
2530 if (!isKnownNonZero(Op, TD))
2532 // x / y might be undefined if y == -1
2533 unsigned BitWidth = getBitWidth(Op->getType(), TD);
2536 APInt KnownZero(BitWidth, 0);
2537 APInt KnownOne(BitWidth, 0);
2538 computeKnownBits(Op, KnownZero, KnownOne, TD);
2541 case Instruction::Load: {
2542 const LoadInst *LI = cast<LoadInst>(Inst);
2543 if (!LI->isUnordered() ||
2544 // Speculative load may create a race that did not exist in the source.
2545 LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
2547 return LI->getPointerOperand()->isDereferenceablePointer(TD);
2549 case Instruction::Call: {
2550 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2551 switch (II->getIntrinsicID()) {
2552 // These synthetic intrinsics have no side-effects and just mark
2553 // information about their operands.
2554 // FIXME: There are other no-op synthetic instructions that potentially
2555 // should be considered at least *safe* to speculate...
2556 case Intrinsic::dbg_declare:
2557 case Intrinsic::dbg_value:
2560 case Intrinsic::bswap:
2561 case Intrinsic::ctlz:
2562 case Intrinsic::ctpop:
2563 case Intrinsic::cttz:
2564 case Intrinsic::objectsize:
2565 case Intrinsic::sadd_with_overflow:
2566 case Intrinsic::smul_with_overflow:
2567 case Intrinsic::ssub_with_overflow:
2568 case Intrinsic::uadd_with_overflow:
2569 case Intrinsic::umul_with_overflow:
2570 case Intrinsic::usub_with_overflow:
2572 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2573 // errno like libm sqrt would.
2574 case Intrinsic::sqrt:
2575 case Intrinsic::fma:
2576 case Intrinsic::fmuladd:
2577 case Intrinsic::fabs:
2579 // TODO: some fp intrinsics are marked as having the same error handling
2580 // as libm. They're safe to speculate when they won't error.
2581 // TODO: are convert_{from,to}_fp16 safe?
2582 // TODO: can we list target-specific intrinsics here?
2586 return false; // The called function could have undefined behavior or
2587 // side-effects, even if marked readnone nounwind.
2589 case Instruction::VAArg:
2590 case Instruction::Alloca:
2591 case Instruction::Invoke:
2592 case Instruction::PHI:
2593 case Instruction::Store:
2594 case Instruction::Ret:
2595 case Instruction::Br:
2596 case Instruction::IndirectBr:
2597 case Instruction::Switch:
2598 case Instruction::Unreachable:
2599 case Instruction::Fence:
2600 case Instruction::LandingPad:
2601 case Instruction::AtomicRMW:
2602 case Instruction::AtomicCmpXchg:
2603 case Instruction::Resume:
2604 return false; // Misc instructions which have effects
2608 /// isKnownNonNull - Return true if we know that the specified value is never
2610 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
2611 // Alloca never returns null, malloc might.
2612 if (isa<AllocaInst>(V)) return true;
2614 // A byval, inalloca, or nonnull argument is never null.
2615 if (const Argument *A = dyn_cast<Argument>(V))
2616 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
2618 // Global values are not null unless extern weak.
2619 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2620 return !GV->hasExternalWeakLinkage();
2622 if (ImmutableCallSite CS = V)
2623 if (CS.isReturnNonNull())
2626 // operator new never returns null.
2627 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))