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/ADT/SmallPtrSet.h"
17 #include "llvm/Analysis/AssumptionCache.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 /// Enable an experimental feature to leverage information about dominating
43 /// conditions to compute known bits. The individual options below control how
44 /// hard we search. The defaults are choosen to be fairly aggressive. If you
45 /// run into compile time problems when testing, scale them back and report
47 static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
48 cl::Hidden, cl::init(false));
50 // This is expensive, so we only do it for the top level query value.
51 // (TODO: evaluate cost vs profit, consider higher thresholds)
52 static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
53 cl::Hidden, cl::init(1));
55 /// How many dominating blocks should be scanned looking for dominating
57 static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
61 // Controls the number of uses of the value searched for possible
62 // dominating comparisons.
63 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
64 cl::Hidden, cl::init(2000));
66 // If true, don't consider only compares whose only use is a branch.
67 static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
68 cl::Hidden, cl::init(false));
70 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
71 /// 0). For vector types, returns the element type's bitwidth.
72 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
73 if (unsigned BitWidth = Ty->getScalarSizeInBits())
76 return DL.getPointerTypeSizeInBits(Ty);
79 // Many of these functions have internal versions that take an assumption
80 // exclusion set. This is because of the potential for mutual recursion to
81 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
82 // classic case of this is assume(x = y), which will attempt to determine
83 // bits in x from bits in y, which will attempt to determine bits in y from
84 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
85 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
86 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
87 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
90 // Simplifying using an assume can only be done in a particular control-flow
91 // context (the context instruction provides that context). If an assume and
92 // the context instruction are not in the same block then the DT helps in
93 // figuring out if we can use it.
97 const Instruction *CxtI;
98 const DominatorTree *DT;
100 Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
101 const DominatorTree *DT = nullptr)
102 : AC(AC), CxtI(CxtI), DT(DT) {}
104 Query(const Query &Q, const Value *NewExcl)
105 : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
106 ExclInvs.insert(NewExcl);
109 } // end anonymous namespace
111 // Given the provided Value and, potentially, a context instruction, return
112 // the preferred context instruction (if any).
113 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
114 // If we've been provided with a context instruction, then use that (provided
115 // it has been inserted).
116 if (CxtI && CxtI->getParent())
119 // If the value is really an already-inserted instruction, then use that.
120 CxtI = dyn_cast<Instruction>(V);
121 if (CxtI && CxtI->getParent())
127 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
128 const DataLayout &DL, unsigned Depth,
131 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
132 const DataLayout &DL, unsigned Depth,
133 AssumptionCache *AC, const Instruction *CxtI,
134 const DominatorTree *DT) {
135 ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
136 Query(AC, safeCxtI(V, CxtI), DT));
139 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
140 const DataLayout &DL, unsigned Depth,
143 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
144 const DataLayout &DL, unsigned Depth,
145 AssumptionCache *AC, const Instruction *CxtI,
146 const DominatorTree *DT) {
147 ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
148 Query(AC, safeCxtI(V, CxtI), DT));
151 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
152 const Query &Q, const DataLayout &DL);
154 bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
155 unsigned Depth, AssumptionCache *AC,
156 const Instruction *CxtI,
157 const DominatorTree *DT) {
158 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
159 Query(AC, safeCxtI(V, CxtI), DT), DL);
162 static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
165 bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
166 AssumptionCache *AC, const Instruction *CxtI,
167 const DominatorTree *DT) {
168 return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
171 static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
172 unsigned Depth, const Query &Q);
174 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
175 unsigned Depth, AssumptionCache *AC,
176 const Instruction *CxtI, const DominatorTree *DT) {
177 return ::MaskedValueIsZero(V, Mask, DL, Depth,
178 Query(AC, safeCxtI(V, CxtI), DT));
181 static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
182 unsigned Depth, const Query &Q);
184 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
185 unsigned Depth, AssumptionCache *AC,
186 const Instruction *CxtI,
187 const DominatorTree *DT) {
188 return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
191 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
192 APInt &KnownZero, APInt &KnownOne,
193 APInt &KnownZero2, APInt &KnownOne2,
194 const DataLayout &DL, unsigned Depth,
197 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
198 // We know that the top bits of C-X are clear if X contains less bits
199 // than C (i.e. no wrap-around can happen). For example, 20-X is
200 // positive if we can prove that X is >= 0 and < 16.
201 if (!CLHS->getValue().isNegative()) {
202 unsigned BitWidth = KnownZero.getBitWidth();
203 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
204 // NLZ can't be BitWidth with no sign bit
205 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
206 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
208 // If all of the MaskV bits are known to be zero, then we know the
209 // output top bits are zero, because we now know that the output is
211 if ((KnownZero2 & MaskV) == MaskV) {
212 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
213 // Top bits known zero.
214 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
220 unsigned BitWidth = KnownZero.getBitWidth();
222 // If an initial sequence of bits in the result is not needed, the
223 // corresponding bits in the operands are not needed.
224 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
225 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
226 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
228 // Carry in a 1 for a subtract, rather than a 0.
229 APInt CarryIn(BitWidth, 0);
231 // Sum = LHS + ~RHS + 1
232 std::swap(KnownZero2, KnownOne2);
236 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
237 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
239 // Compute known bits of the carry.
240 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
241 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
243 // Compute set of known bits (where all three relevant bits are known).
244 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
245 APInt RHSKnown = KnownZero2 | KnownOne2;
246 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
247 APInt Known = LHSKnown & RHSKnown & CarryKnown;
249 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
250 "known bits of sum differ");
252 // Compute known bits of the result.
253 KnownZero = ~PossibleSumOne & Known;
254 KnownOne = PossibleSumOne & Known;
256 // Are we still trying to solve for the sign bit?
257 if (!Known.isNegative()) {
259 // Adding two non-negative numbers, or subtracting a negative number from
260 // a non-negative one, can't wrap into negative.
261 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
262 KnownZero |= APInt::getSignBit(BitWidth);
263 // Adding two negative numbers, or subtracting a non-negative number from
264 // a negative one, can't wrap into non-negative.
265 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
266 KnownOne |= APInt::getSignBit(BitWidth);
271 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
272 APInt &KnownZero, APInt &KnownOne,
273 APInt &KnownZero2, APInt &KnownOne2,
274 const DataLayout &DL, unsigned Depth,
276 unsigned BitWidth = KnownZero.getBitWidth();
277 computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
278 computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
280 bool isKnownNegative = false;
281 bool isKnownNonNegative = false;
282 // If the multiplication is known not to overflow, compute the sign bit.
285 // The product of a number with itself is non-negative.
286 isKnownNonNegative = true;
288 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
289 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
290 bool isKnownNegativeOp1 = KnownOne.isNegative();
291 bool isKnownNegativeOp0 = KnownOne2.isNegative();
292 // The product of two numbers with the same sign is non-negative.
293 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
294 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
295 // The product of a negative number and a non-negative number is either
297 if (!isKnownNonNegative)
298 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
299 isKnownNonZero(Op0, DL, Depth, Q)) ||
300 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
301 isKnownNonZero(Op1, DL, Depth, Q));
305 // If low bits are zero in either operand, output low known-0 bits.
306 // Also compute a conserative estimate for high known-0 bits.
307 // More trickiness is possible, but this is sufficient for the
308 // interesting case of alignment computation.
309 KnownOne.clearAllBits();
310 unsigned TrailZ = KnownZero.countTrailingOnes() +
311 KnownZero2.countTrailingOnes();
312 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
313 KnownZero2.countLeadingOnes(),
314 BitWidth) - BitWidth;
316 TrailZ = std::min(TrailZ, BitWidth);
317 LeadZ = std::min(LeadZ, BitWidth);
318 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
319 APInt::getHighBitsSet(BitWidth, LeadZ);
321 // Only make use of no-wrap flags if we failed to compute the sign bit
322 // directly. This matters if the multiplication always overflows, in
323 // which case we prefer to follow the result of the direct computation,
324 // though as the program is invoking undefined behaviour we can choose
325 // whatever we like here.
326 if (isKnownNonNegative && !KnownOne.isNegative())
327 KnownZero.setBit(BitWidth - 1);
328 else if (isKnownNegative && !KnownZero.isNegative())
329 KnownOne.setBit(BitWidth - 1);
332 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
334 unsigned BitWidth = KnownZero.getBitWidth();
335 unsigned NumRanges = Ranges.getNumOperands() / 2;
336 assert(NumRanges >= 1);
338 // Use the high end of the ranges to find leading zeros.
339 unsigned MinLeadingZeros = BitWidth;
340 for (unsigned i = 0; i < NumRanges; ++i) {
342 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
344 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
345 ConstantRange Range(Lower->getValue(), Upper->getValue());
346 if (Range.isWrappedSet())
347 MinLeadingZeros = 0; // -1 has no zeros
348 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
349 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
352 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
355 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
356 SmallVector<const Value *, 16> WorkSet(1, I);
357 SmallPtrSet<const Value *, 32> Visited;
358 SmallPtrSet<const Value *, 16> EphValues;
360 while (!WorkSet.empty()) {
361 const Value *V = WorkSet.pop_back_val();
362 if (!Visited.insert(V).second)
365 // If all uses of this value are ephemeral, then so is this value.
366 bool FoundNEUse = false;
367 for (const User *I : V->users())
368 if (!EphValues.count(I)) {
378 if (const User *U = dyn_cast<User>(V))
379 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
381 if (isSafeToSpeculativelyExecute(*J))
382 WorkSet.push_back(*J);
390 // Is this an intrinsic that cannot be speculated but also cannot trap?
391 static bool isAssumeLikeIntrinsic(const Instruction *I) {
392 if (const CallInst *CI = dyn_cast<CallInst>(I))
393 if (Function *F = CI->getCalledFunction())
394 switch (F->getIntrinsicID()) {
396 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
397 case Intrinsic::assume:
398 case Intrinsic::dbg_declare:
399 case Intrinsic::dbg_value:
400 case Intrinsic::invariant_start:
401 case Intrinsic::invariant_end:
402 case Intrinsic::lifetime_start:
403 case Intrinsic::lifetime_end:
404 case Intrinsic::objectsize:
405 case Intrinsic::ptr_annotation:
406 case Intrinsic::var_annotation:
413 static bool isValidAssumeForContext(Value *V, const Query &Q) {
414 Instruction *Inv = cast<Instruction>(V);
416 // There are two restrictions on the use of an assume:
417 // 1. The assume must dominate the context (or the control flow must
418 // reach the assume whenever it reaches the context).
419 // 2. The context must not be in the assume's set of ephemeral values
420 // (otherwise we will use the assume to prove that the condition
421 // feeding the assume is trivially true, thus causing the removal of
425 if (Q.DT->dominates(Inv, Q.CxtI)) {
427 } else if (Inv->getParent() == Q.CxtI->getParent()) {
428 // The context comes first, but they're both in the same block. Make sure
429 // there is nothing in between that might interrupt the control flow.
430 for (BasicBlock::const_iterator I =
431 std::next(BasicBlock::const_iterator(Q.CxtI)),
432 IE(Inv); I != IE; ++I)
433 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
436 return !isEphemeralValueOf(Inv, Q.CxtI);
442 // When we don't have a DT, we do a limited search...
443 if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
445 } else if (Inv->getParent() == Q.CxtI->getParent()) {
446 // Search forward from the assume until we reach the context (or the end
447 // of the block); the common case is that the assume will come first.
448 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
449 IE = Inv->getParent()->end(); I != IE; ++I)
453 // The context must come first...
454 for (BasicBlock::const_iterator I =
455 std::next(BasicBlock::const_iterator(Q.CxtI)),
456 IE(Inv); I != IE; ++I)
457 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
460 return !isEphemeralValueOf(Inv, Q.CxtI);
466 bool llvm::isValidAssumeForContext(const Instruction *I,
467 const Instruction *CxtI,
468 const DominatorTree *DT) {
469 return ::isValidAssumeForContext(const_cast<Instruction *>(I),
470 Query(nullptr, CxtI, DT));
473 template<typename LHS, typename RHS>
474 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
475 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
476 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
477 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
480 template<typename LHS, typename RHS>
481 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
482 BinaryOp_match<RHS, LHS, Instruction::And>>
483 m_c_And(const LHS &L, const RHS &R) {
484 return m_CombineOr(m_And(L, R), m_And(R, L));
487 template<typename LHS, typename RHS>
488 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
489 BinaryOp_match<RHS, LHS, Instruction::Or>>
490 m_c_Or(const LHS &L, const RHS &R) {
491 return m_CombineOr(m_Or(L, R), m_Or(R, L));
494 template<typename LHS, typename RHS>
495 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
496 BinaryOp_match<RHS, LHS, Instruction::Xor>>
497 m_c_Xor(const LHS &L, const RHS &R) {
498 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
501 /// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
502 /// true (at the context instruction.) This is mostly a utility function for
503 /// the prototype dominating conditions reasoning below.
504 static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
507 const DataLayout &DL,
508 unsigned Depth, const Query &Q) {
509 Value *LHS = Cmp->getOperand(0);
510 Value *RHS = Cmp->getOperand(1);
511 // TODO: We could potentially be more aggressive here. This would be worth
512 // evaluating. If we can, explore commoning this code with the assume
514 if (LHS != V && RHS != V)
517 const unsigned BitWidth = KnownZero.getBitWidth();
519 switch (Cmp->getPredicate()) {
521 // We know nothing from this condition
523 // TODO: implement unsigned bound from below (known one bits)
524 // TODO: common condition check implementations with assumes
525 // TODO: implement other patterns from assume (e.g. V & B == A)
526 case ICmpInst::ICMP_SGT:
528 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
529 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
530 if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
531 // We know that the sign bit is zero.
532 KnownZero |= APInt::getSignBit(BitWidth);
536 case ICmpInst::ICMP_EQ:
538 computeKnownBits(RHS, KnownZero, KnownOne, DL, Depth + 1, Q);
540 computeKnownBits(LHS, KnownZero, KnownOne, DL, Depth + 1, Q);
542 llvm_unreachable("missing use?");
544 case ICmpInst::ICMP_ULE:
546 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
547 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
548 // The known zero bits carry over
549 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
550 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
553 case ICmpInst::ICMP_ULT:
555 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
556 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
557 // Whatever high bits in rhs are zero are known to be zero (if rhs is a
558 // power of 2, then one more).
559 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
560 if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp), DL))
562 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
568 /// Compute known bits in 'V' from conditions which are known to be true along
569 /// all paths leading to the context instruction. In particular, look for
570 /// cases where one branch of an interesting condition dominates the context
571 /// instruction. This does not do general dataflow.
572 /// NOTE: This code is EXPERIMENTAL and currently off by default.
573 static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
575 const DataLayout &DL,
578 // Need both the dominator tree and the query location to do anything useful
579 if (!Q.DT || !Q.CxtI)
581 Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
583 // Avoid useless work
584 if (auto VI = dyn_cast<Instruction>(V))
585 if (VI->getParent() == Cxt->getParent())
588 // Note: We currently implement two options. It's not clear which of these
589 // will survive long term, we need data for that.
590 // Option 1 - Try walking the dominator tree looking for conditions which
591 // might apply. This works well for local conditions (loop guards, etc..),
592 // but not as well for things far from the context instruction (presuming a
593 // low max blocks explored). If we can set an high enough limit, this would
595 // Option 2 - We restrict out search to those conditions which are uses of
596 // the value we're interested in. This is independent of dom structure,
597 // but is slightly less powerful without looking through lots of use chains.
598 // It does handle conditions far from the context instruction (e.g. early
599 // function exits on entry) really well though.
601 // Option 1 - Search the dom tree
602 unsigned NumBlocksExplored = 0;
603 BasicBlock *Current = Cxt->getParent();
605 // Stop searching if we've gone too far up the chain
606 if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
610 if (!Q.DT->getNode(Current)->getIDom())
612 Current = Q.DT->getNode(Current)->getIDom()->getBlock();
614 // found function entry
617 BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
618 if (!BI || BI->isUnconditional())
620 ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
624 // We're looking for conditions that are guaranteed to hold at the context
625 // instruction. Finding a condition where one path dominates the context
626 // isn't enough because both the true and false cases could merge before
627 // the context instruction we're actually interested in. Instead, we need
628 // to ensure that the taken *edge* dominates the context instruction.
629 BasicBlock *BB0 = BI->getSuccessor(0);
630 BasicBlockEdge Edge(BI->getParent(), BB0);
631 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
634 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
638 // Option 2 - Search the other uses of V
639 unsigned NumUsesExplored = 0;
640 for (auto U : V->users()) {
641 // Avoid massive lists
642 if (NumUsesExplored >= DomConditionsMaxUses)
645 // Consider only compare instructions uniquely controlling a branch
646 ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
650 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
653 for (auto *CmpU : Cmp->users()) {
654 BranchInst *BI = dyn_cast<BranchInst>(CmpU);
655 if (!BI || BI->isUnconditional())
657 // We're looking for conditions that are guaranteed to hold at the
658 // context instruction. Finding a condition where one path dominates
659 // the context isn't enough because both the true and false cases could
660 // merge before the context instruction we're actually interested in.
661 // Instead, we need to ensure that the taken *edge* dominates the context
663 BasicBlock *BB0 = BI->getSuccessor(0);
664 BasicBlockEdge Edge(BI->getParent(), BB0);
665 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
668 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
674 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
675 APInt &KnownOne, const DataLayout &DL,
676 unsigned Depth, const Query &Q) {
677 // Use of assumptions is context-sensitive. If we don't have a context, we
679 if (!Q.AC || !Q.CxtI)
682 unsigned BitWidth = KnownZero.getBitWidth();
684 for (auto &AssumeVH : Q.AC->assumptions()) {
687 CallInst *I = cast<CallInst>(AssumeVH);
688 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
689 "Got assumption for the wrong function!");
690 if (Q.ExclInvs.count(I))
693 // Warning: This loop can end up being somewhat performance sensetive.
694 // We're running this loop for once for each value queried resulting in a
695 // runtime of ~O(#assumes * #values).
697 assert(isa<IntrinsicInst>(I) &&
698 dyn_cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::assume &&
699 "must be an assume intrinsic");
701 Value *Arg = I->getArgOperand(0);
703 if (Arg == V && isValidAssumeForContext(I, Q)) {
704 assert(BitWidth == 1 && "assume operand is not i1?");
705 KnownZero.clearAllBits();
706 KnownOne.setAllBits();
710 // The remaining tests are all recursive, so bail out if we hit the limit.
711 if (Depth == MaxDepth)
715 auto m_V = m_CombineOr(m_Specific(V),
716 m_CombineOr(m_PtrToInt(m_Specific(V)),
717 m_BitCast(m_Specific(V))));
719 CmpInst::Predicate Pred;
722 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
723 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
724 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
725 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
726 KnownZero |= RHSKnownZero;
727 KnownOne |= RHSKnownOne;
729 } else if (match(Arg,
730 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
731 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
732 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
733 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
734 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
735 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
737 // For those bits in the mask that are known to be one, we can propagate
738 // known bits from the RHS to V.
739 KnownZero |= RHSKnownZero & MaskKnownOne;
740 KnownOne |= RHSKnownOne & MaskKnownOne;
741 // assume(~(v & b) = a)
742 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
744 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
745 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
746 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
747 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
748 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
750 // For those bits in the mask that are known to be one, we can propagate
751 // inverted known bits from the RHS to V.
752 KnownZero |= RHSKnownOne & MaskKnownOne;
753 KnownOne |= RHSKnownZero & MaskKnownOne;
755 } else if (match(Arg,
756 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
757 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
758 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
759 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
760 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
761 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
763 // For those bits in B that are known to be zero, we can propagate known
764 // bits from the RHS to V.
765 KnownZero |= RHSKnownZero & BKnownZero;
766 KnownOne |= RHSKnownOne & BKnownZero;
767 // assume(~(v | b) = a)
768 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
770 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
771 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
772 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
773 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
774 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
776 // For those bits in B that are known to be zero, we can propagate
777 // inverted known bits from the RHS to V.
778 KnownZero |= RHSKnownOne & BKnownZero;
779 KnownOne |= RHSKnownZero & BKnownZero;
781 } else if (match(Arg,
782 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
783 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
784 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
785 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
786 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
787 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
789 // For those bits in B that are known to be zero, we can propagate known
790 // bits from the RHS to V. For those bits in B that are known to be one,
791 // we can propagate inverted known bits from the RHS to V.
792 KnownZero |= RHSKnownZero & BKnownZero;
793 KnownOne |= RHSKnownOne & BKnownZero;
794 KnownZero |= RHSKnownOne & BKnownOne;
795 KnownOne |= RHSKnownZero & BKnownOne;
796 // assume(~(v ^ b) = a)
797 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
799 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
800 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
801 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
802 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
803 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
805 // For those bits in B that are known to be zero, we can propagate
806 // inverted known bits from the RHS to V. For those bits in B that are
807 // known to be one, we can propagate known bits from the RHS to V.
808 KnownZero |= RHSKnownOne & BKnownZero;
809 KnownOne |= RHSKnownZero & BKnownZero;
810 KnownZero |= RHSKnownZero & BKnownOne;
811 KnownOne |= RHSKnownOne & BKnownOne;
812 // assume(v << c = a)
813 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
815 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
816 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
817 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
818 // For those bits in RHS that are known, we can propagate them to known
819 // bits in V shifted to the right by C.
820 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
821 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
822 // assume(~(v << c) = a)
823 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
825 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
826 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
827 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
828 // For those bits in RHS that are known, we can propagate them inverted
829 // to known bits in V shifted to the right by C.
830 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
831 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
832 // assume(v >> c = a)
833 } else if (match(Arg,
834 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
835 m_AShr(m_V, m_ConstantInt(C))),
837 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
838 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
839 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
840 // For those bits in RHS that are known, we can propagate them to known
841 // bits in V shifted to the right by C.
842 KnownZero |= RHSKnownZero << C->getZExtValue();
843 KnownOne |= RHSKnownOne << C->getZExtValue();
844 // assume(~(v >> c) = a)
845 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
846 m_LShr(m_V, m_ConstantInt(C)),
847 m_AShr(m_V, m_ConstantInt(C)))),
849 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
850 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
851 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
852 // For those bits in RHS that are known, we can propagate them inverted
853 // to known bits in V shifted to the right by C.
854 KnownZero |= RHSKnownOne << C->getZExtValue();
855 KnownOne |= RHSKnownZero << C->getZExtValue();
856 // assume(v >=_s c) where c is non-negative
857 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
858 Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
859 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
860 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
862 if (RHSKnownZero.isNegative()) {
863 // We know that the sign bit is zero.
864 KnownZero |= APInt::getSignBit(BitWidth);
866 // assume(v >_s c) where c is at least -1.
867 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
868 Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
869 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
870 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
872 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
873 // We know that the sign bit is zero.
874 KnownZero |= APInt::getSignBit(BitWidth);
876 // assume(v <=_s c) where c is negative
877 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
878 Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
879 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
880 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
882 if (RHSKnownOne.isNegative()) {
883 // We know that the sign bit is one.
884 KnownOne |= APInt::getSignBit(BitWidth);
886 // assume(v <_s c) where c is non-positive
887 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
888 Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
889 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
890 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
892 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
893 // We know that the sign bit is one.
894 KnownOne |= APInt::getSignBit(BitWidth);
897 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
898 Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
899 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
900 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
902 // Whatever high bits in c are zero are known to be zero.
904 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
906 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
907 Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
908 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
909 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
911 // Whatever high bits in c are zero are known to be zero (if c is a power
912 // of 2, then one more).
913 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
915 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
918 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
923 /// Determine which bits of V are known to be either zero or one and return
924 /// them in the KnownZero/KnownOne bit sets.
926 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
927 /// we cannot optimize based on the assumption that it is zero without changing
928 /// it to be an explicit zero. If we don't change it to zero, other code could
929 /// optimized based on the contradictory assumption that it is non-zero.
930 /// Because instcombine aggressively folds operations with undef args anyway,
931 /// this won't lose us code quality.
933 /// This function is defined on values with integer type, values with pointer
934 /// type, and vectors of integers. In the case
935 /// where V is a vector, known zero, and known one values are the
936 /// same width as the vector element, and the bit is set only if it is true
937 /// for all of the elements in the vector.
938 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
939 const DataLayout &DL, unsigned Depth, const Query &Q) {
940 assert(V && "No Value?");
941 assert(Depth <= MaxDepth && "Limit Search Depth");
942 unsigned BitWidth = KnownZero.getBitWidth();
944 assert((V->getType()->isIntOrIntVectorTy() ||
945 V->getType()->getScalarType()->isPointerTy()) &&
946 "Not integer or pointer type!");
947 assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
948 (!V->getType()->isIntOrIntVectorTy() ||
949 V->getType()->getScalarSizeInBits() == BitWidth) &&
950 KnownZero.getBitWidth() == BitWidth &&
951 KnownOne.getBitWidth() == BitWidth &&
952 "V, KnownOne and KnownZero should have same BitWidth");
954 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
955 // We know all of the bits for a constant!
956 KnownOne = CI->getValue();
957 KnownZero = ~KnownOne;
960 // Null and aggregate-zero are all-zeros.
961 if (isa<ConstantPointerNull>(V) ||
962 isa<ConstantAggregateZero>(V)) {
963 KnownOne.clearAllBits();
964 KnownZero = APInt::getAllOnesValue(BitWidth);
967 // Handle a constant vector by taking the intersection of the known bits of
968 // each element. There is no real need to handle ConstantVector here, because
969 // we don't handle undef in any particularly useful way.
970 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
971 // We know that CDS must be a vector of integers. Take the intersection of
973 KnownZero.setAllBits(); KnownOne.setAllBits();
974 APInt Elt(KnownZero.getBitWidth(), 0);
975 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
976 Elt = CDS->getElementAsInteger(i);
983 // The address of an aligned GlobalValue has trailing zeros.
984 if (auto *GO = dyn_cast<GlobalObject>(V)) {
985 unsigned Align = GO->getAlignment();
987 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
988 Type *ObjectType = GVar->getType()->getElementType();
989 if (ObjectType->isSized()) {
990 // If the object is defined in the current Module, we'll be giving
991 // it the preferred alignment. Otherwise, we have to assume that it
992 // may only have the minimum ABI alignment.
993 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
994 Align = DL.getPreferredAlignment(GVar);
996 Align = DL.getABITypeAlignment(ObjectType);
1001 KnownZero = APInt::getLowBitsSet(BitWidth,
1002 countTrailingZeros(Align));
1004 KnownZero.clearAllBits();
1005 KnownOne.clearAllBits();
1009 if (Argument *A = dyn_cast<Argument>(V)) {
1010 unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
1012 if (!Align && A->hasStructRetAttr()) {
1013 // An sret parameter has at least the ABI alignment of the return type.
1014 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
1015 if (EltTy->isSized())
1016 Align = DL.getABITypeAlignment(EltTy);
1020 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1022 KnownZero.clearAllBits();
1023 KnownOne.clearAllBits();
1025 // Don't give up yet... there might be an assumption that provides more
1027 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
1029 // Or a dominating condition for that matter
1030 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1031 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL,
1036 // Start out not knowing anything.
1037 KnownZero.clearAllBits(); KnownOne.clearAllBits();
1039 // Limit search depth.
1040 // All recursive calls that increase depth must come after this.
1041 if (Depth == MaxDepth)
1044 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1045 // the bits of its aliasee.
1046 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1047 if (!GA->mayBeOverridden())
1048 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
1052 // Check whether a nearby assume intrinsic can determine some known bits.
1053 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
1055 // Check whether there's a dominating condition which implies something about
1056 // this value at the given context.
1057 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1058 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL, Depth,
1061 Operator *I = dyn_cast<Operator>(V);
1064 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
1065 switch (I->getOpcode()) {
1067 case Instruction::Load:
1068 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
1069 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1071 case Instruction::And: {
1072 // If either the LHS or the RHS are Zero, the result is zero.
1073 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1074 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1076 // Output known-1 bits are only known if set in both the LHS & RHS.
1077 KnownOne &= KnownOne2;
1078 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1079 KnownZero |= KnownZero2;
1082 case Instruction::Or: {
1083 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1084 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1086 // Output known-0 bits are only known if clear in both the LHS & RHS.
1087 KnownZero &= KnownZero2;
1088 // Output known-1 are known to be set if set in either the LHS | RHS.
1089 KnownOne |= KnownOne2;
1092 case Instruction::Xor: {
1093 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1094 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1096 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1097 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1098 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1099 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1100 KnownZero = KnownZeroOut;
1103 case Instruction::Mul: {
1104 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1105 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
1106 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1109 case Instruction::UDiv: {
1110 // For the purposes of computing leading zeros we can conservatively
1111 // treat a udiv as a logical right shift by the power of 2 known to
1112 // be less than the denominator.
1113 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1114 unsigned LeadZ = KnownZero2.countLeadingOnes();
1116 KnownOne2.clearAllBits();
1117 KnownZero2.clearAllBits();
1118 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1119 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1120 if (RHSUnknownLeadingOnes != BitWidth)
1121 LeadZ = std::min(BitWidth,
1122 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1124 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1127 case Instruction::Select:
1128 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
1129 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1131 // Only known if known in both the LHS and RHS.
1132 KnownOne &= KnownOne2;
1133 KnownZero &= KnownZero2;
1135 case Instruction::FPTrunc:
1136 case Instruction::FPExt:
1137 case Instruction::FPToUI:
1138 case Instruction::FPToSI:
1139 case Instruction::SIToFP:
1140 case Instruction::UIToFP:
1141 break; // Can't work with floating point.
1142 case Instruction::PtrToInt:
1143 case Instruction::IntToPtr:
1144 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
1145 // FALL THROUGH and handle them the same as zext/trunc.
1146 case Instruction::ZExt:
1147 case Instruction::Trunc: {
1148 Type *SrcTy = I->getOperand(0)->getType();
1150 unsigned SrcBitWidth;
1151 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1152 // which fall through here.
1153 SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
1155 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1156 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1157 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
1158 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1159 KnownZero = KnownZero.zextOrTrunc(BitWidth);
1160 KnownOne = KnownOne.zextOrTrunc(BitWidth);
1161 // Any top bits are known to be zero.
1162 if (BitWidth > SrcBitWidth)
1163 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1166 case Instruction::BitCast: {
1167 Type *SrcTy = I->getOperand(0)->getType();
1168 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
1169 // TODO: For now, not handling conversions like:
1170 // (bitcast i64 %x to <2 x i32>)
1171 !I->getType()->isVectorTy()) {
1172 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1177 case Instruction::SExt: {
1178 // Compute the bits in the result that are not present in the input.
1179 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1181 KnownZero = KnownZero.trunc(SrcBitWidth);
1182 KnownOne = KnownOne.trunc(SrcBitWidth);
1183 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1184 KnownZero = KnownZero.zext(BitWidth);
1185 KnownOne = KnownOne.zext(BitWidth);
1187 // If the sign bit of the input is known set or clear, then we know the
1188 // top bits of the result.
1189 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
1190 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1191 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
1192 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1195 case Instruction::Shl:
1196 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1197 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1198 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1199 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1200 KnownZero <<= ShiftAmt;
1201 KnownOne <<= ShiftAmt;
1202 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
1205 case Instruction::LShr:
1206 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1207 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1208 // Compute the new bits that are at the top now.
1209 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1211 // Unsigned shift right.
1212 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1213 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1214 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1215 // high bits known zero.
1216 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
1219 case Instruction::AShr:
1220 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1221 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1222 // Compute the new bits that are at the top now.
1223 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
1225 // Signed shift right.
1226 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1227 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1228 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
1232 KnownZero |= HighBits;
1233 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
1234 KnownOne |= HighBits;
1237 case Instruction::Sub: {
1238 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1239 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1240 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1244 case Instruction::Add: {
1245 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1246 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1247 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1251 case Instruction::SRem:
1252 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1253 APInt RA = Rem->getValue().abs();
1254 if (RA.isPowerOf2()) {
1255 APInt LowBits = RA - 1;
1256 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
1259 // The low bits of the first operand are unchanged by the srem.
1260 KnownZero = KnownZero2 & LowBits;
1261 KnownOne = KnownOne2 & LowBits;
1263 // If the first operand is non-negative or has all low bits zero, then
1264 // the upper bits are all zero.
1265 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1266 KnownZero |= ~LowBits;
1268 // If the first operand is negative and not all low bits are zero, then
1269 // the upper bits are all one.
1270 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1271 KnownOne |= ~LowBits;
1273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1277 // The sign bit is the LHS's sign bit, except when the result of the
1278 // remainder is zero.
1279 if (KnownZero.isNonNegative()) {
1280 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1281 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
1283 // If it's known zero, our sign bit is also zero.
1284 if (LHSKnownZero.isNegative())
1285 KnownZero.setBit(BitWidth - 1);
1289 case Instruction::URem: {
1290 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1291 APInt RA = Rem->getValue();
1292 if (RA.isPowerOf2()) {
1293 APInt LowBits = (RA - 1);
1294 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1296 KnownZero |= ~LowBits;
1297 KnownOne &= LowBits;
1302 // Since the result is less than or equal to either operand, any leading
1303 // zero bits in either operand must also exist in the result.
1304 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1305 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1307 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1308 KnownZero2.countLeadingOnes());
1309 KnownOne.clearAllBits();
1310 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1314 case Instruction::Alloca: {
1315 AllocaInst *AI = cast<AllocaInst>(V);
1316 unsigned Align = AI->getAlignment();
1318 Align = DL.getABITypeAlignment(AI->getType()->getElementType());
1321 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1324 case Instruction::GetElementPtr: {
1325 // Analyze all of the subscripts of this getelementptr instruction
1326 // to determine if we can prove known low zero bits.
1327 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1328 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
1330 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1332 gep_type_iterator GTI = gep_type_begin(I);
1333 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1334 Value *Index = I->getOperand(i);
1335 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1336 // Handle struct member offset arithmetic.
1338 // Handle case when index is vector zeroinitializer
1339 Constant *CIndex = cast<Constant>(Index);
1340 if (CIndex->isZeroValue())
1343 if (CIndex->getType()->isVectorTy())
1344 Index = CIndex->getSplatValue();
1346 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1347 const StructLayout *SL = DL.getStructLayout(STy);
1348 uint64_t Offset = SL->getElementOffset(Idx);
1349 TrailZ = std::min<unsigned>(TrailZ,
1350 countTrailingZeros(Offset));
1352 // Handle array index arithmetic.
1353 Type *IndexedTy = GTI.getIndexedType();
1354 if (!IndexedTy->isSized()) {
1358 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1359 uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
1360 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1361 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
1363 TrailZ = std::min(TrailZ,
1364 unsigned(countTrailingZeros(TypeSize) +
1365 LocalKnownZero.countTrailingOnes()));
1369 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1372 case Instruction::PHI: {
1373 PHINode *P = cast<PHINode>(I);
1374 // Handle the case of a simple two-predecessor recurrence PHI.
1375 // There's a lot more that could theoretically be done here, but
1376 // this is sufficient to catch some interesting cases.
1377 if (P->getNumIncomingValues() == 2) {
1378 for (unsigned i = 0; i != 2; ++i) {
1379 Value *L = P->getIncomingValue(i);
1380 Value *R = P->getIncomingValue(!i);
1381 Operator *LU = dyn_cast<Operator>(L);
1384 unsigned Opcode = LU->getOpcode();
1385 // Check for operations that have the property that if
1386 // both their operands have low zero bits, the result
1387 // will have low zero bits.
1388 if (Opcode == Instruction::Add ||
1389 Opcode == Instruction::Sub ||
1390 Opcode == Instruction::And ||
1391 Opcode == Instruction::Or ||
1392 Opcode == Instruction::Mul) {
1393 Value *LL = LU->getOperand(0);
1394 Value *LR = LU->getOperand(1);
1395 // Find a recurrence.
1402 // Ok, we have a PHI of the form L op= R. Check for low
1404 computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
1406 // We need to take the minimum number of known bits
1407 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1408 computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
1410 KnownZero = APInt::getLowBitsSet(BitWidth,
1411 std::min(KnownZero2.countTrailingOnes(),
1412 KnownZero3.countTrailingOnes()));
1418 // Unreachable blocks may have zero-operand PHI nodes.
1419 if (P->getNumIncomingValues() == 0)
1422 // Otherwise take the unions of the known bit sets of the operands,
1423 // taking conservative care to avoid excessive recursion.
1424 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1425 // Skip if every incoming value references to ourself.
1426 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1429 KnownZero = APInt::getAllOnesValue(BitWidth);
1430 KnownOne = APInt::getAllOnesValue(BitWidth);
1431 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1432 // Skip direct self references.
1433 if (P->getIncomingValue(i) == P) continue;
1435 KnownZero2 = APInt(BitWidth, 0);
1436 KnownOne2 = APInt(BitWidth, 0);
1437 // Recurse, but cap the recursion to one level, because we don't
1438 // want to waste time spinning around in loops.
1439 computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, DL,
1441 KnownZero &= KnownZero2;
1442 KnownOne &= KnownOne2;
1443 // If all bits have been ruled out, there's no need to check
1445 if (!KnownZero && !KnownOne)
1451 case Instruction::Call:
1452 case Instruction::Invoke:
1453 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1454 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1455 // If a range metadata is attached to this IntrinsicInst, intersect the
1456 // explicit range specified by the metadata and the implicit range of
1458 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1459 switch (II->getIntrinsicID()) {
1461 case Intrinsic::ctlz:
1462 case Intrinsic::cttz: {
1463 unsigned LowBits = Log2_32(BitWidth)+1;
1464 // If this call is undefined for 0, the result will be less than 2^n.
1465 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1467 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1470 case Intrinsic::ctpop: {
1471 unsigned LowBits = Log2_32(BitWidth)+1;
1472 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1475 case Intrinsic::x86_sse42_crc32_64_64:
1476 KnownZero |= APInt::getHighBitsSet(64, 32);
1481 case Instruction::ExtractValue:
1482 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1483 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1484 if (EVI->getNumIndices() != 1) break;
1485 if (EVI->getIndices()[0] == 0) {
1486 switch (II->getIntrinsicID()) {
1488 case Intrinsic::uadd_with_overflow:
1489 case Intrinsic::sadd_with_overflow:
1490 computeKnownBitsAddSub(true, II->getArgOperand(0),
1491 II->getArgOperand(1), false, KnownZero,
1492 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1494 case Intrinsic::usub_with_overflow:
1495 case Intrinsic::ssub_with_overflow:
1496 computeKnownBitsAddSub(false, II->getArgOperand(0),
1497 II->getArgOperand(1), false, KnownZero,
1498 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1500 case Intrinsic::umul_with_overflow:
1501 case Intrinsic::smul_with_overflow:
1502 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1503 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1511 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1514 /// Determine whether the sign bit is known to be zero or one.
1515 /// Convenience wrapper around computeKnownBits.
1516 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1517 const DataLayout &DL, unsigned Depth, const Query &Q) {
1518 unsigned BitWidth = getBitWidth(V->getType(), DL);
1524 APInt ZeroBits(BitWidth, 0);
1525 APInt OneBits(BitWidth, 0);
1526 computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
1527 KnownOne = OneBits[BitWidth - 1];
1528 KnownZero = ZeroBits[BitWidth - 1];
1531 /// Return true if the given value is known to have exactly one
1532 /// bit set when defined. For vectors return true if every element is known to
1533 /// be a power of two when defined. Supports values with integer or pointer
1534 /// types and vectors of integers.
1535 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1536 const Query &Q, const DataLayout &DL) {
1537 if (Constant *C = dyn_cast<Constant>(V)) {
1538 if (C->isNullValue())
1540 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1541 return CI->getValue().isPowerOf2();
1542 // TODO: Handle vector constants.
1545 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1546 // it is shifted off the end then the result is undefined.
1547 if (match(V, m_Shl(m_One(), m_Value())))
1550 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1551 // bottom. If it is shifted off the bottom then the result is undefined.
1552 if (match(V, m_LShr(m_SignBit(), m_Value())))
1555 // The remaining tests are all recursive, so bail out if we hit the limit.
1556 if (Depth++ == MaxDepth)
1559 Value *X = nullptr, *Y = nullptr;
1560 // A shift of a power of two is a power of two or zero.
1561 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1562 match(V, m_Shr(m_Value(X), m_Value()))))
1563 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
1565 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1566 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
1568 if (SelectInst *SI = dyn_cast<SelectInst>(V))
1569 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
1570 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
1572 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1573 // A power of two and'd with anything is a power of two or zero.
1574 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
1575 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
1577 // X & (-X) is always a power of two or zero.
1578 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1583 // Adding a power-of-two or zero to the same power-of-two or zero yields
1584 // either the original power-of-two, a larger power-of-two or zero.
1585 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1586 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1587 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1588 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1589 match(X, m_And(m_Value(), m_Specific(Y))))
1590 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
1592 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1593 match(Y, m_And(m_Value(), m_Specific(X))))
1594 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
1597 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1598 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1599 computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
1601 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1602 computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
1603 // If i8 V is a power of two or zero:
1604 // ZeroBits: 1 1 1 0 1 1 1 1
1605 // ~ZeroBits: 0 0 0 1 0 0 0 0
1606 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1607 // If OrZero isn't set, we cannot give back a zero result.
1608 // Make sure either the LHS or RHS has a bit set.
1609 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1614 // An exact divide or right shift can only shift off zero bits, so the result
1615 // is a power of two only if the first operand is a power of two and not
1616 // copying a sign bit (sdiv int_min, 2).
1617 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1618 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1619 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1626 /// \brief Test whether a GEP's result is known to be non-null.
1628 /// Uses properties inherent in a GEP to try to determine whether it is known
1631 /// Currently this routine does not support vector GEPs.
1632 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
1633 unsigned Depth, const Query &Q) {
1634 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1637 // FIXME: Support vector-GEPs.
1638 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1640 // If the base pointer is non-null, we cannot walk to a null address with an
1641 // inbounds GEP in address space zero.
1642 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
1645 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1646 // If so, then the GEP cannot produce a null pointer, as doing so would
1647 // inherently violate the inbounds contract within address space zero.
1648 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1649 GTI != GTE; ++GTI) {
1650 // Struct types are easy -- they must always be indexed by a constant.
1651 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1652 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1653 unsigned ElementIdx = OpC->getZExtValue();
1654 const StructLayout *SL = DL.getStructLayout(STy);
1655 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1656 if (ElementOffset > 0)
1661 // If we have a zero-sized type, the index doesn't matter. Keep looping.
1662 if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1665 // Fast path the constant operand case both for efficiency and so we don't
1666 // increment Depth when just zipping down an all-constant GEP.
1667 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1673 // We post-increment Depth here because while isKnownNonZero increments it
1674 // as well, when we pop back up that increment won't persist. We don't want
1675 // to recurse 10k times just because we have 10k GEP operands. We don't
1676 // bail completely out because we want to handle constant GEPs regardless
1678 if (Depth++ >= MaxDepth)
1681 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
1688 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1689 /// ensure that the value it's attached to is never Value? 'RangeType' is
1690 /// is the type of the value described by the range.
1691 static bool rangeMetadataExcludesValue(MDNode* Ranges,
1692 const APInt& Value) {
1693 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1694 assert(NumRanges >= 1);
1695 for (unsigned i = 0; i < NumRanges; ++i) {
1696 ConstantInt *Lower =
1697 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1698 ConstantInt *Upper =
1699 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1700 ConstantRange Range(Lower->getValue(), Upper->getValue());
1701 if (Range.contains(Value))
1707 /// Return true if the given value is known to be non-zero when defined.
1708 /// For vectors return true if every element is known to be non-zero when
1709 /// defined. Supports values with integer or pointer type and vectors of
1711 bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
1713 if (Constant *C = dyn_cast<Constant>(V)) {
1714 if (C->isNullValue())
1716 if (isa<ConstantInt>(C))
1717 // Must be non-zero due to null test above.
1719 // TODO: Handle vectors
1723 if (Instruction* I = dyn_cast<Instruction>(V)) {
1724 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1725 // If the possible ranges don't contain zero, then the value is
1726 // definitely non-zero.
1727 if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1728 const APInt ZeroValue(Ty->getBitWidth(), 0);
1729 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1735 // The remaining tests are all recursive, so bail out if we hit the limit.
1736 if (Depth++ >= MaxDepth)
1739 // Check for pointer simplifications.
1740 if (V->getType()->isPointerTy()) {
1741 if (isKnownNonNull(V))
1743 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1744 if (isGEPKnownNonNull(GEP, DL, Depth, Q))
1748 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
1750 // X | Y != 0 if X != 0 or Y != 0.
1751 Value *X = nullptr, *Y = nullptr;
1752 if (match(V, m_Or(m_Value(X), m_Value(Y))))
1753 return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
1755 // ext X != 0 if X != 0.
1756 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1757 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
1759 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
1760 // if the lowest bit is shifted off the end.
1761 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1762 // shl nuw can't remove any non-zero bits.
1763 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1764 if (BO->hasNoUnsignedWrap())
1765 return isKnownNonZero(X, DL, Depth, Q);
1767 APInt KnownZero(BitWidth, 0);
1768 APInt KnownOne(BitWidth, 0);
1769 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1773 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
1774 // defined if the sign bit is shifted off the end.
1775 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1776 // shr exact can only shift out zero bits.
1777 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1779 return isKnownNonZero(X, DL, Depth, Q);
1781 bool XKnownNonNegative, XKnownNegative;
1782 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1786 // div exact can only produce a zero if the dividend is zero.
1787 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1788 return isKnownNonZero(X, DL, Depth, Q);
1791 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1792 bool XKnownNonNegative, XKnownNegative;
1793 bool YKnownNonNegative, YKnownNegative;
1794 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1795 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
1797 // If X and Y are both non-negative (as signed values) then their sum is not
1798 // zero unless both X and Y are zero.
1799 if (XKnownNonNegative && YKnownNonNegative)
1800 if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
1803 // If X and Y are both negative (as signed values) then their sum is not
1804 // zero unless both X and Y equal INT_MIN.
1805 if (BitWidth && XKnownNegative && YKnownNegative) {
1806 APInt KnownZero(BitWidth, 0);
1807 APInt KnownOne(BitWidth, 0);
1808 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1809 // The sign bit of X is set. If some other bit is set then X is not equal
1811 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1812 if ((KnownOne & Mask) != 0)
1814 // The sign bit of Y is set. If some other bit is set then Y is not equal
1816 computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
1817 if ((KnownOne & Mask) != 0)
1821 // The sum of a non-negative number and a power of two is not zero.
1822 if (XKnownNonNegative &&
1823 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
1825 if (YKnownNonNegative &&
1826 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
1830 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1831 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1832 // If X and Y are non-zero then so is X * Y as long as the multiplication
1833 // does not overflow.
1834 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1835 isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
1838 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1839 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1840 if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
1841 isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
1845 if (!BitWidth) return false;
1846 APInt KnownZero(BitWidth, 0);
1847 APInt KnownOne(BitWidth, 0);
1848 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
1849 return KnownOne != 0;
1852 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
1853 /// simplify operations downstream. Mask is known to be zero for bits that V
1856 /// This function is defined on values with integer type, values with pointer
1857 /// type, and vectors of integers. In the case
1858 /// where V is a vector, the mask, known zero, and known one values are the
1859 /// same width as the vector element, and the bit is set only if it is true
1860 /// for all of the elements in the vector.
1861 bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
1862 unsigned Depth, const Query &Q) {
1863 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1864 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
1865 return (KnownZero & Mask) == Mask;
1870 /// Return the number of times the sign bit of the register is replicated into
1871 /// the other bits. We know that at least 1 bit is always equal to the sign bit
1872 /// (itself), but other cases can give us information. For example, immediately
1873 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
1874 /// other, so we return 3.
1876 /// 'Op' must have a scalar integer type.
1878 unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
1880 unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
1882 unsigned FirstAnswer = 1;
1884 // Note that ConstantInt is handled by the general computeKnownBits case
1888 return 1; // Limit search depth.
1890 Operator *U = dyn_cast<Operator>(V);
1891 switch (Operator::getOpcode(V)) {
1893 case Instruction::SExt:
1894 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1895 return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
1897 case Instruction::SDiv: {
1898 const APInt *Denominator;
1899 // sdiv X, C -> adds log(C) sign bits.
1900 if (match(U->getOperand(1), m_APInt(Denominator))) {
1902 // Ignore non-positive denominator.
1903 if (!Denominator->isStrictlyPositive())
1906 // Calculate the incoming numerator bits.
1907 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1909 // Add floor(log(C)) bits to the numerator bits.
1910 return std::min(TyBits, NumBits + Denominator->logBase2());
1915 case Instruction::SRem: {
1916 const APInt *Denominator;
1917 // srem X, C -> we know that the result is within 0..C-1 when C is a
1918 // positive constant and the sign bits are at most TypeBits - log2(C).
1919 if (match(U->getOperand(1), m_APInt(Denominator))) {
1921 // Ignore non-positive denominator.
1922 if (!Denominator->isStrictlyPositive())
1925 // Calculate the incoming numerator bits. SRem by a positive constant
1926 // can't lower the number of sign bits.
1928 ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1930 // Calculate the leading sign bit constraints by examining the
1931 // denominator. The remainder is in the range 0..C-1, which is
1932 // calculated by the log2(denominator). The sign bits are the bit-width
1933 // minus this value. The result of this subtraction has to be positive.
1934 unsigned ResBits = TyBits - Denominator->logBase2();
1936 return std::max(NumrBits, ResBits);
1941 case Instruction::AShr: {
1942 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1943 // ashr X, C -> adds C sign bits. Vectors too.
1945 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1946 Tmp += ShAmt->getZExtValue();
1947 if (Tmp > TyBits) Tmp = TyBits;
1951 case Instruction::Shl: {
1953 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1954 // shl destroys sign bits.
1955 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1956 Tmp2 = ShAmt->getZExtValue();
1957 if (Tmp2 >= TyBits || // Bad shift.
1958 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1963 case Instruction::And:
1964 case Instruction::Or:
1965 case Instruction::Xor: // NOT is handled here.
1966 // Logical binary ops preserve the number of sign bits at the worst.
1967 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1969 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
1970 FirstAnswer = std::min(Tmp, Tmp2);
1971 // We computed what we know about the sign bits as our first
1972 // answer. Now proceed to the generic code that uses
1973 // computeKnownBits, and pick whichever answer is better.
1977 case Instruction::Select:
1978 Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
1979 if (Tmp == 1) return 1; // Early out.
1980 Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
1981 return std::min(Tmp, Tmp2);
1983 case Instruction::Add:
1984 // Add can have at most one carry bit. Thus we know that the output
1985 // is, at worst, one more bit than the inputs.
1986 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1987 if (Tmp == 1) return 1; // Early out.
1989 // Special case decrementing a value (ADD X, -1):
1990 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
1991 if (CRHS->isAllOnesValue()) {
1992 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1993 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1996 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1998 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2001 // If we are subtracting one from a positive number, there is no carry
2002 // out of the result.
2003 if (KnownZero.isNegative())
2007 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2008 if (Tmp2 == 1) return 1;
2009 return std::min(Tmp, Tmp2)-1;
2011 case Instruction::Sub:
2012 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2013 if (Tmp2 == 1) return 1;
2016 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2017 if (CLHS->isNullValue()) {
2018 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2019 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
2021 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2023 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2026 // If the input is known to be positive (the sign bit is known clear),
2027 // the output of the NEG has the same number of sign bits as the input.
2028 if (KnownZero.isNegative())
2031 // Otherwise, we treat this like a SUB.
2034 // Sub can have at most one carry bit. Thus we know that the output
2035 // is, at worst, one more bit than the inputs.
2036 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2037 if (Tmp == 1) return 1; // Early out.
2038 return std::min(Tmp, Tmp2)-1;
2040 case Instruction::PHI: {
2041 PHINode *PN = cast<PHINode>(U);
2042 unsigned NumIncomingValues = PN->getNumIncomingValues();
2043 // Don't analyze large in-degree PHIs.
2044 if (NumIncomingValues > 4) break;
2045 // Unreachable blocks may have zero-operand PHI nodes.
2046 if (NumIncomingValues == 0) break;
2048 // Take the minimum of all incoming values. This can't infinitely loop
2049 // because of our depth threshold.
2050 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
2051 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2052 if (Tmp == 1) return Tmp;
2054 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
2059 case Instruction::Trunc:
2060 // FIXME: it's tricky to do anything useful for this, but it is an important
2061 // case for targets like X86.
2065 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2066 // use this information.
2067 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2069 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
2071 if (KnownZero.isNegative()) { // sign bit is 0
2073 } else if (KnownOne.isNegative()) { // sign bit is 1;
2080 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2081 // the number of identical bits in the top of the input value.
2083 Mask <<= Mask.getBitWidth()-TyBits;
2084 // Return # leading zeros. We use 'min' here in case Val was zero before
2085 // shifting. We don't want to return '64' as for an i32 "0".
2086 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2089 /// This function computes the integer multiple of Base that equals V.
2090 /// If successful, it returns true and returns the multiple in
2091 /// Multiple. If unsuccessful, it returns false. It looks
2092 /// through SExt instructions only if LookThroughSExt is true.
2093 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2094 bool LookThroughSExt, unsigned Depth) {
2095 const unsigned MaxDepth = 6;
2097 assert(V && "No Value?");
2098 assert(Depth <= MaxDepth && "Limit Search Depth");
2099 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2101 Type *T = V->getType();
2103 ConstantInt *CI = dyn_cast<ConstantInt>(V);
2113 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2114 Constant *BaseVal = ConstantInt::get(T, Base);
2115 if (CO && CO == BaseVal) {
2117 Multiple = ConstantInt::get(T, 1);
2121 if (CI && CI->getZExtValue() % Base == 0) {
2122 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2126 if (Depth == MaxDepth) return false; // Limit search depth.
2128 Operator *I = dyn_cast<Operator>(V);
2129 if (!I) return false;
2131 switch (I->getOpcode()) {
2133 case Instruction::SExt:
2134 if (!LookThroughSExt) return false;
2135 // otherwise fall through to ZExt
2136 case Instruction::ZExt:
2137 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2138 LookThroughSExt, Depth+1);
2139 case Instruction::Shl:
2140 case Instruction::Mul: {
2141 Value *Op0 = I->getOperand(0);
2142 Value *Op1 = I->getOperand(1);
2144 if (I->getOpcode() == Instruction::Shl) {
2145 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2146 if (!Op1CI) return false;
2147 // Turn Op0 << Op1 into Op0 * 2^Op1
2148 APInt Op1Int = Op1CI->getValue();
2149 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2150 APInt API(Op1Int.getBitWidth(), 0);
2151 API.setBit(BitToSet);
2152 Op1 = ConstantInt::get(V->getContext(), API);
2155 Value *Mul0 = nullptr;
2156 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2157 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2158 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2159 if (Op1C->getType()->getPrimitiveSizeInBits() <
2160 MulC->getType()->getPrimitiveSizeInBits())
2161 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2162 if (Op1C->getType()->getPrimitiveSizeInBits() >
2163 MulC->getType()->getPrimitiveSizeInBits())
2164 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2166 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2167 Multiple = ConstantExpr::getMul(MulC, Op1C);
2171 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2172 if (Mul0CI->getValue() == 1) {
2173 // V == Base * Op1, so return Op1
2179 Value *Mul1 = nullptr;
2180 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2181 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2182 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2183 if (Op0C->getType()->getPrimitiveSizeInBits() <
2184 MulC->getType()->getPrimitiveSizeInBits())
2185 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2186 if (Op0C->getType()->getPrimitiveSizeInBits() >
2187 MulC->getType()->getPrimitiveSizeInBits())
2188 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2190 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2191 Multiple = ConstantExpr::getMul(MulC, Op0C);
2195 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2196 if (Mul1CI->getValue() == 1) {
2197 // V == Base * Op0, so return Op0
2205 // We could not determine if V is a multiple of Base.
2209 /// Return true if we can prove that the specified FP value is never equal to
2212 /// NOTE: this function will need to be revisited when we support non-default
2215 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2216 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2217 return !CFP->getValueAPF().isNegZero();
2219 // FIXME: Magic number! At the least, this should be given a name because it's
2220 // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2221 // expose it as a parameter, so it can be used for testing / experimenting.
2223 return false; // Limit search depth.
2225 const Operator *I = dyn_cast<Operator>(V);
2226 if (!I) return false;
2228 // Check if the nsz fast-math flag is set
2229 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2230 if (FPO->hasNoSignedZeros())
2233 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2234 if (I->getOpcode() == Instruction::FAdd)
2235 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2236 if (CFP->isNullValue())
2239 // sitofp and uitofp turn into +0.0 for zero.
2240 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2243 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2244 // sqrt(-0.0) = -0.0, no other negative results are possible.
2245 if (II->getIntrinsicID() == Intrinsic::sqrt)
2246 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
2248 if (const CallInst *CI = dyn_cast<CallInst>(I))
2249 if (const Function *F = CI->getCalledFunction()) {
2250 if (F->isDeclaration()) {
2252 if (F->getName() == "abs") return true;
2253 // fabs[lf](x) != -0.0
2254 if (F->getName() == "fabs") return true;
2255 if (F->getName() == "fabsf") return true;
2256 if (F->getName() == "fabsl") return true;
2257 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2258 F->getName() == "sqrtl")
2259 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
2266 bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2267 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2268 return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2270 // FIXME: Magic number! At the least, this should be given a name because it's
2271 // used similarly in CannotBeNegativeZero(). A better fix may be to
2272 // expose it as a parameter, so it can be used for testing / experimenting.
2274 return false; // Limit search depth.
2276 const Operator *I = dyn_cast<Operator>(V);
2277 if (!I) return false;
2279 switch (I->getOpcode()) {
2281 case Instruction::FMul:
2282 // x*x is always non-negative or a NaN.
2283 if (I->getOperand(0) == I->getOperand(1))
2286 case Instruction::FAdd:
2287 case Instruction::FDiv:
2288 case Instruction::FRem:
2289 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2290 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2291 case Instruction::FPExt:
2292 case Instruction::FPTrunc:
2293 // Widening/narrowing never change sign.
2294 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2295 case Instruction::Call:
2296 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2297 switch (II->getIntrinsicID()) {
2299 case Intrinsic::exp:
2300 case Intrinsic::exp2:
2301 case Intrinsic::fabs:
2302 case Intrinsic::sqrt:
2304 case Intrinsic::powi:
2305 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2306 // powi(x,n) is non-negative if n is even.
2307 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2310 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2311 case Intrinsic::fma:
2312 case Intrinsic::fmuladd:
2313 // x*x+y is non-negative if y is non-negative.
2314 return I->getOperand(0) == I->getOperand(1) &&
2315 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2322 /// If the specified value can be set by repeating the same byte in memory,
2323 /// return the i8 value that it is represented with. This is
2324 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2325 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2326 /// byte store (e.g. i16 0x1234), return null.
2327 Value *llvm::isBytewiseValue(Value *V) {
2328 // All byte-wide stores are splatable, even of arbitrary variables.
2329 if (V->getType()->isIntegerTy(8)) return V;
2331 // Handle 'null' ConstantArrayZero etc.
2332 if (Constant *C = dyn_cast<Constant>(V))
2333 if (C->isNullValue())
2334 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2336 // Constant float and double values can be handled as integer values if the
2337 // corresponding integer value is "byteable". An important case is 0.0.
2338 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2339 if (CFP->getType()->isFloatTy())
2340 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2341 if (CFP->getType()->isDoubleTy())
2342 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2343 // Don't handle long double formats, which have strange constraints.
2346 // We can handle constant integers that are multiple of 8 bits.
2347 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2348 if (CI->getBitWidth() % 8 == 0) {
2349 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
2351 // We can check that all bytes of an integer are equal by making use of a
2352 // little trick: rotate by 8 and check if it's still the same value.
2353 if (CI->getValue() != CI->getValue().rotl(8))
2355 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
2359 // A ConstantDataArray/Vector is splatable if all its members are equal and
2361 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2362 Value *Elt = CA->getElementAsConstant(0);
2363 Value *Val = isBytewiseValue(Elt);
2367 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2368 if (CA->getElementAsConstant(I) != Elt)
2374 // Conceptually, we could handle things like:
2375 // %a = zext i8 %X to i16
2376 // %b = shl i16 %a, 8
2377 // %c = or i16 %a, %b
2378 // but until there is an example that actually needs this, it doesn't seem
2379 // worth worrying about.
2384 // This is the recursive version of BuildSubAggregate. It takes a few different
2385 // arguments. Idxs is the index within the nested struct From that we are
2386 // looking at now (which is of type IndexedType). IdxSkip is the number of
2387 // indices from Idxs that should be left out when inserting into the resulting
2388 // struct. To is the result struct built so far, new insertvalue instructions
2390 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2391 SmallVectorImpl<unsigned> &Idxs,
2393 Instruction *InsertBefore) {
2394 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2396 // Save the original To argument so we can modify it
2398 // General case, the type indexed by Idxs is a struct
2399 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2400 // Process each struct element recursively
2403 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2407 // Couldn't find any inserted value for this index? Cleanup
2408 while (PrevTo != OrigTo) {
2409 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2410 PrevTo = Del->getAggregateOperand();
2411 Del->eraseFromParent();
2413 // Stop processing elements
2417 // If we successfully found a value for each of our subaggregates
2421 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2422 // the struct's elements had a value that was inserted directly. In the latter
2423 // case, perhaps we can't determine each of the subelements individually, but
2424 // we might be able to find the complete struct somewhere.
2426 // Find the value that is at that particular spot
2427 Value *V = FindInsertedValue(From, Idxs);
2432 // Insert the value in the new (sub) aggregrate
2433 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2434 "tmp", InsertBefore);
2437 // This helper takes a nested struct and extracts a part of it (which is again a
2438 // struct) into a new value. For example, given the struct:
2439 // { a, { b, { c, d }, e } }
2440 // and the indices "1, 1" this returns
2443 // It does this by inserting an insertvalue for each element in the resulting
2444 // struct, as opposed to just inserting a single struct. This will only work if
2445 // each of the elements of the substruct are known (ie, inserted into From by an
2446 // insertvalue instruction somewhere).
2448 // All inserted insertvalue instructions are inserted before InsertBefore
2449 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2450 Instruction *InsertBefore) {
2451 assert(InsertBefore && "Must have someplace to insert!");
2452 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2454 Value *To = UndefValue::get(IndexedType);
2455 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2456 unsigned IdxSkip = Idxs.size();
2458 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2461 /// Given an aggregrate and an sequence of indices, see if
2462 /// the scalar value indexed is already around as a register, for example if it
2463 /// were inserted directly into the aggregrate.
2465 /// If InsertBefore is not null, this function will duplicate (modified)
2466 /// insertvalues when a part of a nested struct is extracted.
2467 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2468 Instruction *InsertBefore) {
2469 // Nothing to index? Just return V then (this is useful at the end of our
2471 if (idx_range.empty())
2473 // We have indices, so V should have an indexable type.
2474 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2475 "Not looking at a struct or array?");
2476 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2477 "Invalid indices for type?");
2479 if (Constant *C = dyn_cast<Constant>(V)) {
2480 C = C->getAggregateElement(idx_range[0]);
2481 if (!C) return nullptr;
2482 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2485 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2486 // Loop the indices for the insertvalue instruction in parallel with the
2487 // requested indices
2488 const unsigned *req_idx = idx_range.begin();
2489 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2490 i != e; ++i, ++req_idx) {
2491 if (req_idx == idx_range.end()) {
2492 // We can't handle this without inserting insertvalues
2496 // The requested index identifies a part of a nested aggregate. Handle
2497 // this specially. For example,
2498 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2499 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2500 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2501 // This can be changed into
2502 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2503 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2504 // which allows the unused 0,0 element from the nested struct to be
2506 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2510 // This insert value inserts something else than what we are looking for.
2511 // See if the (aggregrate) value inserted into has the value we are
2512 // looking for, then.
2514 return FindInsertedValue(I->getAggregateOperand(), idx_range,
2517 // If we end up here, the indices of the insertvalue match with those
2518 // requested (though possibly only partially). Now we recursively look at
2519 // the inserted value, passing any remaining indices.
2520 return FindInsertedValue(I->getInsertedValueOperand(),
2521 makeArrayRef(req_idx, idx_range.end()),
2525 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2526 // If we're extracting a value from an aggregrate that was extracted from
2527 // something else, we can extract from that something else directly instead.
2528 // However, we will need to chain I's indices with the requested indices.
2530 // Calculate the number of indices required
2531 unsigned size = I->getNumIndices() + idx_range.size();
2532 // Allocate some space to put the new indices in
2533 SmallVector<unsigned, 5> Idxs;
2535 // Add indices from the extract value instruction
2536 Idxs.append(I->idx_begin(), I->idx_end());
2538 // Add requested indices
2539 Idxs.append(idx_range.begin(), idx_range.end());
2541 assert(Idxs.size() == size
2542 && "Number of indices added not correct?");
2544 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2546 // Otherwise, we don't know (such as, extracting from a function return value
2547 // or load instruction)
2551 /// Analyze the specified pointer to see if it can be expressed as a base
2552 /// pointer plus a constant offset. Return the base and offset to the caller.
2553 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2554 const DataLayout &DL) {
2555 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
2556 APInt ByteOffset(BitWidth, 0);
2558 if (Ptr->getType()->isVectorTy())
2561 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2562 APInt GEPOffset(BitWidth, 0);
2563 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2566 ByteOffset += GEPOffset;
2568 Ptr = GEP->getPointerOperand();
2569 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2570 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2571 Ptr = cast<Operator>(Ptr)->getOperand(0);
2572 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2573 if (GA->mayBeOverridden())
2575 Ptr = GA->getAliasee();
2580 Offset = ByteOffset.getSExtValue();
2585 /// This function computes the length of a null-terminated C string pointed to
2586 /// by V. If successful, it returns true and returns the string in Str.
2587 /// If unsuccessful, it returns false.
2588 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2589 uint64_t Offset, bool TrimAtNul) {
2592 // Look through bitcast instructions and geps.
2593 V = V->stripPointerCasts();
2595 // If the value is a GEP instructionor constant expression, treat it as an
2597 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2598 // Make sure the GEP has exactly three arguments.
2599 if (GEP->getNumOperands() != 3)
2602 // Make sure the index-ee is a pointer to array of i8.
2603 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2604 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
2605 if (!AT || !AT->getElementType()->isIntegerTy(8))
2608 // Check to make sure that the first operand of the GEP is an integer and
2609 // has value 0 so that we are sure we're indexing into the initializer.
2610 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2611 if (!FirstIdx || !FirstIdx->isZero())
2614 // If the second index isn't a ConstantInt, then this is a variable index
2615 // into the array. If this occurs, we can't say anything meaningful about
2617 uint64_t StartIdx = 0;
2618 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2619 StartIdx = CI->getZExtValue();
2622 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
2625 // The GEP instruction, constant or instruction, must reference a global
2626 // variable that is a constant and is initialized. The referenced constant
2627 // initializer is the array that we'll use for optimization.
2628 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2629 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2632 // Handle the all-zeros case
2633 if (GV->getInitializer()->isNullValue()) {
2634 // This is a degenerate case. The initializer is constant zero so the
2635 // length of the string must be zero.
2640 // Must be a Constant Array
2641 const ConstantDataArray *Array =
2642 dyn_cast<ConstantDataArray>(GV->getInitializer());
2643 if (!Array || !Array->isString())
2646 // Get the number of elements in the array
2647 uint64_t NumElts = Array->getType()->getArrayNumElements();
2649 // Start out with the entire array in the StringRef.
2650 Str = Array->getAsString();
2652 if (Offset > NumElts)
2655 // Skip over 'offset' bytes.
2656 Str = Str.substr(Offset);
2659 // Trim off the \0 and anything after it. If the array is not nul
2660 // terminated, we just return the whole end of string. The client may know
2661 // some other way that the string is length-bound.
2662 Str = Str.substr(0, Str.find('\0'));
2667 // These next two are very similar to the above, but also look through PHI
2669 // TODO: See if we can integrate these two together.
2671 /// If we can compute the length of the string pointed to by
2672 /// the specified pointer, return 'len+1'. If we can't, return 0.
2673 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2674 // Look through noop bitcast instructions.
2675 V = V->stripPointerCasts();
2677 // If this is a PHI node, there are two cases: either we have already seen it
2679 if (PHINode *PN = dyn_cast<PHINode>(V)) {
2680 if (!PHIs.insert(PN).second)
2681 return ~0ULL; // already in the set.
2683 // If it was new, see if all the input strings are the same length.
2684 uint64_t LenSoFar = ~0ULL;
2685 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2686 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2687 if (Len == 0) return 0; // Unknown length -> unknown.
2689 if (Len == ~0ULL) continue;
2691 if (Len != LenSoFar && LenSoFar != ~0ULL)
2692 return 0; // Disagree -> unknown.
2696 // Success, all agree.
2700 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2701 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2702 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2703 if (Len1 == 0) return 0;
2704 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2705 if (Len2 == 0) return 0;
2706 if (Len1 == ~0ULL) return Len2;
2707 if (Len2 == ~0ULL) return Len1;
2708 if (Len1 != Len2) return 0;
2712 // Otherwise, see if we can read the string.
2714 if (!getConstantStringInfo(V, StrData))
2717 return StrData.size()+1;
2720 /// If we can compute the length of the string pointed to by
2721 /// the specified pointer, return 'len+1'. If we can't, return 0.
2722 uint64_t llvm::GetStringLength(Value *V) {
2723 if (!V->getType()->isPointerTy()) return 0;
2725 SmallPtrSet<PHINode*, 32> PHIs;
2726 uint64_t Len = GetStringLengthH(V, PHIs);
2727 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2728 // an empty string as a length.
2729 return Len == ~0ULL ? 1 : Len;
2732 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
2733 unsigned MaxLookup) {
2734 if (!V->getType()->isPointerTy())
2736 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2737 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2738 V = GEP->getPointerOperand();
2739 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2740 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
2741 V = cast<Operator>(V)->getOperand(0);
2742 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2743 if (GA->mayBeOverridden())
2745 V = GA->getAliasee();
2747 // See if InstructionSimplify knows any relevant tricks.
2748 if (Instruction *I = dyn_cast<Instruction>(V))
2749 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
2750 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
2757 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2762 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
2763 const DataLayout &DL, unsigned MaxLookup) {
2764 SmallPtrSet<Value *, 4> Visited;
2765 SmallVector<Value *, 4> Worklist;
2766 Worklist.push_back(V);
2768 Value *P = Worklist.pop_back_val();
2769 P = GetUnderlyingObject(P, DL, MaxLookup);
2771 if (!Visited.insert(P).second)
2774 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2775 Worklist.push_back(SI->getTrueValue());
2776 Worklist.push_back(SI->getFalseValue());
2780 if (PHINode *PN = dyn_cast<PHINode>(P)) {
2781 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2782 Worklist.push_back(PN->getIncomingValue(i));
2786 Objects.push_back(P);
2787 } while (!Worklist.empty());
2790 /// Return true if the only users of this pointer are lifetime markers.
2791 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
2792 for (const User *U : V->users()) {
2793 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2794 if (!II) return false;
2796 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2797 II->getIntrinsicID() != Intrinsic::lifetime_end)
2803 bool llvm::isSafeToSpeculativelyExecute(const Value *V) {
2804 const Operator *Inst = dyn_cast<Operator>(V);
2808 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2809 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2813 switch (Inst->getOpcode()) {
2816 case Instruction::UDiv:
2817 case Instruction::URem: {
2818 // x / y is undefined if y == 0.
2820 if (match(Inst->getOperand(1), m_APInt(V)))
2824 case Instruction::SDiv:
2825 case Instruction::SRem: {
2826 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
2827 const APInt *Numerator, *Denominator;
2828 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
2830 // We cannot hoist this division if the denominator is 0.
2831 if (*Denominator == 0)
2833 // It's safe to hoist if the denominator is not 0 or -1.
2834 if (*Denominator != -1)
2836 // At this point we know that the denominator is -1. It is safe to hoist as
2837 // long we know that the numerator is not INT_MIN.
2838 if (match(Inst->getOperand(0), m_APInt(Numerator)))
2839 return !Numerator->isMinSignedValue();
2840 // The numerator *might* be MinSignedValue.
2843 case Instruction::Load: {
2844 const LoadInst *LI = cast<LoadInst>(Inst);
2845 if (!LI->isUnordered() ||
2846 // Speculative load may create a race that did not exist in the source.
2847 LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
2849 const DataLayout &DL = LI->getModule()->getDataLayout();
2850 return LI->getPointerOperand()->isDereferenceablePointer(DL);
2852 case Instruction::Call: {
2853 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2854 switch (II->getIntrinsicID()) {
2855 // These synthetic intrinsics have no side-effects and just mark
2856 // information about their operands.
2857 // FIXME: There are other no-op synthetic instructions that potentially
2858 // should be considered at least *safe* to speculate...
2859 case Intrinsic::dbg_declare:
2860 case Intrinsic::dbg_value:
2863 case Intrinsic::bswap:
2864 case Intrinsic::ctlz:
2865 case Intrinsic::ctpop:
2866 case Intrinsic::cttz:
2867 case Intrinsic::objectsize:
2868 case Intrinsic::sadd_with_overflow:
2869 case Intrinsic::smul_with_overflow:
2870 case Intrinsic::ssub_with_overflow:
2871 case Intrinsic::uadd_with_overflow:
2872 case Intrinsic::umul_with_overflow:
2873 case Intrinsic::usub_with_overflow:
2875 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2876 // errno like libm sqrt would.
2877 case Intrinsic::sqrt:
2878 case Intrinsic::fma:
2879 case Intrinsic::fmuladd:
2880 case Intrinsic::fabs:
2881 case Intrinsic::minnum:
2882 case Intrinsic::maxnum:
2884 // TODO: some fp intrinsics are marked as having the same error handling
2885 // as libm. They're safe to speculate when they won't error.
2886 // TODO: are convert_{from,to}_fp16 safe?
2887 // TODO: can we list target-specific intrinsics here?
2891 return false; // The called function could have undefined behavior or
2892 // side-effects, even if marked readnone nounwind.
2894 case Instruction::VAArg:
2895 case Instruction::Alloca:
2896 case Instruction::Invoke:
2897 case Instruction::PHI:
2898 case Instruction::Store:
2899 case Instruction::Ret:
2900 case Instruction::Br:
2901 case Instruction::IndirectBr:
2902 case Instruction::Switch:
2903 case Instruction::Unreachable:
2904 case Instruction::Fence:
2905 case Instruction::LandingPad:
2906 case Instruction::AtomicRMW:
2907 case Instruction::AtomicCmpXchg:
2908 case Instruction::Resume:
2909 return false; // Misc instructions which have effects
2913 /// Return true if we know that the specified value is never null.
2914 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
2915 // Alloca never returns null, malloc might.
2916 if (isa<AllocaInst>(V)) return true;
2918 // A byval, inalloca, or nonnull argument is never null.
2919 if (const Argument *A = dyn_cast<Argument>(V))
2920 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
2922 // Global values are not null unless extern weak.
2923 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2924 return !GV->hasExternalWeakLinkage();
2926 // A Load tagged w/nonnull metadata is never null.
2927 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
2928 return LI->getMetadata(LLVMContext::MD_nonnull);
2930 if (ImmutableCallSite CS = V)
2931 if (CS.isReturnNonNull())
2934 // operator new never returns null.
2935 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
2941 OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
2942 const DataLayout &DL,
2943 AssumptionCache *AC,
2944 const Instruction *CxtI,
2945 const DominatorTree *DT) {
2946 // Multiplying n * m significant bits yields a result of n + m significant
2947 // bits. If the total number of significant bits does not exceed the
2948 // result bit width (minus 1), there is no overflow.
2949 // This means if we have enough leading zero bits in the operands
2950 // we can guarantee that the result does not overflow.
2951 // Ref: "Hacker's Delight" by Henry Warren
2952 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
2953 APInt LHSKnownZero(BitWidth, 0);
2954 APInt LHSKnownOne(BitWidth, 0);
2955 APInt RHSKnownZero(BitWidth, 0);
2956 APInt RHSKnownOne(BitWidth, 0);
2957 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
2959 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
2961 // Note that underestimating the number of zero bits gives a more
2962 // conservative answer.
2963 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
2964 RHSKnownZero.countLeadingOnes();
2965 // First handle the easy case: if we have enough zero bits there's
2966 // definitely no overflow.
2967 if (ZeroBits >= BitWidth)
2968 return OverflowResult::NeverOverflows;
2970 // Get the largest possible values for each operand.
2971 APInt LHSMax = ~LHSKnownZero;
2972 APInt RHSMax = ~RHSKnownZero;
2974 // We know the multiply operation doesn't overflow if the maximum values for
2975 // each operand will not overflow after we multiply them together.
2977 LHSMax.umul_ov(RHSMax, MaxOverflow);
2979 return OverflowResult::NeverOverflows;
2981 // We know it always overflows if multiplying the smallest possible values for
2982 // the operands also results in overflow.
2984 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
2986 return OverflowResult::AlwaysOverflows;
2988 return OverflowResult::MayOverflow;
2991 OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
2992 const DataLayout &DL,
2993 AssumptionCache *AC,
2994 const Instruction *CxtI,
2995 const DominatorTree *DT) {
2996 bool LHSKnownNonNegative, LHSKnownNegative;
2997 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
2999 if (LHSKnownNonNegative || LHSKnownNegative) {
3000 bool RHSKnownNonNegative, RHSKnownNegative;
3001 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3004 if (LHSKnownNegative && RHSKnownNegative) {
3005 // The sign bit is set in both cases: this MUST overflow.
3006 // Create a simple add instruction, and insert it into the struct.
3007 return OverflowResult::AlwaysOverflows;
3010 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3011 // The sign bit is clear in both cases: this CANNOT overflow.
3012 // Create a simple add instruction, and insert it into the struct.
3013 return OverflowResult::NeverOverflows;
3017 return OverflowResult::MayOverflow;