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/Optional.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/MemoryBuiltins.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/GetElementPtrTypeIterator.h"
28 #include "llvm/IR/GlobalAlias.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/Statepoint.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/MathExtras.h"
41 using namespace llvm::PatternMatch;
43 const unsigned MaxDepth = 6;
45 /// Enable an experimental feature to leverage information about dominating
46 /// conditions to compute known bits. The individual options below control how
47 /// hard we search. The defaults are chosen to be fairly aggressive. If you
48 /// run into compile time problems when testing, scale them back and report
50 static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
51 cl::Hidden, cl::init(false));
53 // This is expensive, so we only do it for the top level query value.
54 // (TODO: evaluate cost vs profit, consider higher thresholds)
55 static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
56 cl::Hidden, cl::init(1));
58 /// How many dominating blocks should be scanned looking for dominating
60 static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
64 // Controls the number of uses of the value searched for possible
65 // dominating comparisons.
66 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
67 cl::Hidden, cl::init(20));
69 // If true, don't consider only compares whose only use is a branch.
70 static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
71 cl::Hidden, cl::init(false));
73 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
74 /// 0). For vector types, returns the element type's bitwidth.
75 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
76 if (unsigned BitWidth = Ty->getScalarSizeInBits())
79 return DL.getPointerTypeSizeInBits(Ty);
82 // Many of these functions have internal versions that take an assumption
83 // exclusion set. This is because of the potential for mutual recursion to
84 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
85 // classic case of this is assume(x = y), which will attempt to determine
86 // bits in x from bits in y, which will attempt to determine bits in y from
87 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
88 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
89 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
90 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
93 // Simplifying using an assume can only be done in a particular control-flow
94 // context (the context instruction provides that context). If an assume and
95 // the context instruction are not in the same block then the DT helps in
96 // figuring out if we can use it.
100 const Instruction *CxtI;
101 const DominatorTree *DT;
103 Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
104 const DominatorTree *DT = nullptr)
105 : AC(AC), CxtI(CxtI), DT(DT) {}
107 Query(const Query &Q, const Value *NewExcl)
108 : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
109 ExclInvs.insert(NewExcl);
112 } // end anonymous namespace
114 // Given the provided Value and, potentially, a context instruction, return
115 // the preferred context instruction (if any).
116 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
117 // If we've been provided with a context instruction, then use that (provided
118 // it has been inserted).
119 if (CxtI && CxtI->getParent())
122 // If the value is really an already-inserted instruction, then use that.
123 CxtI = dyn_cast<Instruction>(V);
124 if (CxtI && CxtI->getParent())
130 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
131 const DataLayout &DL, unsigned Depth,
134 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
135 const DataLayout &DL, unsigned Depth,
136 AssumptionCache *AC, const Instruction *CxtI,
137 const DominatorTree *DT) {
138 ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
139 Query(AC, safeCxtI(V, CxtI), DT));
142 bool llvm::haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
143 AssumptionCache *AC, const Instruction *CxtI,
144 const DominatorTree *DT) {
145 assert(LHS->getType() == RHS->getType() &&
146 "LHS and RHS should have the same type");
147 assert(LHS->getType()->isIntOrIntVectorTy() &&
148 "LHS and RHS should be integers");
149 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
150 APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
151 APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
152 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
153 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
154 return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
157 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
158 const DataLayout &DL, unsigned Depth,
161 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
162 const DataLayout &DL, unsigned Depth,
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT) {
165 ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
166 Query(AC, safeCxtI(V, CxtI), DT));
169 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
170 const Query &Q, const DataLayout &DL);
172 bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
173 unsigned Depth, AssumptionCache *AC,
174 const Instruction *CxtI,
175 const DominatorTree *DT) {
176 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
177 Query(AC, safeCxtI(V, CxtI), DT), DL);
180 static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
183 bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
184 AssumptionCache *AC, const Instruction *CxtI,
185 const DominatorTree *DT) {
186 return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
189 bool llvm::isKnownNonNegative(Value *V, const DataLayout &DL, unsigned Depth,
190 AssumptionCache *AC, const Instruction *CxtI,
191 const DominatorTree *DT) {
192 bool NonNegative, Negative;
193 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
197 static bool isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
200 bool llvm::isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
201 AssumptionCache *AC, const Instruction *CxtI,
202 const DominatorTree *DT) {
203 return ::isKnownNonEqual(V1, V2, DL, Query(AC,
204 safeCxtI(V1, safeCxtI(V2, CxtI)),
208 static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
209 unsigned Depth, const Query &Q);
211 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
212 unsigned Depth, AssumptionCache *AC,
213 const Instruction *CxtI, const DominatorTree *DT) {
214 return ::MaskedValueIsZero(V, Mask, DL, Depth,
215 Query(AC, safeCxtI(V, CxtI), DT));
218 static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
219 unsigned Depth, const Query &Q);
221 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
222 unsigned Depth, AssumptionCache *AC,
223 const Instruction *CxtI,
224 const DominatorTree *DT) {
225 return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
228 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
229 APInt &KnownZero, APInt &KnownOne,
230 APInt &KnownZero2, APInt &KnownOne2,
231 const DataLayout &DL, unsigned Depth,
234 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
235 // We know that the top bits of C-X are clear if X contains less bits
236 // than C (i.e. no wrap-around can happen). For example, 20-X is
237 // positive if we can prove that X is >= 0 and < 16.
238 if (!CLHS->getValue().isNegative()) {
239 unsigned BitWidth = KnownZero.getBitWidth();
240 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
241 // NLZ can't be BitWidth with no sign bit
242 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
243 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
245 // If all of the MaskV bits are known to be zero, then we know the
246 // output top bits are zero, because we now know that the output is
248 if ((KnownZero2 & MaskV) == MaskV) {
249 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
250 // Top bits known zero.
251 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
257 unsigned BitWidth = KnownZero.getBitWidth();
259 // If an initial sequence of bits in the result is not needed, the
260 // corresponding bits in the operands are not needed.
261 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
262 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
263 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
265 // Carry in a 1 for a subtract, rather than a 0.
266 APInt CarryIn(BitWidth, 0);
268 // Sum = LHS + ~RHS + 1
269 std::swap(KnownZero2, KnownOne2);
273 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
274 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
276 // Compute known bits of the carry.
277 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
278 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
280 // Compute set of known bits (where all three relevant bits are known).
281 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
282 APInt RHSKnown = KnownZero2 | KnownOne2;
283 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
284 APInt Known = LHSKnown & RHSKnown & CarryKnown;
286 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
287 "known bits of sum differ");
289 // Compute known bits of the result.
290 KnownZero = ~PossibleSumOne & Known;
291 KnownOne = PossibleSumOne & Known;
293 // Are we still trying to solve for the sign bit?
294 if (!Known.isNegative()) {
296 // Adding two non-negative numbers, or subtracting a negative number from
297 // a non-negative one, can't wrap into negative.
298 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
299 KnownZero |= APInt::getSignBit(BitWidth);
300 // Adding two negative numbers, or subtracting a non-negative number from
301 // a negative one, can't wrap into non-negative.
302 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
303 KnownOne |= APInt::getSignBit(BitWidth);
308 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
309 APInt &KnownZero, APInt &KnownOne,
310 APInt &KnownZero2, APInt &KnownOne2,
311 const DataLayout &DL, unsigned Depth,
313 unsigned BitWidth = KnownZero.getBitWidth();
314 computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
315 computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
317 bool isKnownNegative = false;
318 bool isKnownNonNegative = false;
319 // If the multiplication is known not to overflow, compute the sign bit.
322 // The product of a number with itself is non-negative.
323 isKnownNonNegative = true;
325 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
326 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
327 bool isKnownNegativeOp1 = KnownOne.isNegative();
328 bool isKnownNegativeOp0 = KnownOne2.isNegative();
329 // The product of two numbers with the same sign is non-negative.
330 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
331 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
332 // The product of a negative number and a non-negative number is either
334 if (!isKnownNonNegative)
335 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
336 isKnownNonZero(Op0, DL, Depth, Q)) ||
337 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
338 isKnownNonZero(Op1, DL, Depth, Q));
342 // If low bits are zero in either operand, output low known-0 bits.
343 // Also compute a conservative estimate for high known-0 bits.
344 // More trickiness is possible, but this is sufficient for the
345 // interesting case of alignment computation.
346 KnownOne.clearAllBits();
347 unsigned TrailZ = KnownZero.countTrailingOnes() +
348 KnownZero2.countTrailingOnes();
349 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
350 KnownZero2.countLeadingOnes(),
351 BitWidth) - BitWidth;
353 TrailZ = std::min(TrailZ, BitWidth);
354 LeadZ = std::min(LeadZ, BitWidth);
355 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
356 APInt::getHighBitsSet(BitWidth, LeadZ);
358 // Only make use of no-wrap flags if we failed to compute the sign bit
359 // directly. This matters if the multiplication always overflows, in
360 // which case we prefer to follow the result of the direct computation,
361 // though as the program is invoking undefined behaviour we can choose
362 // whatever we like here.
363 if (isKnownNonNegative && !KnownOne.isNegative())
364 KnownZero.setBit(BitWidth - 1);
365 else if (isKnownNegative && !KnownZero.isNegative())
366 KnownOne.setBit(BitWidth - 1);
369 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
371 unsigned BitWidth = KnownZero.getBitWidth();
372 unsigned NumRanges = Ranges.getNumOperands() / 2;
373 assert(NumRanges >= 1);
375 // Use the high end of the ranges to find leading zeros.
376 unsigned MinLeadingZeros = BitWidth;
377 for (unsigned i = 0; i < NumRanges; ++i) {
379 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
381 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
382 ConstantRange Range(Lower->getValue(), Upper->getValue());
383 if (Range.isWrappedSet())
384 MinLeadingZeros = 0; // -1 has no zeros
385 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
386 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
389 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
392 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
393 SmallVector<const Value *, 16> WorkSet(1, I);
394 SmallPtrSet<const Value *, 32> Visited;
395 SmallPtrSet<const Value *, 16> EphValues;
397 // The instruction defining an assumption's condition itself is always
398 // considered ephemeral to that assumption (even if it has other
399 // non-ephemeral users). See r246696's test case for an example.
400 if (std::find(I->op_begin(), I->op_end(), E) != I->op_end())
403 while (!WorkSet.empty()) {
404 const Value *V = WorkSet.pop_back_val();
405 if (!Visited.insert(V).second)
408 // If all uses of this value are ephemeral, then so is this value.
409 if (std::all_of(V->user_begin(), V->user_end(),
410 [&](const User *U) { return EphValues.count(U); })) {
415 if (const User *U = dyn_cast<User>(V))
416 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
418 if (isSafeToSpeculativelyExecute(*J))
419 WorkSet.push_back(*J);
427 // Is this an intrinsic that cannot be speculated but also cannot trap?
428 static bool isAssumeLikeIntrinsic(const Instruction *I) {
429 if (const CallInst *CI = dyn_cast<CallInst>(I))
430 if (Function *F = CI->getCalledFunction())
431 switch (F->getIntrinsicID()) {
433 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
434 case Intrinsic::assume:
435 case Intrinsic::dbg_declare:
436 case Intrinsic::dbg_value:
437 case Intrinsic::invariant_start:
438 case Intrinsic::invariant_end:
439 case Intrinsic::lifetime_start:
440 case Intrinsic::lifetime_end:
441 case Intrinsic::objectsize:
442 case Intrinsic::ptr_annotation:
443 case Intrinsic::var_annotation:
450 static bool isValidAssumeForContext(Value *V, const Query &Q) {
451 Instruction *Inv = cast<Instruction>(V);
453 // There are two restrictions on the use of an assume:
454 // 1. The assume must dominate the context (or the control flow must
455 // reach the assume whenever it reaches the context).
456 // 2. The context must not be in the assume's set of ephemeral values
457 // (otherwise we will use the assume to prove that the condition
458 // feeding the assume is trivially true, thus causing the removal of
462 if (Q.DT->dominates(Inv, Q.CxtI)) {
464 } else if (Inv->getParent() == Q.CxtI->getParent()) {
465 // The context comes first, but they're both in the same block. Make sure
466 // there is nothing in between that might interrupt the control flow.
467 for (BasicBlock::const_iterator I =
468 std::next(BasicBlock::const_iterator(Q.CxtI)),
469 IE(Inv); I != IE; ++I)
470 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
473 return !isEphemeralValueOf(Inv, Q.CxtI);
479 // When we don't have a DT, we do a limited search...
480 if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
482 } else if (Inv->getParent() == Q.CxtI->getParent()) {
483 // Search forward from the assume until we reach the context (or the end
484 // of the block); the common case is that the assume will come first.
485 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
486 IE = Inv->getParent()->end(); I != IE; ++I)
490 // The context must come first...
491 for (BasicBlock::const_iterator I =
492 std::next(BasicBlock::const_iterator(Q.CxtI)),
493 IE(Inv); I != IE; ++I)
494 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
497 return !isEphemeralValueOf(Inv, Q.CxtI);
503 bool llvm::isValidAssumeForContext(const Instruction *I,
504 const Instruction *CxtI,
505 const DominatorTree *DT) {
506 return ::isValidAssumeForContext(const_cast<Instruction *>(I),
507 Query(nullptr, CxtI, DT));
510 template<typename LHS, typename RHS>
511 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
512 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
513 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
514 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
517 template<typename LHS, typename RHS>
518 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
519 BinaryOp_match<RHS, LHS, Instruction::And>>
520 m_c_And(const LHS &L, const RHS &R) {
521 return m_CombineOr(m_And(L, R), m_And(R, L));
524 template<typename LHS, typename RHS>
525 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
526 BinaryOp_match<RHS, LHS, Instruction::Or>>
527 m_c_Or(const LHS &L, const RHS &R) {
528 return m_CombineOr(m_Or(L, R), m_Or(R, L));
531 template<typename LHS, typename RHS>
532 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
533 BinaryOp_match<RHS, LHS, Instruction::Xor>>
534 m_c_Xor(const LHS &L, const RHS &R) {
535 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
538 /// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
539 /// true (at the context instruction.) This is mostly a utility function for
540 /// the prototype dominating conditions reasoning below.
541 static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
544 const DataLayout &DL,
545 unsigned Depth, const Query &Q) {
546 Value *LHS = Cmp->getOperand(0);
547 Value *RHS = Cmp->getOperand(1);
548 // TODO: We could potentially be more aggressive here. This would be worth
549 // evaluating. If we can, explore commoning this code with the assume
551 if (LHS != V && RHS != V)
554 const unsigned BitWidth = KnownZero.getBitWidth();
556 switch (Cmp->getPredicate()) {
558 // We know nothing from this condition
560 // TODO: implement unsigned bound from below (known one bits)
561 // TODO: common condition check implementations with assumes
562 // TODO: implement other patterns from assume (e.g. V & B == A)
563 case ICmpInst::ICMP_SGT:
565 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
566 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
567 if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
568 // We know that the sign bit is zero.
569 KnownZero |= APInt::getSignBit(BitWidth);
573 case ICmpInst::ICMP_EQ:
575 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
577 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
579 computeKnownBits(LHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
581 llvm_unreachable("missing use?");
582 KnownZero |= KnownZeroTemp;
583 KnownOne |= KnownOneTemp;
586 case ICmpInst::ICMP_ULE:
588 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
589 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
590 // The known zero bits carry over
591 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
592 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
595 case ICmpInst::ICMP_ULT:
597 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
598 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
599 // Whatever high bits in rhs are zero are known to be zero (if rhs is a
600 // power of 2, then one more).
601 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
602 if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp), DL))
604 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
610 /// Compute known bits in 'V' from conditions which are known to be true along
611 /// all paths leading to the context instruction. In particular, look for
612 /// cases where one branch of an interesting condition dominates the context
613 /// instruction. This does not do general dataflow.
614 /// NOTE: This code is EXPERIMENTAL and currently off by default.
615 static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
617 const DataLayout &DL,
620 // Need both the dominator tree and the query location to do anything useful
621 if (!Q.DT || !Q.CxtI)
623 Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
624 // The context instruction might be in a statically unreachable block. If
625 // so, asking dominator queries may yield suprising results. (e.g. the block
626 // may not have a dom tree node)
627 if (!Q.DT->isReachableFromEntry(Cxt->getParent()))
630 // Avoid useless work
631 if (auto VI = dyn_cast<Instruction>(V))
632 if (VI->getParent() == Cxt->getParent())
635 // Note: We currently implement two options. It's not clear which of these
636 // will survive long term, we need data for that.
637 // Option 1 - Try walking the dominator tree looking for conditions which
638 // might apply. This works well for local conditions (loop guards, etc..),
639 // but not as well for things far from the context instruction (presuming a
640 // low max blocks explored). If we can set an high enough limit, this would
642 // Option 2 - We restrict out search to those conditions which are uses of
643 // the value we're interested in. This is independent of dom structure,
644 // but is slightly less powerful without looking through lots of use chains.
645 // It does handle conditions far from the context instruction (e.g. early
646 // function exits on entry) really well though.
648 // Option 1 - Search the dom tree
649 unsigned NumBlocksExplored = 0;
650 BasicBlock *Current = Cxt->getParent();
652 // Stop searching if we've gone too far up the chain
653 if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
657 if (!Q.DT->getNode(Current)->getIDom())
659 Current = Q.DT->getNode(Current)->getIDom()->getBlock();
661 // found function entry
664 BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
665 if (!BI || BI->isUnconditional())
667 ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
671 // We're looking for conditions that are guaranteed to hold at the context
672 // instruction. Finding a condition where one path dominates the context
673 // isn't enough because both the true and false cases could merge before
674 // the context instruction we're actually interested in. Instead, we need
675 // to ensure that the taken *edge* dominates the context instruction. We
676 // know that the edge must be reachable since we started from a reachable
678 BasicBlock *BB0 = BI->getSuccessor(0);
679 BasicBlockEdge Edge(BI->getParent(), BB0);
680 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
683 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
687 // Option 2 - Search the other uses of V
688 unsigned NumUsesExplored = 0;
689 for (auto U : V->users()) {
690 // Avoid massive lists
691 if (NumUsesExplored >= DomConditionsMaxUses)
694 // Consider only compare instructions uniquely controlling a branch
695 ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
699 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
702 for (auto *CmpU : Cmp->users()) {
703 BranchInst *BI = dyn_cast<BranchInst>(CmpU);
704 if (!BI || BI->isUnconditional())
706 // We're looking for conditions that are guaranteed to hold at the
707 // context instruction. Finding a condition where one path dominates
708 // the context isn't enough because both the true and false cases could
709 // merge before the context instruction we're actually interested in.
710 // Instead, we need to ensure that the taken *edge* dominates the context
712 BasicBlock *BB0 = BI->getSuccessor(0);
713 BasicBlockEdge Edge(BI->getParent(), BB0);
714 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
717 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
723 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
724 APInt &KnownOne, const DataLayout &DL,
725 unsigned Depth, const Query &Q) {
726 // Use of assumptions is context-sensitive. If we don't have a context, we
728 if (!Q.AC || !Q.CxtI)
731 unsigned BitWidth = KnownZero.getBitWidth();
733 for (auto &AssumeVH : Q.AC->assumptions()) {
736 CallInst *I = cast<CallInst>(AssumeVH);
737 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
738 "Got assumption for the wrong function!");
739 if (Q.ExclInvs.count(I))
742 // Warning: This loop can end up being somewhat performance sensetive.
743 // We're running this loop for once for each value queried resulting in a
744 // runtime of ~O(#assumes * #values).
746 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
747 "must be an assume intrinsic");
749 Value *Arg = I->getArgOperand(0);
751 if (Arg == V && isValidAssumeForContext(I, Q)) {
752 assert(BitWidth == 1 && "assume operand is not i1?");
753 KnownZero.clearAllBits();
754 KnownOne.setAllBits();
758 // The remaining tests are all recursive, so bail out if we hit the limit.
759 if (Depth == MaxDepth)
763 auto m_V = m_CombineOr(m_Specific(V),
764 m_CombineOr(m_PtrToInt(m_Specific(V)),
765 m_BitCast(m_Specific(V))));
767 CmpInst::Predicate Pred;
770 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
771 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
772 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
773 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
774 KnownZero |= RHSKnownZero;
775 KnownOne |= RHSKnownOne;
777 } else if (match(Arg,
778 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
779 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
780 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
781 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
782 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
783 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
785 // For those bits in the mask that are known to be one, we can propagate
786 // known bits from the RHS to V.
787 KnownZero |= RHSKnownZero & MaskKnownOne;
788 KnownOne |= RHSKnownOne & MaskKnownOne;
789 // assume(~(v & b) = a)
790 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
792 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
793 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
794 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
795 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
796 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
798 // For those bits in the mask that are known to be one, we can propagate
799 // inverted known bits from the RHS to V.
800 KnownZero |= RHSKnownOne & MaskKnownOne;
801 KnownOne |= RHSKnownZero & MaskKnownOne;
803 } else if (match(Arg,
804 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
805 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
806 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
807 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
808 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
809 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
811 // For those bits in B that are known to be zero, we can propagate known
812 // bits from the RHS to V.
813 KnownZero |= RHSKnownZero & BKnownZero;
814 KnownOne |= RHSKnownOne & BKnownZero;
815 // assume(~(v | b) = a)
816 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
818 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
819 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
820 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
821 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
822 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
824 // For those bits in B that are known to be zero, we can propagate
825 // inverted known bits from the RHS to V.
826 KnownZero |= RHSKnownOne & BKnownZero;
827 KnownOne |= RHSKnownZero & BKnownZero;
829 } else if (match(Arg,
830 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
831 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
832 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
833 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
834 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
835 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
837 // For those bits in B that are known to be zero, we can propagate known
838 // bits from the RHS to V. For those bits in B that are known to be one,
839 // we can propagate inverted known bits from the RHS to V.
840 KnownZero |= RHSKnownZero & BKnownZero;
841 KnownOne |= RHSKnownOne & BKnownZero;
842 KnownZero |= RHSKnownOne & BKnownOne;
843 KnownOne |= RHSKnownZero & BKnownOne;
844 // assume(~(v ^ b) = a)
845 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
847 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
848 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
849 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
850 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
851 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
853 // For those bits in B that are known to be zero, we can propagate
854 // inverted known bits from the RHS to V. For those bits in B that are
855 // known to be one, we can propagate known bits from the RHS to V.
856 KnownZero |= RHSKnownOne & BKnownZero;
857 KnownOne |= RHSKnownZero & BKnownZero;
858 KnownZero |= RHSKnownZero & BKnownOne;
859 KnownOne |= RHSKnownOne & BKnownOne;
860 // assume(v << c = a)
861 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
863 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
864 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
865 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
866 // For those bits in RHS that are known, we can propagate them to known
867 // bits in V shifted to the right by C.
868 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
869 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
870 // assume(~(v << c) = a)
871 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
873 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
874 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
875 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
876 // For those bits in RHS that are known, we can propagate them inverted
877 // to known bits in V shifted to the right by C.
878 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
879 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
880 // assume(v >> c = a)
881 } else if (match(Arg,
882 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
883 m_AShr(m_V, m_ConstantInt(C))),
885 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
886 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
887 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
888 // For those bits in RHS that are known, we can propagate them to known
889 // bits in V shifted to the right by C.
890 KnownZero |= RHSKnownZero << C->getZExtValue();
891 KnownOne |= RHSKnownOne << C->getZExtValue();
892 // assume(~(v >> c) = a)
893 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
894 m_LShr(m_V, m_ConstantInt(C)),
895 m_AShr(m_V, m_ConstantInt(C)))),
897 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
898 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
899 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
900 // For those bits in RHS that are known, we can propagate them inverted
901 // to known bits in V shifted to the right by C.
902 KnownZero |= RHSKnownOne << C->getZExtValue();
903 KnownOne |= RHSKnownZero << C->getZExtValue();
904 // assume(v >=_s c) where c is non-negative
905 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
906 Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
907 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
908 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
910 if (RHSKnownZero.isNegative()) {
911 // We know that the sign bit is zero.
912 KnownZero |= APInt::getSignBit(BitWidth);
914 // assume(v >_s c) where c is at least -1.
915 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
916 Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
917 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
918 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
920 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
921 // We know that the sign bit is zero.
922 KnownZero |= APInt::getSignBit(BitWidth);
924 // assume(v <=_s c) where c is negative
925 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
926 Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
927 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
928 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
930 if (RHSKnownOne.isNegative()) {
931 // We know that the sign bit is one.
932 KnownOne |= APInt::getSignBit(BitWidth);
934 // assume(v <_s c) where c is non-positive
935 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
936 Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
937 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
938 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
940 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
941 // We know that the sign bit is one.
942 KnownOne |= APInt::getSignBit(BitWidth);
945 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
946 Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
947 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
948 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
950 // Whatever high bits in c are zero are known to be zero.
952 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
954 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
955 Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
956 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
957 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
959 // Whatever high bits in c are zero are known to be zero (if c is a power
960 // of 2, then one more).
961 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
963 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
966 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
971 // Compute known bits from a shift operator, including those with a
972 // non-constant shift amount. KnownZero and KnownOne are the outputs of this
973 // function. KnownZero2 and KnownOne2 are pre-allocated temporaries with the
974 // same bit width as KnownZero and KnownOne. KZF and KOF are operator-specific
975 // functors that, given the known-zero or known-one bits respectively, and a
976 // shift amount, compute the implied known-zero or known-one bits of the shift
977 // operator's result respectively for that shift amount. The results from calling
978 // KZF and KOF are conservatively combined for all permitted shift amounts.
979 template <typename KZFunctor, typename KOFunctor>
980 static void computeKnownBitsFromShiftOperator(Operator *I,
981 APInt &KnownZero, APInt &KnownOne,
982 APInt &KnownZero2, APInt &KnownOne2,
983 const DataLayout &DL, unsigned Depth, const Query &Q,
984 KZFunctor KZF, KOFunctor KOF) {
985 unsigned BitWidth = KnownZero.getBitWidth();
987 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
988 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
990 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
991 KnownZero = KZF(KnownZero, ShiftAmt);
992 KnownOne = KOF(KnownOne, ShiftAmt);
996 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
998 // Note: We cannot use KnownZero.getLimitedValue() here, because if
999 // BitWidth > 64 and any upper bits are known, we'll end up returning the
1000 // limit value (which implies all bits are known).
1001 uint64_t ShiftAmtKZ = KnownZero.zextOrTrunc(64).getZExtValue();
1002 uint64_t ShiftAmtKO = KnownOne.zextOrTrunc(64).getZExtValue();
1004 // It would be more-clearly correct to use the two temporaries for this
1005 // calculation. Reusing the APInts here to prevent unnecessary allocations.
1006 KnownZero.clearAllBits(), KnownOne.clearAllBits();
1008 // If we know the shifter operand is nonzero, we can sometimes infer more
1009 // known bits. However this is expensive to compute, so be lazy about it and
1010 // only compute it when absolutely necessary.
1011 Optional<bool> ShifterOperandIsNonZero;
1013 // Early exit if we can't constrain any well-defined shift amount.
1014 if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
1015 ShifterOperandIsNonZero =
1016 isKnownNonZero(I->getOperand(1), DL, Depth + 1, Q);
1017 if (!*ShifterOperandIsNonZero)
1021 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1023 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
1024 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
1025 // Combine the shifted known input bits only for those shift amounts
1026 // compatible with its known constraints.
1027 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
1029 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
1031 // If we know the shifter is nonzero, we may be able to infer more known
1032 // bits. This check is sunk down as far as possible to avoid the expensive
1033 // call to isKnownNonZero if the cheaper checks above fail.
1034 if (ShiftAmt == 0) {
1035 if (!ShifterOperandIsNonZero.hasValue())
1036 ShifterOperandIsNonZero =
1037 isKnownNonZero(I->getOperand(1), DL, Depth + 1, Q);
1038 if (*ShifterOperandIsNonZero)
1042 KnownZero &= KZF(KnownZero2, ShiftAmt);
1043 KnownOne &= KOF(KnownOne2, ShiftAmt);
1046 // If there are no compatible shift amounts, then we've proven that the shift
1047 // amount must be >= the BitWidth, and the result is undefined. We could
1048 // return anything we'd like, but we need to make sure the sets of known bits
1049 // stay disjoint (it should be better for some other code to actually
1050 // propagate the undef than to pick a value here using known bits).
1051 if ((KnownZero & KnownOne) != 0)
1052 KnownZero.clearAllBits(), KnownOne.clearAllBits();
1055 static void computeKnownBitsFromOperator(Operator *I, APInt &KnownZero,
1056 APInt &KnownOne, const DataLayout &DL,
1057 unsigned Depth, const Query &Q) {
1058 unsigned BitWidth = KnownZero.getBitWidth();
1060 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
1061 switch (I->getOpcode()) {
1063 case Instruction::Load:
1064 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
1065 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1067 case Instruction::And: {
1068 // If either the LHS or the RHS are Zero, the result is zero.
1069 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1070 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1072 // Output known-1 bits are only known if set in both the LHS & RHS.
1073 KnownOne &= KnownOne2;
1074 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1075 KnownZero |= KnownZero2;
1078 case Instruction::Or: {
1079 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1080 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1082 // Output known-0 bits are only known if clear in both the LHS & RHS.
1083 KnownZero &= KnownZero2;
1084 // Output known-1 are known to be set if set in either the LHS | RHS.
1085 KnownOne |= KnownOne2;
1088 case Instruction::Xor: {
1089 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1090 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1092 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1093 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1094 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1095 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1096 KnownZero = KnownZeroOut;
1099 case Instruction::Mul: {
1100 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1101 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
1102 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1105 case Instruction::UDiv: {
1106 // For the purposes of computing leading zeros we can conservatively
1107 // treat a udiv as a logical right shift by the power of 2 known to
1108 // be less than the denominator.
1109 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1110 unsigned LeadZ = KnownZero2.countLeadingOnes();
1112 KnownOne2.clearAllBits();
1113 KnownZero2.clearAllBits();
1114 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1115 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1116 if (RHSUnknownLeadingOnes != BitWidth)
1117 LeadZ = std::min(BitWidth,
1118 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1120 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1123 case Instruction::Select:
1124 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
1125 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1127 // Only known if known in both the LHS and RHS.
1128 KnownOne &= KnownOne2;
1129 KnownZero &= KnownZero2;
1131 case Instruction::FPTrunc:
1132 case Instruction::FPExt:
1133 case Instruction::FPToUI:
1134 case Instruction::FPToSI:
1135 case Instruction::SIToFP:
1136 case Instruction::UIToFP:
1137 break; // Can't work with floating point.
1138 case Instruction::PtrToInt:
1139 case Instruction::IntToPtr:
1140 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
1141 // FALL THROUGH and handle them the same as zext/trunc.
1142 case Instruction::ZExt:
1143 case Instruction::Trunc: {
1144 Type *SrcTy = I->getOperand(0)->getType();
1146 unsigned SrcBitWidth;
1147 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1148 // which fall through here.
1149 SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
1151 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1152 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1153 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
1154 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1155 KnownZero = KnownZero.zextOrTrunc(BitWidth);
1156 KnownOne = KnownOne.zextOrTrunc(BitWidth);
1157 // Any top bits are known to be zero.
1158 if (BitWidth > SrcBitWidth)
1159 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1162 case Instruction::BitCast: {
1163 Type *SrcTy = I->getOperand(0)->getType();
1164 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy() ||
1165 SrcTy->isFloatingPointTy()) &&
1166 // TODO: For now, not handling conversions like:
1167 // (bitcast i64 %x to <2 x i32>)
1168 !I->getType()->isVectorTy()) {
1169 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1174 case Instruction::SExt: {
1175 // Compute the bits in the result that are not present in the input.
1176 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1178 KnownZero = KnownZero.trunc(SrcBitWidth);
1179 KnownOne = KnownOne.trunc(SrcBitWidth);
1180 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1181 KnownZero = KnownZero.zext(BitWidth);
1182 KnownOne = KnownOne.zext(BitWidth);
1184 // If the sign bit of the input is known set or clear, then we know the
1185 // top bits of the result.
1186 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
1187 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1188 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
1189 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1192 case Instruction::Shl: {
1193 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1194 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1195 return (KnownZero << ShiftAmt) |
1196 APInt::getLowBitsSet(BitWidth, ShiftAmt); // Low bits known 0.
1199 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1200 return KnownOne << ShiftAmt;
1203 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1204 KnownZero2, KnownOne2, DL, Depth, Q,
1208 case Instruction::LShr: {
1209 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1210 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1211 return APIntOps::lshr(KnownZero, ShiftAmt) |
1212 // High bits known zero.
1213 APInt::getHighBitsSet(BitWidth, ShiftAmt);
1216 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1217 return APIntOps::lshr(KnownOne, ShiftAmt);
1220 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1221 KnownZero2, KnownOne2, DL, Depth, Q,
1225 case Instruction::AShr: {
1226 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1227 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1228 return APIntOps::ashr(KnownZero, ShiftAmt);
1231 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1232 return APIntOps::ashr(KnownOne, ShiftAmt);
1235 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1236 KnownZero2, KnownOne2, DL, Depth, Q,
1240 case Instruction::Sub: {
1241 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1242 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1243 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1247 case Instruction::Add: {
1248 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1249 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1250 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1254 case Instruction::SRem:
1255 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256 APInt RA = Rem->getValue().abs();
1257 if (RA.isPowerOf2()) {
1258 APInt LowBits = RA - 1;
1259 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
1262 // The low bits of the first operand are unchanged by the srem.
1263 KnownZero = KnownZero2 & LowBits;
1264 KnownOne = KnownOne2 & LowBits;
1266 // If the first operand is non-negative or has all low bits zero, then
1267 // the upper bits are all zero.
1268 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1269 KnownZero |= ~LowBits;
1271 // If the first operand is negative and not all low bits are zero, then
1272 // the upper bits are all one.
1273 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1274 KnownOne |= ~LowBits;
1276 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1280 // The sign bit is the LHS's sign bit, except when the result of the
1281 // remainder is zero.
1282 if (KnownZero.isNonNegative()) {
1283 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1284 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
1286 // If it's known zero, our sign bit is also zero.
1287 if (LHSKnownZero.isNegative())
1288 KnownZero.setBit(BitWidth - 1);
1292 case Instruction::URem: {
1293 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1294 APInt RA = Rem->getValue();
1295 if (RA.isPowerOf2()) {
1296 APInt LowBits = (RA - 1);
1297 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1299 KnownZero |= ~LowBits;
1300 KnownOne &= LowBits;
1305 // Since the result is less than or equal to either operand, any leading
1306 // zero bits in either operand must also exist in the result.
1307 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1308 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1310 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1311 KnownZero2.countLeadingOnes());
1312 KnownOne.clearAllBits();
1313 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1317 case Instruction::Alloca: {
1318 AllocaInst *AI = cast<AllocaInst>(I);
1319 unsigned Align = AI->getAlignment();
1321 Align = DL.getABITypeAlignment(AI->getType()->getElementType());
1324 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1327 case Instruction::GetElementPtr: {
1328 // Analyze all of the subscripts of this getelementptr instruction
1329 // to determine if we can prove known low zero bits.
1330 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1331 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
1333 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1335 gep_type_iterator GTI = gep_type_begin(I);
1336 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1337 Value *Index = I->getOperand(i);
1338 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1339 // Handle struct member offset arithmetic.
1341 // Handle case when index is vector zeroinitializer
1342 Constant *CIndex = cast<Constant>(Index);
1343 if (CIndex->isZeroValue())
1346 if (CIndex->getType()->isVectorTy())
1347 Index = CIndex->getSplatValue();
1349 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1350 const StructLayout *SL = DL.getStructLayout(STy);
1351 uint64_t Offset = SL->getElementOffset(Idx);
1352 TrailZ = std::min<unsigned>(TrailZ,
1353 countTrailingZeros(Offset));
1355 // Handle array index arithmetic.
1356 Type *IndexedTy = GTI.getIndexedType();
1357 if (!IndexedTy->isSized()) {
1361 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1362 uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
1363 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1364 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
1366 TrailZ = std::min(TrailZ,
1367 unsigned(countTrailingZeros(TypeSize) +
1368 LocalKnownZero.countTrailingOnes()));
1372 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1375 case Instruction::PHI: {
1376 PHINode *P = cast<PHINode>(I);
1377 // Handle the case of a simple two-predecessor recurrence PHI.
1378 // There's a lot more that could theoretically be done here, but
1379 // this is sufficient to catch some interesting cases.
1380 if (P->getNumIncomingValues() == 2) {
1381 for (unsigned i = 0; i != 2; ++i) {
1382 Value *L = P->getIncomingValue(i);
1383 Value *R = P->getIncomingValue(!i);
1384 Operator *LU = dyn_cast<Operator>(L);
1387 unsigned Opcode = LU->getOpcode();
1388 // Check for operations that have the property that if
1389 // both their operands have low zero bits, the result
1390 // will have low zero bits.
1391 if (Opcode == Instruction::Add ||
1392 Opcode == Instruction::Sub ||
1393 Opcode == Instruction::And ||
1394 Opcode == Instruction::Or ||
1395 Opcode == Instruction::Mul) {
1396 Value *LL = LU->getOperand(0);
1397 Value *LR = LU->getOperand(1);
1398 // Find a recurrence.
1405 // Ok, we have a PHI of the form L op= R. Check for low
1407 computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
1409 // We need to take the minimum number of known bits
1410 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1411 computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
1413 KnownZero = APInt::getLowBitsSet(BitWidth,
1414 std::min(KnownZero2.countTrailingOnes(),
1415 KnownZero3.countTrailingOnes()));
1421 // Unreachable blocks may have zero-operand PHI nodes.
1422 if (P->getNumIncomingValues() == 0)
1425 // Otherwise take the unions of the known bit sets of the operands,
1426 // taking conservative care to avoid excessive recursion.
1427 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1428 // Skip if every incoming value references to ourself.
1429 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1432 KnownZero = APInt::getAllOnesValue(BitWidth);
1433 KnownOne = APInt::getAllOnesValue(BitWidth);
1434 for (Value *IncValue : P->incoming_values()) {
1435 // Skip direct self references.
1436 if (IncValue == P) continue;
1438 KnownZero2 = APInt(BitWidth, 0);
1439 KnownOne2 = APInt(BitWidth, 0);
1440 // Recurse, but cap the recursion to one level, because we don't
1441 // want to waste time spinning around in loops.
1442 computeKnownBits(IncValue, KnownZero2, KnownOne2, DL,
1444 KnownZero &= KnownZero2;
1445 KnownOne &= KnownOne2;
1446 // If all bits have been ruled out, there's no need to check
1448 if (!KnownZero && !KnownOne)
1454 case Instruction::Call:
1455 case Instruction::Invoke:
1456 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1457 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1458 // If a range metadata is attached to this IntrinsicInst, intersect the
1459 // explicit range specified by the metadata and the implicit range of
1461 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1462 switch (II->getIntrinsicID()) {
1464 case Intrinsic::bswap:
1465 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL,
1467 KnownZero |= KnownZero2.byteSwap();
1468 KnownOne |= KnownOne2.byteSwap();
1470 case Intrinsic::ctlz:
1471 case Intrinsic::cttz: {
1472 unsigned LowBits = Log2_32(BitWidth)+1;
1473 // If this call is undefined for 0, the result will be less than 2^n.
1474 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1476 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1479 case Intrinsic::ctpop: {
1480 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL,
1482 // We can bound the space the count needs. Also, bits known to be zero
1483 // can't contribute to the population.
1484 unsigned BitsPossiblySet = BitWidth - KnownZero2.countPopulation();
1485 unsigned LeadingZeros =
1486 APInt(BitWidth, BitsPossiblySet).countLeadingZeros();
1487 assert(LeadingZeros <= BitWidth);
1488 KnownZero |= APInt::getHighBitsSet(BitWidth, LeadingZeros);
1489 KnownOne &= ~KnownZero;
1490 // TODO: we could bound KnownOne using the lower bound on the number
1491 // of bits which might be set provided by popcnt KnownOne2.
1494 case Intrinsic::fabs: {
1495 Type *Ty = II->getType();
1496 APInt SignBit = APInt::getSignBit(Ty->getScalarSizeInBits());
1497 KnownZero |= APInt::getSplat(Ty->getPrimitiveSizeInBits(), SignBit);
1500 case Intrinsic::x86_sse42_crc32_64_64:
1501 KnownZero |= APInt::getHighBitsSet(64, 32);
1506 case Instruction::ExtractValue:
1507 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1508 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1509 if (EVI->getNumIndices() != 1) break;
1510 if (EVI->getIndices()[0] == 0) {
1511 switch (II->getIntrinsicID()) {
1513 case Intrinsic::uadd_with_overflow:
1514 case Intrinsic::sadd_with_overflow:
1515 computeKnownBitsAddSub(true, II->getArgOperand(0),
1516 II->getArgOperand(1), false, KnownZero,
1517 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1519 case Intrinsic::usub_with_overflow:
1520 case Intrinsic::ssub_with_overflow:
1521 computeKnownBitsAddSub(false, II->getArgOperand(0),
1522 II->getArgOperand(1), false, KnownZero,
1523 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1525 case Intrinsic::umul_with_overflow:
1526 case Intrinsic::smul_with_overflow:
1527 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1528 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1537 static unsigned getAlignment(const Value *V, const DataLayout &DL) {
1539 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1540 Align = GO->getAlignment();
1542 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
1543 Type *ObjectType = GVar->getType()->getElementType();
1544 if (ObjectType->isSized()) {
1545 // If the object is defined in the current Module, we'll be giving
1546 // it the preferred alignment. Otherwise, we have to assume that it
1547 // may only have the minimum ABI alignment.
1548 if (GVar->isStrongDefinitionForLinker())
1549 Align = DL.getPreferredAlignment(GVar);
1551 Align = DL.getABITypeAlignment(ObjectType);
1555 } else if (const Argument *A = dyn_cast<Argument>(V)) {
1556 Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
1558 if (!Align && A->hasStructRetAttr()) {
1559 // An sret parameter has at least the ABI alignment of the return type.
1560 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
1561 if (EltTy->isSized())
1562 Align = DL.getABITypeAlignment(EltTy);
1564 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
1565 Align = AI->getAlignment();
1566 else if (auto CS = ImmutableCallSite(V))
1567 Align = CS.getAttributes().getParamAlignment(AttributeSet::ReturnIndex);
1568 else if (const LoadInst *LI = dyn_cast<LoadInst>(V))
1569 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
1570 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
1571 Align = CI->getLimitedValue();
1577 /// Determine which bits of V are known to be either zero or one and return
1578 /// them in the KnownZero/KnownOne bit sets.
1580 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1581 /// we cannot optimize based on the assumption that it is zero without changing
1582 /// it to be an explicit zero. If we don't change it to zero, other code could
1583 /// optimized based on the contradictory assumption that it is non-zero.
1584 /// Because instcombine aggressively folds operations with undef args anyway,
1585 /// this won't lose us code quality.
1587 /// This function is defined on values with integer type, values with pointer
1588 /// type, and vectors of integers. In the case
1589 /// where V is a vector, known zero, and known one values are the
1590 /// same width as the vector element, and the bit is set only if it is true
1591 /// for all of the elements in the vector.
1592 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
1593 const DataLayout &DL, unsigned Depth, const Query &Q) {
1594 assert(V && "No Value?");
1595 assert(Depth <= MaxDepth && "Limit Search Depth");
1596 unsigned BitWidth = KnownZero.getBitWidth();
1598 assert((V->getType()->isIntOrIntVectorTy() ||
1599 V->getType()->isFPOrFPVectorTy() ||
1600 V->getType()->getScalarType()->isPointerTy()) &&
1601 "Not integer, floating point, or pointer type!");
1602 assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
1603 (!V->getType()->isIntOrIntVectorTy() ||
1604 V->getType()->getScalarSizeInBits() == BitWidth) &&
1605 KnownZero.getBitWidth() == BitWidth &&
1606 KnownOne.getBitWidth() == BitWidth &&
1607 "V, KnownOne and KnownZero should have same BitWidth");
1609 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1610 // We know all of the bits for a constant!
1611 KnownOne = CI->getValue();
1612 KnownZero = ~KnownOne;
1615 // Null and aggregate-zero are all-zeros.
1616 if (isa<ConstantPointerNull>(V) ||
1617 isa<ConstantAggregateZero>(V)) {
1618 KnownOne.clearAllBits();
1619 KnownZero = APInt::getAllOnesValue(BitWidth);
1622 // Handle a constant vector by taking the intersection of the known bits of
1623 // each element. There is no real need to handle ConstantVector here, because
1624 // we don't handle undef in any particularly useful way.
1625 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1626 // We know that CDS must be a vector of integers. Take the intersection of
1628 KnownZero.setAllBits(); KnownOne.setAllBits();
1629 APInt Elt(KnownZero.getBitWidth(), 0);
1630 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1631 Elt = CDS->getElementAsInteger(i);
1638 // Start out not knowing anything.
1639 KnownZero.clearAllBits(); KnownOne.clearAllBits();
1641 // Limit search depth.
1642 // All recursive calls that increase depth must come after this.
1643 if (Depth == MaxDepth)
1646 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1647 // the bits of its aliasee.
1648 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1649 if (!GA->mayBeOverridden())
1650 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
1654 if (Operator *I = dyn_cast<Operator>(V))
1655 computeKnownBitsFromOperator(I, KnownZero, KnownOne, DL, Depth, Q);
1657 // Aligned pointers have trailing zeros - refine KnownZero set
1658 if (V->getType()->isPointerTy()) {
1659 unsigned Align = getAlignment(V, DL);
1661 KnownZero |= APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1664 // computeKnownBitsFromAssume and computeKnownBitsFromDominatingCondition
1665 // strictly refines KnownZero and KnownOne. Therefore, we run them after
1666 // computeKnownBitsFromOperator.
1668 // Check whether a nearby assume intrinsic can determine some known bits.
1669 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
1671 // Check whether there's a dominating condition which implies something about
1672 // this value at the given context.
1673 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1674 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL, Depth,
1677 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1680 /// Determine whether the sign bit is known to be zero or one.
1681 /// Convenience wrapper around computeKnownBits.
1682 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1683 const DataLayout &DL, unsigned Depth, const Query &Q) {
1684 unsigned BitWidth = getBitWidth(V->getType(), DL);
1690 APInt ZeroBits(BitWidth, 0);
1691 APInt OneBits(BitWidth, 0);
1692 computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
1693 KnownOne = OneBits[BitWidth - 1];
1694 KnownZero = ZeroBits[BitWidth - 1];
1697 /// Return true if the given value is known to have exactly one
1698 /// bit set when defined. For vectors return true if every element is known to
1699 /// be a power of two when defined. Supports values with integer or pointer
1700 /// types and vectors of integers.
1701 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1702 const Query &Q, const DataLayout &DL) {
1703 if (Constant *C = dyn_cast<Constant>(V)) {
1704 if (C->isNullValue())
1706 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1707 return CI->getValue().isPowerOf2();
1708 // TODO: Handle vector constants.
1711 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1712 // it is shifted off the end then the result is undefined.
1713 if (match(V, m_Shl(m_One(), m_Value())))
1716 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1717 // bottom. If it is shifted off the bottom then the result is undefined.
1718 if (match(V, m_LShr(m_SignBit(), m_Value())))
1721 // The remaining tests are all recursive, so bail out if we hit the limit.
1722 if (Depth++ == MaxDepth)
1725 Value *X = nullptr, *Y = nullptr;
1726 // A shift of a power of two is a power of two or zero.
1727 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1728 match(V, m_Shr(m_Value(X), m_Value()))))
1729 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
1731 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1732 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
1734 if (SelectInst *SI = dyn_cast<SelectInst>(V))
1735 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
1736 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
1738 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1739 // A power of two and'd with anything is a power of two or zero.
1740 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
1741 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
1743 // X & (-X) is always a power of two or zero.
1744 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1749 // Adding a power-of-two or zero to the same power-of-two or zero yields
1750 // either the original power-of-two, a larger power-of-two or zero.
1751 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1752 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1753 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1754 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1755 match(X, m_And(m_Value(), m_Specific(Y))))
1756 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
1758 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1759 match(Y, m_And(m_Value(), m_Specific(X))))
1760 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
1763 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1764 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1765 computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
1767 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1768 computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
1769 // If i8 V is a power of two or zero:
1770 // ZeroBits: 1 1 1 0 1 1 1 1
1771 // ~ZeroBits: 0 0 0 1 0 0 0 0
1772 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1773 // If OrZero isn't set, we cannot give back a zero result.
1774 // Make sure either the LHS or RHS has a bit set.
1775 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1780 // An exact divide or right shift can only shift off zero bits, so the result
1781 // is a power of two only if the first operand is a power of two and not
1782 // copying a sign bit (sdiv int_min, 2).
1783 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1784 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1785 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1792 /// \brief Test whether a GEP's result is known to be non-null.
1794 /// Uses properties inherent in a GEP to try to determine whether it is known
1797 /// Currently this routine does not support vector GEPs.
1798 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
1799 unsigned Depth, const Query &Q) {
1800 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1803 // FIXME: Support vector-GEPs.
1804 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1806 // If the base pointer is non-null, we cannot walk to a null address with an
1807 // inbounds GEP in address space zero.
1808 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
1811 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1812 // If so, then the GEP cannot produce a null pointer, as doing so would
1813 // inherently violate the inbounds contract within address space zero.
1814 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1815 GTI != GTE; ++GTI) {
1816 // Struct types are easy -- they must always be indexed by a constant.
1817 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1818 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1819 unsigned ElementIdx = OpC->getZExtValue();
1820 const StructLayout *SL = DL.getStructLayout(STy);
1821 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1822 if (ElementOffset > 0)
1827 // If we have a zero-sized type, the index doesn't matter. Keep looping.
1828 if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1831 // Fast path the constant operand case both for efficiency and so we don't
1832 // increment Depth when just zipping down an all-constant GEP.
1833 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1839 // We post-increment Depth here because while isKnownNonZero increments it
1840 // as well, when we pop back up that increment won't persist. We don't want
1841 // to recurse 10k times just because we have 10k GEP operands. We don't
1842 // bail completely out because we want to handle constant GEPs regardless
1844 if (Depth++ >= MaxDepth)
1847 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
1854 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1855 /// ensure that the value it's attached to is never Value? 'RangeType' is
1856 /// is the type of the value described by the range.
1857 static bool rangeMetadataExcludesValue(MDNode* Ranges,
1858 const APInt& Value) {
1859 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1860 assert(NumRanges >= 1);
1861 for (unsigned i = 0; i < NumRanges; ++i) {
1862 ConstantInt *Lower =
1863 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1864 ConstantInt *Upper =
1865 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1866 ConstantRange Range(Lower->getValue(), Upper->getValue());
1867 if (Range.contains(Value))
1873 /// Return true if the given value is known to be non-zero when defined.
1874 /// For vectors return true if every element is known to be non-zero when
1875 /// defined. Supports values with integer or pointer type and vectors of
1877 bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
1879 if (Constant *C = dyn_cast<Constant>(V)) {
1880 if (C->isNullValue())
1882 if (isa<ConstantInt>(C))
1883 // Must be non-zero due to null test above.
1885 // TODO: Handle vectors
1889 if (Instruction* I = dyn_cast<Instruction>(V)) {
1890 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1891 // If the possible ranges don't contain zero, then the value is
1892 // definitely non-zero.
1893 if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1894 const APInt ZeroValue(Ty->getBitWidth(), 0);
1895 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1901 // The remaining tests are all recursive, so bail out if we hit the limit.
1902 if (Depth++ >= MaxDepth)
1905 // Check for pointer simplifications.
1906 if (V->getType()->isPointerTy()) {
1907 if (isKnownNonNull(V))
1909 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1910 if (isGEPKnownNonNull(GEP, DL, Depth, Q))
1914 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
1916 // X | Y != 0 if X != 0 or Y != 0.
1917 Value *X = nullptr, *Y = nullptr;
1918 if (match(V, m_Or(m_Value(X), m_Value(Y))))
1919 return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
1921 // ext X != 0 if X != 0.
1922 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1923 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
1925 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
1926 // if the lowest bit is shifted off the end.
1927 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1928 // shl nuw can't remove any non-zero bits.
1929 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1930 if (BO->hasNoUnsignedWrap())
1931 return isKnownNonZero(X, DL, Depth, Q);
1933 APInt KnownZero(BitWidth, 0);
1934 APInt KnownOne(BitWidth, 0);
1935 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1939 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
1940 // defined if the sign bit is shifted off the end.
1941 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1942 // shr exact can only shift out zero bits.
1943 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1945 return isKnownNonZero(X, DL, Depth, Q);
1947 bool XKnownNonNegative, XKnownNegative;
1948 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1952 // If the shifter operand is a constant, and all of the bits shifted
1953 // out are known to be zero, and X is known non-zero then at least one
1954 // non-zero bit must remain.
1955 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
1956 APInt KnownZero(BitWidth, 0);
1957 APInt KnownOne(BitWidth, 0);
1958 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1960 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1961 // Is there a known one in the portion not shifted out?
1962 if (KnownOne.countLeadingZeros() < BitWidth - ShiftVal)
1964 // Are all the bits to be shifted out known zero?
1965 if (KnownZero.countTrailingOnes() >= ShiftVal)
1966 return isKnownNonZero(X, DL, Depth, Q);
1969 // div exact can only produce a zero if the dividend is zero.
1970 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1971 return isKnownNonZero(X, DL, Depth, Q);
1974 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1975 bool XKnownNonNegative, XKnownNegative;
1976 bool YKnownNonNegative, YKnownNegative;
1977 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1978 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
1980 // If X and Y are both non-negative (as signed values) then their sum is not
1981 // zero unless both X and Y are zero.
1982 if (XKnownNonNegative && YKnownNonNegative)
1983 if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
1986 // If X and Y are both negative (as signed values) then their sum is not
1987 // zero unless both X and Y equal INT_MIN.
1988 if (BitWidth && XKnownNegative && YKnownNegative) {
1989 APInt KnownZero(BitWidth, 0);
1990 APInt KnownOne(BitWidth, 0);
1991 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1992 // The sign bit of X is set. If some other bit is set then X is not equal
1994 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1995 if ((KnownOne & Mask) != 0)
1997 // The sign bit of Y is set. If some other bit is set then Y is not equal
1999 computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
2000 if ((KnownOne & Mask) != 0)
2004 // The sum of a non-negative number and a power of two is not zero.
2005 if (XKnownNonNegative &&
2006 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
2008 if (YKnownNonNegative &&
2009 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
2013 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
2014 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2015 // If X and Y are non-zero then so is X * Y as long as the multiplication
2016 // does not overflow.
2017 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
2018 isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
2021 // (C ? X : Y) != 0 if X != 0 and Y != 0.
2022 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2023 if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
2024 isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
2028 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2029 // Try and detect a recurrence that monotonically increases from a
2030 // starting value, as these are common as induction variables.
2031 if (PN->getNumIncomingValues() == 2) {
2032 Value *Start = PN->getIncomingValue(0);
2033 Value *Induction = PN->getIncomingValue(1);
2034 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2035 std::swap(Start, Induction);
2036 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2037 if (!C->isZero() && !C->isNegative()) {
2039 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2040 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2048 if (!BitWidth) return false;
2049 APInt KnownZero(BitWidth, 0);
2050 APInt KnownOne(BitWidth, 0);
2051 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
2052 return KnownOne != 0;
2055 /// Return true if V2 == V1 + X, where X is known non-zero.
2056 static bool isAddOfNonZero(Value *V1, Value *V2, const DataLayout &DL,
2058 BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2059 if (!BO || BO->getOpcode() != Instruction::Add)
2061 Value *Op = nullptr;
2062 if (V2 == BO->getOperand(0))
2063 Op = BO->getOperand(1);
2064 else if (V2 == BO->getOperand(1))
2065 Op = BO->getOperand(0);
2068 return isKnownNonZero(Op, DL, 0, Q);
2071 /// Return true if it is known that V1 != V2.
2072 static bool isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
2074 if (V1->getType()->isVectorTy() || V1 == V2)
2076 if (V1->getType() != V2->getType())
2077 // We can't look through casts yet.
2079 if (isAddOfNonZero(V1, V2, DL, Q) || isAddOfNonZero(V2, V1, DL, Q))
2082 if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
2083 // Are any known bits in V1 contradictory to known bits in V2? If V1
2084 // has a known zero where V2 has a known one, they must not be equal.
2085 auto BitWidth = Ty->getBitWidth();
2086 APInt KnownZero1(BitWidth, 0);
2087 APInt KnownOne1(BitWidth, 0);
2088 computeKnownBits(V1, KnownZero1, KnownOne1, DL, 0, Q);
2089 APInt KnownZero2(BitWidth, 0);
2090 APInt KnownOne2(BitWidth, 0);
2091 computeKnownBits(V2, KnownZero2, KnownOne2, DL, 0, Q);
2093 auto OppositeBits = (KnownZero1 & KnownOne2) | (KnownZero2 & KnownOne1);
2094 if (OppositeBits.getBoolValue())
2100 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
2101 /// simplify operations downstream. Mask is known to be zero for bits that V
2104 /// This function is defined on values with integer type, values with pointer
2105 /// type, and vectors of integers. In the case
2106 /// where V is a vector, the mask, known zero, and known one values are the
2107 /// same width as the vector element, and the bit is set only if it is true
2108 /// for all of the elements in the vector.
2109 bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
2110 unsigned Depth, const Query &Q) {
2111 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
2112 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
2113 return (KnownZero & Mask) == Mask;
2118 /// Return the number of times the sign bit of the register is replicated into
2119 /// the other bits. We know that at least 1 bit is always equal to the sign bit
2120 /// (itself), but other cases can give us information. For example, immediately
2121 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2122 /// other, so we return 3.
2124 /// 'Op' must have a scalar integer type.
2126 unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
2128 unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
2130 unsigned FirstAnswer = 1;
2132 // Note that ConstantInt is handled by the general computeKnownBits case
2136 return 1; // Limit search depth.
2138 Operator *U = dyn_cast<Operator>(V);
2139 switch (Operator::getOpcode(V)) {
2141 case Instruction::SExt:
2142 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2143 return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
2145 case Instruction::SDiv: {
2146 const APInt *Denominator;
2147 // sdiv X, C -> adds log(C) sign bits.
2148 if (match(U->getOperand(1), m_APInt(Denominator))) {
2150 // Ignore non-positive denominator.
2151 if (!Denominator->isStrictlyPositive())
2154 // Calculate the incoming numerator bits.
2155 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2157 // Add floor(log(C)) bits to the numerator bits.
2158 return std::min(TyBits, NumBits + Denominator->logBase2());
2163 case Instruction::SRem: {
2164 const APInt *Denominator;
2165 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2166 // positive constant. This let us put a lower bound on the number of sign
2168 if (match(U->getOperand(1), m_APInt(Denominator))) {
2170 // Ignore non-positive denominator.
2171 if (!Denominator->isStrictlyPositive())
2174 // Calculate the incoming numerator bits. SRem by a positive constant
2175 // can't lower the number of sign bits.
2177 ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2179 // Calculate the leading sign bit constraints by examining the
2180 // denominator. Given that the denominator is positive, there are two
2183 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2184 // (1 << ceilLogBase2(C)).
2186 // 2. the numerator is negative. Then the result range is (-C,0] and
2187 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2189 // Thus a lower bound on the number of sign bits is `TyBits -
2190 // ceilLogBase2(C)`.
2192 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
2193 return std::max(NumrBits, ResBits);
2198 case Instruction::AShr: {
2199 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2200 // ashr X, C -> adds C sign bits. Vectors too.
2202 if (match(U->getOperand(1), m_APInt(ShAmt))) {
2203 Tmp += ShAmt->getZExtValue();
2204 if (Tmp > TyBits) Tmp = TyBits;
2208 case Instruction::Shl: {
2210 if (match(U->getOperand(1), m_APInt(ShAmt))) {
2211 // shl destroys sign bits.
2212 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2213 Tmp2 = ShAmt->getZExtValue();
2214 if (Tmp2 >= TyBits || // Bad shift.
2215 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2220 case Instruction::And:
2221 case Instruction::Or:
2222 case Instruction::Xor: // NOT is handled here.
2223 // Logical binary ops preserve the number of sign bits at the worst.
2224 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2226 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2227 FirstAnswer = std::min(Tmp, Tmp2);
2228 // We computed what we know about the sign bits as our first
2229 // answer. Now proceed to the generic code that uses
2230 // computeKnownBits, and pick whichever answer is better.
2234 case Instruction::Select:
2235 Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2236 if (Tmp == 1) return 1; // Early out.
2237 Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
2238 return std::min(Tmp, Tmp2);
2240 case Instruction::Add:
2241 // Add can have at most one carry bit. Thus we know that the output
2242 // is, at worst, one more bit than the inputs.
2243 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2244 if (Tmp == 1) return 1; // Early out.
2246 // Special case decrementing a value (ADD X, -1):
2247 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2248 if (CRHS->isAllOnesValue()) {
2249 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2250 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
2253 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2255 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2258 // If we are subtracting one from a positive number, there is no carry
2259 // out of the result.
2260 if (KnownZero.isNegative())
2264 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2265 if (Tmp2 == 1) return 1;
2266 return std::min(Tmp, Tmp2)-1;
2268 case Instruction::Sub:
2269 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2270 if (Tmp2 == 1) return 1;
2273 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2274 if (CLHS->isNullValue()) {
2275 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2276 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
2278 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2280 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2283 // If the input is known to be positive (the sign bit is known clear),
2284 // the output of the NEG has the same number of sign bits as the input.
2285 if (KnownZero.isNegative())
2288 // Otherwise, we treat this like a SUB.
2291 // Sub can have at most one carry bit. Thus we know that the output
2292 // is, at worst, one more bit than the inputs.
2293 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2294 if (Tmp == 1) return 1; // Early out.
2295 return std::min(Tmp, Tmp2)-1;
2297 case Instruction::PHI: {
2298 PHINode *PN = cast<PHINode>(U);
2299 unsigned NumIncomingValues = PN->getNumIncomingValues();
2300 // Don't analyze large in-degree PHIs.
2301 if (NumIncomingValues > 4) break;
2302 // Unreachable blocks may have zero-operand PHI nodes.
2303 if (NumIncomingValues == 0) break;
2305 // Take the minimum of all incoming values. This can't infinitely loop
2306 // because of our depth threshold.
2307 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
2308 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2309 if (Tmp == 1) return Tmp;
2311 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
2316 case Instruction::Trunc:
2317 // FIXME: it's tricky to do anything useful for this, but it is an important
2318 // case for targets like X86.
2322 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2323 // use this information.
2324 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2326 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
2328 if (KnownZero.isNegative()) { // sign bit is 0
2330 } else if (KnownOne.isNegative()) { // sign bit is 1;
2337 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2338 // the number of identical bits in the top of the input value.
2340 Mask <<= Mask.getBitWidth()-TyBits;
2341 // Return # leading zeros. We use 'min' here in case Val was zero before
2342 // shifting. We don't want to return '64' as for an i32 "0".
2343 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2346 /// This function computes the integer multiple of Base that equals V.
2347 /// If successful, it returns true and returns the multiple in
2348 /// Multiple. If unsuccessful, it returns false. It looks
2349 /// through SExt instructions only if LookThroughSExt is true.
2350 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2351 bool LookThroughSExt, unsigned Depth) {
2352 const unsigned MaxDepth = 6;
2354 assert(V && "No Value?");
2355 assert(Depth <= MaxDepth && "Limit Search Depth");
2356 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2358 Type *T = V->getType();
2360 ConstantInt *CI = dyn_cast<ConstantInt>(V);
2370 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2371 Constant *BaseVal = ConstantInt::get(T, Base);
2372 if (CO && CO == BaseVal) {
2374 Multiple = ConstantInt::get(T, 1);
2378 if (CI && CI->getZExtValue() % Base == 0) {
2379 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2383 if (Depth == MaxDepth) return false; // Limit search depth.
2385 Operator *I = dyn_cast<Operator>(V);
2386 if (!I) return false;
2388 switch (I->getOpcode()) {
2390 case Instruction::SExt:
2391 if (!LookThroughSExt) return false;
2392 // otherwise fall through to ZExt
2393 case Instruction::ZExt:
2394 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2395 LookThroughSExt, Depth+1);
2396 case Instruction::Shl:
2397 case Instruction::Mul: {
2398 Value *Op0 = I->getOperand(0);
2399 Value *Op1 = I->getOperand(1);
2401 if (I->getOpcode() == Instruction::Shl) {
2402 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2403 if (!Op1CI) return false;
2404 // Turn Op0 << Op1 into Op0 * 2^Op1
2405 APInt Op1Int = Op1CI->getValue();
2406 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2407 APInt API(Op1Int.getBitWidth(), 0);
2408 API.setBit(BitToSet);
2409 Op1 = ConstantInt::get(V->getContext(), API);
2412 Value *Mul0 = nullptr;
2413 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2414 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2415 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2416 if (Op1C->getType()->getPrimitiveSizeInBits() <
2417 MulC->getType()->getPrimitiveSizeInBits())
2418 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2419 if (Op1C->getType()->getPrimitiveSizeInBits() >
2420 MulC->getType()->getPrimitiveSizeInBits())
2421 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2423 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2424 Multiple = ConstantExpr::getMul(MulC, Op1C);
2428 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2429 if (Mul0CI->getValue() == 1) {
2430 // V == Base * Op1, so return Op1
2436 Value *Mul1 = nullptr;
2437 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2438 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2439 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2440 if (Op0C->getType()->getPrimitiveSizeInBits() <
2441 MulC->getType()->getPrimitiveSizeInBits())
2442 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2443 if (Op0C->getType()->getPrimitiveSizeInBits() >
2444 MulC->getType()->getPrimitiveSizeInBits())
2445 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2447 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2448 Multiple = ConstantExpr::getMul(MulC, Op0C);
2452 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2453 if (Mul1CI->getValue() == 1) {
2454 // V == Base * Op0, so return Op0
2462 // We could not determine if V is a multiple of Base.
2466 /// Return true if we can prove that the specified FP value is never equal to
2469 /// NOTE: this function will need to be revisited when we support non-default
2472 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2473 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2474 return !CFP->getValueAPF().isNegZero();
2476 // FIXME: Magic number! At the least, this should be given a name because it's
2477 // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2478 // expose it as a parameter, so it can be used for testing / experimenting.
2480 return false; // Limit search depth.
2482 const Operator *I = dyn_cast<Operator>(V);
2483 if (!I) return false;
2485 // Check if the nsz fast-math flag is set
2486 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2487 if (FPO->hasNoSignedZeros())
2490 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2491 if (I->getOpcode() == Instruction::FAdd)
2492 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2493 if (CFP->isNullValue())
2496 // sitofp and uitofp turn into +0.0 for zero.
2497 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2500 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501 // sqrt(-0.0) = -0.0, no other negative results are possible.
2502 if (II->getIntrinsicID() == Intrinsic::sqrt)
2503 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
2505 if (const CallInst *CI = dyn_cast<CallInst>(I))
2506 if (const Function *F = CI->getCalledFunction()) {
2507 if (F->isDeclaration()) {
2509 if (F->getName() == "abs") return true;
2510 // fabs[lf](x) != -0.0
2511 if (F->getName() == "fabs") return true;
2512 if (F->getName() == "fabsf") return true;
2513 if (F->getName() == "fabsl") return true;
2514 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2515 F->getName() == "sqrtl")
2516 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
2523 bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2524 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2525 return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2527 // FIXME: Magic number! At the least, this should be given a name because it's
2528 // used similarly in CannotBeNegativeZero(). A better fix may be to
2529 // expose it as a parameter, so it can be used for testing / experimenting.
2531 return false; // Limit search depth.
2533 const Operator *I = dyn_cast<Operator>(V);
2534 if (!I) return false;
2536 switch (I->getOpcode()) {
2538 case Instruction::FMul:
2539 // x*x is always non-negative or a NaN.
2540 if (I->getOperand(0) == I->getOperand(1))
2543 case Instruction::FAdd:
2544 case Instruction::FDiv:
2545 case Instruction::FRem:
2546 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2547 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2548 case Instruction::FPExt:
2549 case Instruction::FPTrunc:
2550 // Widening/narrowing never change sign.
2551 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2552 case Instruction::Call:
2553 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2554 switch (II->getIntrinsicID()) {
2556 case Intrinsic::exp:
2557 case Intrinsic::exp2:
2558 case Intrinsic::fabs:
2559 case Intrinsic::sqrt:
2561 case Intrinsic::powi:
2562 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2563 // powi(x,n) is non-negative if n is even.
2564 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2567 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2568 case Intrinsic::fma:
2569 case Intrinsic::fmuladd:
2570 // x*x+y is non-negative if y is non-negative.
2571 return I->getOperand(0) == I->getOperand(1) &&
2572 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2579 /// If the specified value can be set by repeating the same byte in memory,
2580 /// return the i8 value that it is represented with. This is
2581 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2582 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2583 /// byte store (e.g. i16 0x1234), return null.
2584 Value *llvm::isBytewiseValue(Value *V) {
2585 // All byte-wide stores are splatable, even of arbitrary variables.
2586 if (V->getType()->isIntegerTy(8)) return V;
2588 // Handle 'null' ConstantArrayZero etc.
2589 if (Constant *C = dyn_cast<Constant>(V))
2590 if (C->isNullValue())
2591 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2593 // Constant float and double values can be handled as integer values if the
2594 // corresponding integer value is "byteable". An important case is 0.0.
2595 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2596 if (CFP->getType()->isFloatTy())
2597 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2598 if (CFP->getType()->isDoubleTy())
2599 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2600 // Don't handle long double formats, which have strange constraints.
2603 // We can handle constant integers that are multiple of 8 bits.
2604 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2605 if (CI->getBitWidth() % 8 == 0) {
2606 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
2608 if (!CI->getValue().isSplat(8))
2610 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
2614 // A ConstantDataArray/Vector is splatable if all its members are equal and
2616 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2617 Value *Elt = CA->getElementAsConstant(0);
2618 Value *Val = isBytewiseValue(Elt);
2622 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2623 if (CA->getElementAsConstant(I) != Elt)
2629 // Conceptually, we could handle things like:
2630 // %a = zext i8 %X to i16
2631 // %b = shl i16 %a, 8
2632 // %c = or i16 %a, %b
2633 // but until there is an example that actually needs this, it doesn't seem
2634 // worth worrying about.
2639 // This is the recursive version of BuildSubAggregate. It takes a few different
2640 // arguments. Idxs is the index within the nested struct From that we are
2641 // looking at now (which is of type IndexedType). IdxSkip is the number of
2642 // indices from Idxs that should be left out when inserting into the resulting
2643 // struct. To is the result struct built so far, new insertvalue instructions
2645 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2646 SmallVectorImpl<unsigned> &Idxs,
2648 Instruction *InsertBefore) {
2649 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2651 // Save the original To argument so we can modify it
2653 // General case, the type indexed by Idxs is a struct
2654 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2655 // Process each struct element recursively
2658 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2662 // Couldn't find any inserted value for this index? Cleanup
2663 while (PrevTo != OrigTo) {
2664 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2665 PrevTo = Del->getAggregateOperand();
2666 Del->eraseFromParent();
2668 // Stop processing elements
2672 // If we successfully found a value for each of our subaggregates
2676 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2677 // the struct's elements had a value that was inserted directly. In the latter
2678 // case, perhaps we can't determine each of the subelements individually, but
2679 // we might be able to find the complete struct somewhere.
2681 // Find the value that is at that particular spot
2682 Value *V = FindInsertedValue(From, Idxs);
2687 // Insert the value in the new (sub) aggregrate
2688 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2689 "tmp", InsertBefore);
2692 // This helper takes a nested struct and extracts a part of it (which is again a
2693 // struct) into a new value. For example, given the struct:
2694 // { a, { b, { c, d }, e } }
2695 // and the indices "1, 1" this returns
2698 // It does this by inserting an insertvalue for each element in the resulting
2699 // struct, as opposed to just inserting a single struct. This will only work if
2700 // each of the elements of the substruct are known (ie, inserted into From by an
2701 // insertvalue instruction somewhere).
2703 // All inserted insertvalue instructions are inserted before InsertBefore
2704 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2705 Instruction *InsertBefore) {
2706 assert(InsertBefore && "Must have someplace to insert!");
2707 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2709 Value *To = UndefValue::get(IndexedType);
2710 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2711 unsigned IdxSkip = Idxs.size();
2713 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2716 /// Given an aggregrate and an sequence of indices, see if
2717 /// the scalar value indexed is already around as a register, for example if it
2718 /// were inserted directly into the aggregrate.
2720 /// If InsertBefore is not null, this function will duplicate (modified)
2721 /// insertvalues when a part of a nested struct is extracted.
2722 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2723 Instruction *InsertBefore) {
2724 // Nothing to index? Just return V then (this is useful at the end of our
2726 if (idx_range.empty())
2728 // We have indices, so V should have an indexable type.
2729 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2730 "Not looking at a struct or array?");
2731 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2732 "Invalid indices for type?");
2734 if (Constant *C = dyn_cast<Constant>(V)) {
2735 C = C->getAggregateElement(idx_range[0]);
2736 if (!C) return nullptr;
2737 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2740 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2741 // Loop the indices for the insertvalue instruction in parallel with the
2742 // requested indices
2743 const unsigned *req_idx = idx_range.begin();
2744 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2745 i != e; ++i, ++req_idx) {
2746 if (req_idx == idx_range.end()) {
2747 // We can't handle this without inserting insertvalues
2751 // The requested index identifies a part of a nested aggregate. Handle
2752 // this specially. For example,
2753 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2754 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2755 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2756 // This can be changed into
2757 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2758 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2759 // which allows the unused 0,0 element from the nested struct to be
2761 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2765 // This insert value inserts something else than what we are looking for.
2766 // See if the (aggregate) value inserted into has the value we are
2767 // looking for, then.
2769 return FindInsertedValue(I->getAggregateOperand(), idx_range,
2772 // If we end up here, the indices of the insertvalue match with those
2773 // requested (though possibly only partially). Now we recursively look at
2774 // the inserted value, passing any remaining indices.
2775 return FindInsertedValue(I->getInsertedValueOperand(),
2776 makeArrayRef(req_idx, idx_range.end()),
2780 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2781 // If we're extracting a value from an aggregate that was extracted from
2782 // something else, we can extract from that something else directly instead.
2783 // However, we will need to chain I's indices with the requested indices.
2785 // Calculate the number of indices required
2786 unsigned size = I->getNumIndices() + idx_range.size();
2787 // Allocate some space to put the new indices in
2788 SmallVector<unsigned, 5> Idxs;
2790 // Add indices from the extract value instruction
2791 Idxs.append(I->idx_begin(), I->idx_end());
2793 // Add requested indices
2794 Idxs.append(idx_range.begin(), idx_range.end());
2796 assert(Idxs.size() == size
2797 && "Number of indices added not correct?");
2799 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2801 // Otherwise, we don't know (such as, extracting from a function return value
2802 // or load instruction)
2806 /// Analyze the specified pointer to see if it can be expressed as a base
2807 /// pointer plus a constant offset. Return the base and offset to the caller.
2808 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2809 const DataLayout &DL) {
2810 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
2811 APInt ByteOffset(BitWidth, 0);
2813 if (Ptr->getType()->isVectorTy())
2816 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2817 APInt GEPOffset(BitWidth, 0);
2818 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2821 ByteOffset += GEPOffset;
2823 Ptr = GEP->getPointerOperand();
2824 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2825 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2826 Ptr = cast<Operator>(Ptr)->getOperand(0);
2827 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2828 if (GA->mayBeOverridden())
2830 Ptr = GA->getAliasee();
2835 Offset = ByteOffset.getSExtValue();
2840 /// This function computes the length of a null-terminated C string pointed to
2841 /// by V. If successful, it returns true and returns the string in Str.
2842 /// If unsuccessful, it returns false.
2843 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2844 uint64_t Offset, bool TrimAtNul) {
2847 // Look through bitcast instructions and geps.
2848 V = V->stripPointerCasts();
2850 // If the value is a GEP instruction or constant expression, treat it as an
2852 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2853 // Make sure the GEP has exactly three arguments.
2854 if (GEP->getNumOperands() != 3)
2857 // Make sure the index-ee is a pointer to array of i8.
2858 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2859 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
2860 if (!AT || !AT->getElementType()->isIntegerTy(8))
2863 // Check to make sure that the first operand of the GEP is an integer and
2864 // has value 0 so that we are sure we're indexing into the initializer.
2865 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2866 if (!FirstIdx || !FirstIdx->isZero())
2869 // If the second index isn't a ConstantInt, then this is a variable index
2870 // into the array. If this occurs, we can't say anything meaningful about
2872 uint64_t StartIdx = 0;
2873 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2874 StartIdx = CI->getZExtValue();
2877 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
2881 // The GEP instruction, constant or instruction, must reference a global
2882 // variable that is a constant and is initialized. The referenced constant
2883 // initializer is the array that we'll use for optimization.
2884 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2885 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2888 // Handle the all-zeros case
2889 if (GV->getInitializer()->isNullValue()) {
2890 // This is a degenerate case. The initializer is constant zero so the
2891 // length of the string must be zero.
2896 // Must be a Constant Array
2897 const ConstantDataArray *Array =
2898 dyn_cast<ConstantDataArray>(GV->getInitializer());
2899 if (!Array || !Array->isString())
2902 // Get the number of elements in the array
2903 uint64_t NumElts = Array->getType()->getArrayNumElements();
2905 // Start out with the entire array in the StringRef.
2906 Str = Array->getAsString();
2908 if (Offset > NumElts)
2911 // Skip over 'offset' bytes.
2912 Str = Str.substr(Offset);
2915 // Trim off the \0 and anything after it. If the array is not nul
2916 // terminated, we just return the whole end of string. The client may know
2917 // some other way that the string is length-bound.
2918 Str = Str.substr(0, Str.find('\0'));
2923 // These next two are very similar to the above, but also look through PHI
2925 // TODO: See if we can integrate these two together.
2927 /// If we can compute the length of the string pointed to by
2928 /// the specified pointer, return 'len+1'. If we can't, return 0.
2929 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2930 // Look through noop bitcast instructions.
2931 V = V->stripPointerCasts();
2933 // If this is a PHI node, there are two cases: either we have already seen it
2935 if (PHINode *PN = dyn_cast<PHINode>(V)) {
2936 if (!PHIs.insert(PN).second)
2937 return ~0ULL; // already in the set.
2939 // If it was new, see if all the input strings are the same length.
2940 uint64_t LenSoFar = ~0ULL;
2941 for (Value *IncValue : PN->incoming_values()) {
2942 uint64_t Len = GetStringLengthH(IncValue, PHIs);
2943 if (Len == 0) return 0; // Unknown length -> unknown.
2945 if (Len == ~0ULL) continue;
2947 if (Len != LenSoFar && LenSoFar != ~0ULL)
2948 return 0; // Disagree -> unknown.
2952 // Success, all agree.
2956 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2957 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2958 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2959 if (Len1 == 0) return 0;
2960 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2961 if (Len2 == 0) return 0;
2962 if (Len1 == ~0ULL) return Len2;
2963 if (Len2 == ~0ULL) return Len1;
2964 if (Len1 != Len2) return 0;
2968 // Otherwise, see if we can read the string.
2970 if (!getConstantStringInfo(V, StrData))
2973 return StrData.size()+1;
2976 /// If we can compute the length of the string pointed to by
2977 /// the specified pointer, return 'len+1'. If we can't, return 0.
2978 uint64_t llvm::GetStringLength(Value *V) {
2979 if (!V->getType()->isPointerTy()) return 0;
2981 SmallPtrSet<PHINode*, 32> PHIs;
2982 uint64_t Len = GetStringLengthH(V, PHIs);
2983 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2984 // an empty string as a length.
2985 return Len == ~0ULL ? 1 : Len;
2988 /// \brief \p PN defines a loop-variant pointer to an object. Check if the
2989 /// previous iteration of the loop was referring to the same object as \p PN.
2990 static bool isSameUnderlyingObjectInLoop(PHINode *PN, LoopInfo *LI) {
2991 // Find the loop-defined value.
2992 Loop *L = LI->getLoopFor(PN->getParent());
2993 if (PN->getNumIncomingValues() != 2)
2996 // Find the value from previous iteration.
2997 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
2998 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
2999 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3000 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3003 // If a new pointer is loaded in the loop, the pointer references a different
3004 // object in every iteration. E.g.:
3008 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3009 if (!L->isLoopInvariant(Load->getPointerOperand()))
3014 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3015 unsigned MaxLookup) {
3016 if (!V->getType()->isPointerTy())
3018 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3019 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3020 V = GEP->getPointerOperand();
3021 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3022 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
3023 V = cast<Operator>(V)->getOperand(0);
3024 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
3025 if (GA->mayBeOverridden())
3027 V = GA->getAliasee();
3029 // See if InstructionSimplify knows any relevant tricks.
3030 if (Instruction *I = dyn_cast<Instruction>(V))
3031 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
3032 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
3039 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3044 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
3045 const DataLayout &DL, LoopInfo *LI,
3046 unsigned MaxLookup) {
3047 SmallPtrSet<Value *, 4> Visited;
3048 SmallVector<Value *, 4> Worklist;
3049 Worklist.push_back(V);
3051 Value *P = Worklist.pop_back_val();
3052 P = GetUnderlyingObject(P, DL, MaxLookup);
3054 if (!Visited.insert(P).second)
3057 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3058 Worklist.push_back(SI->getTrueValue());
3059 Worklist.push_back(SI->getFalseValue());
3063 if (PHINode *PN = dyn_cast<PHINode>(P)) {
3064 // If this PHI changes the underlying object in every iteration of the
3065 // loop, don't look through it. Consider:
3068 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3072 // Prev is tracking Curr one iteration behind so they refer to different
3073 // underlying objects.
3074 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3075 isSameUnderlyingObjectInLoop(PN, LI))
3076 for (Value *IncValue : PN->incoming_values())
3077 Worklist.push_back(IncValue);
3081 Objects.push_back(P);
3082 } while (!Worklist.empty());
3085 /// Return true if the only users of this pointer are lifetime markers.
3086 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
3087 for (const User *U : V->users()) {
3088 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3089 if (!II) return false;
3091 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3092 II->getIntrinsicID() != Intrinsic::lifetime_end)
3098 static bool isDereferenceableFromAttribute(const Value *BV, APInt Offset,
3099 Type *Ty, const DataLayout &DL,
3100 const Instruction *CtxI,
3101 const DominatorTree *DT,
3102 const TargetLibraryInfo *TLI) {
3103 assert(Offset.isNonNegative() && "offset can't be negative");
3104 assert(Ty->isSized() && "must be sized");
3106 APInt DerefBytes(Offset.getBitWidth(), 0);
3107 bool CheckForNonNull = false;
3108 if (const Argument *A = dyn_cast<Argument>(BV)) {
3109 DerefBytes = A->getDereferenceableBytes();
3110 if (!DerefBytes.getBoolValue()) {
3111 DerefBytes = A->getDereferenceableOrNullBytes();
3112 CheckForNonNull = true;
3114 } else if (auto CS = ImmutableCallSite(BV)) {
3115 DerefBytes = CS.getDereferenceableBytes(0);
3116 if (!DerefBytes.getBoolValue()) {
3117 DerefBytes = CS.getDereferenceableOrNullBytes(0);
3118 CheckForNonNull = true;
3120 } else if (const LoadInst *LI = dyn_cast<LoadInst>(BV)) {
3121 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
3122 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
3123 DerefBytes = CI->getLimitedValue();
3125 if (!DerefBytes.getBoolValue()) {
3127 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
3128 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
3129 DerefBytes = CI->getLimitedValue();
3131 CheckForNonNull = true;
3135 if (DerefBytes.getBoolValue())
3136 if (DerefBytes.uge(Offset + DL.getTypeStoreSize(Ty)))
3137 if (!CheckForNonNull || isKnownNonNullAt(BV, CtxI, DT, TLI))
3143 static bool isDereferenceableFromAttribute(const Value *V, const DataLayout &DL,
3144 const Instruction *CtxI,
3145 const DominatorTree *DT,
3146 const TargetLibraryInfo *TLI) {
3147 Type *VTy = V->getType();
3148 Type *Ty = VTy->getPointerElementType();
3152 APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
3153 return isDereferenceableFromAttribute(V, Offset, Ty, DL, CtxI, DT, TLI);
3156 static bool isAligned(const Value *Base, APInt Offset, unsigned Align,
3157 const DataLayout &DL) {
3158 APInt BaseAlign(Offset.getBitWidth(), getAlignment(Base, DL));
3161 Type *Ty = Base->getType()->getPointerElementType();
3162 BaseAlign = DL.getABITypeAlignment(Ty);
3165 APInt Alignment(Offset.getBitWidth(), Align);
3167 assert(Alignment.isPowerOf2() && "must be a power of 2!");
3168 return BaseAlign.uge(Alignment) && !(Offset & (Alignment-1));
3171 static bool isAligned(const Value *Base, unsigned Align, const DataLayout &DL) {
3172 APInt Offset(DL.getTypeStoreSizeInBits(Base->getType()), 0);
3173 return isAligned(Base, Offset, Align, DL);
3176 /// Test if V is always a pointer to allocated and suitably aligned memory for
3177 /// a simple load or store.
3178 static bool isDereferenceableAndAlignedPointer(
3179 const Value *V, unsigned Align, const DataLayout &DL,
3180 const Instruction *CtxI, const DominatorTree *DT,
3181 const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited) {
3182 // Note that it is not safe to speculate into a malloc'd region because
3183 // malloc may return null.
3185 // These are obviously ok if aligned.
3186 if (isa<AllocaInst>(V))
3187 return isAligned(V, Align, DL);
3189 // It's not always safe to follow a bitcast, for example:
3190 // bitcast i8* (alloca i8) to i32*
3191 // would result in a 4-byte load from a 1-byte alloca. However,
3192 // if we're casting from a pointer from a type of larger size
3193 // to a type of smaller size (or the same size), and the alignment
3194 // is at least as large as for the resulting pointer type, then
3195 // we can look through the bitcast.
3196 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
3197 Type *STy = BC->getSrcTy()->getPointerElementType(),
3198 *DTy = BC->getDestTy()->getPointerElementType();
3199 if (STy->isSized() && DTy->isSized() &&
3200 (DL.getTypeStoreSize(STy) >= DL.getTypeStoreSize(DTy)) &&
3201 (DL.getABITypeAlignment(STy) >= DL.getABITypeAlignment(DTy)))
3202 return isDereferenceableAndAlignedPointer(BC->getOperand(0), Align, DL,
3203 CtxI, DT, TLI, Visited);
3206 // Global variables which can't collapse to null are ok.
3207 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
3208 if (!GV->hasExternalWeakLinkage())
3209 return isAligned(V, Align, DL);
3211 // byval arguments are okay.
3212 if (const Argument *A = dyn_cast<Argument>(V))
3213 if (A->hasByValAttr())
3214 return isAligned(V, Align, DL);
3216 if (isDereferenceableFromAttribute(V, DL, CtxI, DT, TLI))
3217 return isAligned(V, Align, DL);
3219 // For GEPs, determine if the indexing lands within the allocated object.
3220 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3221 Type *VTy = GEP->getType();
3222 Type *Ty = VTy->getPointerElementType();
3223 const Value *Base = GEP->getPointerOperand();
3225 // Conservatively require that the base pointer be fully dereferenceable
3227 if (!Visited.insert(Base).second)
3229 if (!isDereferenceableAndAlignedPointer(Base, Align, DL, CtxI, DT, TLI,
3233 APInt Offset(DL.getPointerTypeSizeInBits(VTy), 0);
3234 if (!GEP->accumulateConstantOffset(DL, Offset))
3237 // Check if the load is within the bounds of the underlying object
3238 // and offset is aligned.
3239 uint64_t LoadSize = DL.getTypeStoreSize(Ty);
3240 Type *BaseType = Base->getType()->getPointerElementType();
3241 assert(isPowerOf2_32(Align) && "must be a power of 2!");
3242 return (Offset + LoadSize).ule(DL.getTypeAllocSize(BaseType)) &&
3243 !(Offset & APInt(Offset.getBitWidth(), Align-1));
3246 // For gc.relocate, look through relocations
3247 if (const IntrinsicInst *I = dyn_cast<IntrinsicInst>(V))
3248 if (I->getIntrinsicID() == Intrinsic::experimental_gc_relocate) {
3249 GCRelocateOperands RelocateInst(I);
3250 return isDereferenceableAndAlignedPointer(
3251 RelocateInst.getDerivedPtr(), Align, DL, CtxI, DT, TLI, Visited);
3254 if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
3255 return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Align, DL,
3256 CtxI, DT, TLI, Visited);
3258 // If we don't know, assume the worst.
3262 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
3263 const DataLayout &DL,
3264 const Instruction *CtxI,
3265 const DominatorTree *DT,
3266 const TargetLibraryInfo *TLI) {
3267 // When dereferenceability information is provided by a dereferenceable
3268 // attribute, we know exactly how many bytes are dereferenceable. If we can
3269 // determine the exact offset to the attributed variable, we can use that
3270 // information here.
3271 Type *VTy = V->getType();
3272 Type *Ty = VTy->getPointerElementType();
3274 // Require ABI alignment for loads without alignment specification
3276 Align = DL.getABITypeAlignment(Ty);
3278 if (Ty->isSized()) {
3279 APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
3280 const Value *BV = V->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
3282 if (Offset.isNonNegative())
3283 if (isDereferenceableFromAttribute(BV, Offset, Ty, DL, CtxI, DT, TLI) &&
3284 isAligned(BV, Offset, Align, DL))
3288 SmallPtrSet<const Value *, 32> Visited;
3289 return ::isDereferenceableAndAlignedPointer(V, Align, DL, CtxI, DT, TLI,
3293 bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL,
3294 const Instruction *CtxI,
3295 const DominatorTree *DT,
3296 const TargetLibraryInfo *TLI) {
3297 return isDereferenceableAndAlignedPointer(V, 1, DL, CtxI, DT, TLI);
3300 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3301 const Instruction *CtxI,
3302 const DominatorTree *DT,
3303 const TargetLibraryInfo *TLI) {
3304 const Operator *Inst = dyn_cast<Operator>(V);
3308 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3309 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3313 switch (Inst->getOpcode()) {
3316 case Instruction::UDiv:
3317 case Instruction::URem: {
3318 // x / y is undefined if y == 0.
3320 if (match(Inst->getOperand(1), m_APInt(V)))
3324 case Instruction::SDiv:
3325 case Instruction::SRem: {
3326 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
3327 const APInt *Numerator, *Denominator;
3328 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3330 // We cannot hoist this division if the denominator is 0.
3331 if (*Denominator == 0)
3333 // It's safe to hoist if the denominator is not 0 or -1.
3334 if (*Denominator != -1)
3336 // At this point we know that the denominator is -1. It is safe to hoist as
3337 // long we know that the numerator is not INT_MIN.
3338 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3339 return !Numerator->isMinSignedValue();
3340 // The numerator *might* be MinSignedValue.
3343 case Instruction::Load: {
3344 const LoadInst *LI = cast<LoadInst>(Inst);
3345 if (!LI->isUnordered() ||
3346 // Speculative load may create a race that did not exist in the source.
3347 LI->getParent()->getParent()->hasFnAttribute(
3348 Attribute::SanitizeThread) ||
3349 // Speculative load may load data from dirty regions.
3350 LI->getParent()->getParent()->hasFnAttribute(
3351 Attribute::SanitizeAddress))
3353 const DataLayout &DL = LI->getModule()->getDataLayout();
3354 return isDereferenceableAndAlignedPointer(
3355 LI->getPointerOperand(), LI->getAlignment(), DL, CtxI, DT, TLI);
3357 case Instruction::Call: {
3358 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3359 switch (II->getIntrinsicID()) {
3360 // These synthetic intrinsics have no side-effects and just mark
3361 // information about their operands.
3362 // FIXME: There are other no-op synthetic instructions that potentially
3363 // should be considered at least *safe* to speculate...
3364 case Intrinsic::dbg_declare:
3365 case Intrinsic::dbg_value:
3368 case Intrinsic::bswap:
3369 case Intrinsic::ctlz:
3370 case Intrinsic::ctpop:
3371 case Intrinsic::cttz:
3372 case Intrinsic::objectsize:
3373 case Intrinsic::sadd_with_overflow:
3374 case Intrinsic::smul_with_overflow:
3375 case Intrinsic::ssub_with_overflow:
3376 case Intrinsic::uadd_with_overflow:
3377 case Intrinsic::umul_with_overflow:
3378 case Intrinsic::usub_with_overflow:
3380 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
3381 // errno like libm sqrt would.
3382 case Intrinsic::sqrt:
3383 case Intrinsic::fma:
3384 case Intrinsic::fmuladd:
3385 case Intrinsic::fabs:
3386 case Intrinsic::minnum:
3387 case Intrinsic::maxnum:
3389 // TODO: some fp intrinsics are marked as having the same error handling
3390 // as libm. They're safe to speculate when they won't error.
3391 // TODO: are convert_{from,to}_fp16 safe?
3392 // TODO: can we list target-specific intrinsics here?
3396 return false; // The called function could have undefined behavior or
3397 // side-effects, even if marked readnone nounwind.
3399 case Instruction::VAArg:
3400 case Instruction::Alloca:
3401 case Instruction::Invoke:
3402 case Instruction::PHI:
3403 case Instruction::Store:
3404 case Instruction::Ret:
3405 case Instruction::Br:
3406 case Instruction::IndirectBr:
3407 case Instruction::Switch:
3408 case Instruction::Unreachable:
3409 case Instruction::Fence:
3410 case Instruction::AtomicRMW:
3411 case Instruction::AtomicCmpXchg:
3412 case Instruction::LandingPad:
3413 case Instruction::Resume:
3414 case Instruction::CatchPad:
3415 case Instruction::CatchEndPad:
3416 case Instruction::CatchRet:
3417 case Instruction::CleanupPad:
3418 case Instruction::CleanupEndPad:
3419 case Instruction::CleanupRet:
3420 case Instruction::TerminatePad:
3421 return false; // Misc instructions which have effects
3425 bool llvm::mayBeMemoryDependent(const Instruction &I) {
3426 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3429 /// Return true if we know that the specified value is never null.
3430 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
3431 assert(V->getType()->isPointerTy() && "V must be pointer type");
3433 // Alloca never returns null, malloc might.
3434 if (isa<AllocaInst>(V)) return true;
3436 // A byval, inalloca, or nonnull argument is never null.
3437 if (const Argument *A = dyn_cast<Argument>(V))
3438 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
3440 // A global variable in address space 0 is non null unless extern weak.
3441 // Other address spaces may have null as a valid address for a global,
3442 // so we can't assume anything.
3443 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
3444 return !GV->hasExternalWeakLinkage() &&
3445 GV->getType()->getAddressSpace() == 0;
3447 // A Load tagged w/nonnull metadata is never null.
3448 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
3449 return LI->getMetadata(LLVMContext::MD_nonnull);
3451 if (auto CS = ImmutableCallSite(V))
3452 if (CS.isReturnNonNull())
3455 // operator new never returns null.
3456 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
3462 static bool isKnownNonNullFromDominatingCondition(const Value *V,
3463 const Instruction *CtxI,
3464 const DominatorTree *DT) {
3465 assert(V->getType()->isPointerTy() && "V must be pointer type");
3467 unsigned NumUsesExplored = 0;
3468 for (auto U : V->users()) {
3469 // Avoid massive lists
3470 if (NumUsesExplored >= DomConditionsMaxUses)
3473 // Consider only compare instructions uniquely controlling a branch
3474 const ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
3478 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
3481 for (auto *CmpU : Cmp->users()) {
3482 const BranchInst *BI = dyn_cast<BranchInst>(CmpU);
3486 assert(BI->isConditional() && "uses a comparison!");
3488 BasicBlock *NonNullSuccessor = nullptr;
3489 CmpInst::Predicate Pred;
3491 if (match(const_cast<ICmpInst*>(Cmp),
3492 m_c_ICmp(Pred, m_Specific(V), m_Zero()))) {
3493 if (Pred == ICmpInst::ICMP_EQ)
3494 NonNullSuccessor = BI->getSuccessor(1);
3495 else if (Pred == ICmpInst::ICMP_NE)
3496 NonNullSuccessor = BI->getSuccessor(0);
3499 if (NonNullSuccessor) {
3500 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3501 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3510 bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
3511 const DominatorTree *DT, const TargetLibraryInfo *TLI) {
3512 if (isKnownNonNull(V, TLI))
3515 return CtxI ? ::isKnownNonNullFromDominatingCondition(V, CtxI, DT) : false;
3518 OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
3519 const DataLayout &DL,
3520 AssumptionCache *AC,
3521 const Instruction *CxtI,
3522 const DominatorTree *DT) {
3523 // Multiplying n * m significant bits yields a result of n + m significant
3524 // bits. If the total number of significant bits does not exceed the
3525 // result bit width (minus 1), there is no overflow.
3526 // This means if we have enough leading zero bits in the operands
3527 // we can guarantee that the result does not overflow.
3528 // Ref: "Hacker's Delight" by Henry Warren
3529 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3530 APInt LHSKnownZero(BitWidth, 0);
3531 APInt LHSKnownOne(BitWidth, 0);
3532 APInt RHSKnownZero(BitWidth, 0);
3533 APInt RHSKnownOne(BitWidth, 0);
3534 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3536 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3538 // Note that underestimating the number of zero bits gives a more
3539 // conservative answer.
3540 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
3541 RHSKnownZero.countLeadingOnes();
3542 // First handle the easy case: if we have enough zero bits there's
3543 // definitely no overflow.
3544 if (ZeroBits >= BitWidth)
3545 return OverflowResult::NeverOverflows;
3547 // Get the largest possible values for each operand.
3548 APInt LHSMax = ~LHSKnownZero;
3549 APInt RHSMax = ~RHSKnownZero;
3551 // We know the multiply operation doesn't overflow if the maximum values for
3552 // each operand will not overflow after we multiply them together.
3554 LHSMax.umul_ov(RHSMax, MaxOverflow);
3556 return OverflowResult::NeverOverflows;
3558 // We know it always overflows if multiplying the smallest possible values for
3559 // the operands also results in overflow.
3561 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
3563 return OverflowResult::AlwaysOverflows;
3565 return OverflowResult::MayOverflow;
3568 OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
3569 const DataLayout &DL,
3570 AssumptionCache *AC,
3571 const Instruction *CxtI,
3572 const DominatorTree *DT) {
3573 bool LHSKnownNonNegative, LHSKnownNegative;
3574 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3576 if (LHSKnownNonNegative || LHSKnownNegative) {
3577 bool RHSKnownNonNegative, RHSKnownNegative;
3578 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3581 if (LHSKnownNegative && RHSKnownNegative) {
3582 // The sign bit is set in both cases: this MUST overflow.
3583 // Create a simple add instruction, and insert it into the struct.
3584 return OverflowResult::AlwaysOverflows;
3587 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3588 // The sign bit is clear in both cases: this CANNOT overflow.
3589 // Create a simple add instruction, and insert it into the struct.
3590 return OverflowResult::NeverOverflows;
3594 return OverflowResult::MayOverflow;
3597 static OverflowResult computeOverflowForSignedAdd(
3598 Value *LHS, Value *RHS, AddOperator *Add, const DataLayout &DL,
3599 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) {
3600 if (Add && Add->hasNoSignedWrap()) {
3601 return OverflowResult::NeverOverflows;
3604 bool LHSKnownNonNegative, LHSKnownNegative;
3605 bool RHSKnownNonNegative, RHSKnownNegative;
3606 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3608 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3611 if ((LHSKnownNonNegative && RHSKnownNegative) ||
3612 (LHSKnownNegative && RHSKnownNonNegative)) {
3613 // The sign bits are opposite: this CANNOT overflow.
3614 return OverflowResult::NeverOverflows;
3617 // The remaining code needs Add to be available. Early returns if not so.
3619 return OverflowResult::MayOverflow;
3621 // If the sign of Add is the same as at least one of the operands, this add
3622 // CANNOT overflow. This is particularly useful when the sum is
3623 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3625 bool LHSOrRHSKnownNonNegative =
3626 (LHSKnownNonNegative || RHSKnownNonNegative);
3627 bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative);
3628 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
3629 bool AddKnownNonNegative, AddKnownNegative;
3630 ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL,
3631 /*Depth=*/0, AC, CxtI, DT);
3632 if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) ||
3633 (AddKnownNegative && LHSOrRHSKnownNegative)) {
3634 return OverflowResult::NeverOverflows;
3638 return OverflowResult::MayOverflow;
3641 OverflowResult llvm::computeOverflowForSignedAdd(AddOperator *Add,
3642 const DataLayout &DL,
3643 AssumptionCache *AC,
3644 const Instruction *CxtI,
3645 const DominatorTree *DT) {
3646 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
3647 Add, DL, AC, CxtI, DT);
3650 OverflowResult llvm::computeOverflowForSignedAdd(Value *LHS, Value *RHS,
3651 const DataLayout &DL,
3652 AssumptionCache *AC,
3653 const Instruction *CxtI,
3654 const DominatorTree *DT) {
3655 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
3658 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
3659 // FIXME: This conservative implementation can be relaxed. E.g. most
3660 // atomic operations are guaranteed to terminate on most platforms
3661 // and most functions terminate.
3663 return !I->isAtomic() && // atomics may never succeed on some platforms
3664 !isa<CallInst>(I) && // could throw and might not terminate
3665 !isa<InvokeInst>(I) && // might not terminate and could throw to
3666 // non-successor (see bug 24185 for details).
3667 !isa<ResumeInst>(I) && // has no successors
3668 !isa<ReturnInst>(I); // has no successors
3671 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3673 // The loop header is guaranteed to be executed for every iteration.
3675 // FIXME: Relax this constraint to cover all basic blocks that are
3676 // guaranteed to be executed at every iteration.
3677 if (I->getParent() != L->getHeader()) return false;
3679 for (const Instruction &LI : *L->getHeader()) {
3680 if (&LI == I) return true;
3681 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3683 llvm_unreachable("Instruction not contained in its own parent basic block.");
3686 bool llvm::propagatesFullPoison(const Instruction *I) {
3687 switch (I->getOpcode()) {
3688 case Instruction::Add:
3689 case Instruction::Sub:
3690 case Instruction::Xor:
3691 case Instruction::Trunc:
3692 case Instruction::BitCast:
3693 case Instruction::AddrSpaceCast:
3694 // These operations all propagate poison unconditionally. Note that poison
3695 // is not any particular value, so xor or subtraction of poison with
3696 // itself still yields poison, not zero.
3699 case Instruction::AShr:
3700 case Instruction::SExt:
3701 // For these operations, one bit of the input is replicated across
3702 // multiple output bits. A replicated poison bit is still poison.
3705 case Instruction::Shl: {
3706 // Left shift *by* a poison value is poison. The number of
3707 // positions to shift is unsigned, so no negative values are
3708 // possible there. Left shift by zero places preserves poison. So
3709 // it only remains to consider left shift of poison by a positive
3710 // number of places.
3712 // A left shift by a positive number of places leaves the lowest order bit
3713 // non-poisoned. However, if such a shift has a no-wrap flag, then we can
3714 // make the poison operand violate that flag, yielding a fresh full-poison
3716 auto *OBO = cast<OverflowingBinaryOperator>(I);
3717 return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
3720 case Instruction::Mul: {
3721 // A multiplication by zero yields a non-poison zero result, so we need to
3722 // rule out zero as an operand. Conservatively, multiplication by a
3723 // non-zero constant is not multiplication by zero.
3725 // Multiplication by a non-zero constant can leave some bits
3726 // non-poisoned. For example, a multiplication by 2 leaves the lowest
3727 // order bit unpoisoned. So we need to consider that.
3729 // Multiplication by 1 preserves poison. If the multiplication has a
3730 // no-wrap flag, then we can make the poison operand violate that flag
3731 // when multiplied by any integer other than 0 and 1.
3732 auto *OBO = cast<OverflowingBinaryOperator>(I);
3733 if (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) {
3734 for (Value *V : OBO->operands()) {
3735 if (auto *CI = dyn_cast<ConstantInt>(V)) {
3736 // A ConstantInt cannot yield poison, so we can assume that it is
3737 // the other operand that is poison.
3738 return !CI->isZero();
3745 case Instruction::GetElementPtr:
3746 // A GEP implicitly represents a sequence of additions, subtractions,
3747 // truncations, sign extensions and multiplications. The multiplications
3748 // are by the non-zero sizes of some set of types, so we do not have to be
3749 // concerned with multiplication by zero. If the GEP is in-bounds, then
3750 // these operations are implicitly no-signed-wrap so poison is propagated
3751 // by the arguments above for Add, Sub, Trunc, SExt and Mul.
3752 return cast<GEPOperator>(I)->isInBounds();
3759 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3760 switch (I->getOpcode()) {
3761 case Instruction::Store:
3762 return cast<StoreInst>(I)->getPointerOperand();
3764 case Instruction::Load:
3765 return cast<LoadInst>(I)->getPointerOperand();
3767 case Instruction::AtomicCmpXchg:
3768 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3770 case Instruction::AtomicRMW:
3771 return cast<AtomicRMWInst>(I)->getPointerOperand();
3773 case Instruction::UDiv:
3774 case Instruction::SDiv:
3775 case Instruction::URem:
3776 case Instruction::SRem:
3777 return I->getOperand(1);
3784 bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) {
3785 // We currently only look for uses of poison values within the same basic
3786 // block, as that makes it easier to guarantee that the uses will be
3787 // executed given that PoisonI is executed.
3789 // FIXME: Expand this to consider uses beyond the same basic block. To do
3790 // this, look out for the distinction between post-dominance and strong
3792 const BasicBlock *BB = PoisonI->getParent();
3794 // Set of instructions that we have proved will yield poison if PoisonI
3796 SmallSet<const Value *, 16> YieldsPoison;
3797 YieldsPoison.insert(PoisonI);
3799 for (BasicBlock::const_iterator I = PoisonI->getIterator(), E = BB->end();
3801 if (&*I != PoisonI) {
3802 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&*I);
3803 if (NotPoison != nullptr && YieldsPoison.count(NotPoison)) return true;
3804 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
3808 // Mark poison that propagates from I through uses of I.
3809 if (YieldsPoison.count(&*I)) {
3810 for (const User *User : I->users()) {
3811 const Instruction *UserI = cast<Instruction>(User);
3812 if (UserI->getParent() == BB && propagatesFullPoison(UserI))
3813 YieldsPoison.insert(User);
3820 static bool isKnownNonNaN(Value *V, FastMathFlags FMF) {
3824 if (auto *C = dyn_cast<ConstantFP>(V))
3829 static bool isKnownNonZero(Value *V) {
3830 if (auto *C = dyn_cast<ConstantFP>(V))
3831 return !C->isZero();
3835 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
3837 Value *CmpLHS, Value *CmpRHS,
3838 Value *TrueVal, Value *FalseVal,
3839 Value *&LHS, Value *&RHS) {
3843 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
3844 // return inconsistent results between implementations.
3845 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
3846 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
3847 // Therefore we behave conservatively and only proceed if at least one of the
3848 // operands is known to not be zero, or if we don't care about signed zeroes.
3851 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
3852 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
3853 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
3854 !isKnownNonZero(CmpRHS))
3855 return {SPF_UNKNOWN, SPNB_NA, false};
3858 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
3859 bool Ordered = false;
3861 // When given one NaN and one non-NaN input:
3862 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
3863 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
3864 // ordered comparison fails), which could be NaN or non-NaN.
3865 // so here we discover exactly what NaN behavior is required/accepted.
3866 if (CmpInst::isFPPredicate(Pred)) {
3867 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
3868 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
3870 if (LHSSafe && RHSSafe) {
3871 // Both operands are known non-NaN.
3872 NaNBehavior = SPNB_RETURNS_ANY;
3873 } else if (CmpInst::isOrdered(Pred)) {
3874 // An ordered comparison will return false when given a NaN, so it
3878 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
3879 NaNBehavior = SPNB_RETURNS_NAN;
3881 NaNBehavior = SPNB_RETURNS_OTHER;
3883 // Completely unsafe.
3884 return {SPF_UNKNOWN, SPNB_NA, false};
3887 // An unordered comparison will return true when given a NaN, so it
3890 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
3891 NaNBehavior = SPNB_RETURNS_OTHER;
3893 NaNBehavior = SPNB_RETURNS_NAN;
3895 // Completely unsafe.
3896 return {SPF_UNKNOWN, SPNB_NA, false};
3900 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
3901 std::swap(CmpLHS, CmpRHS);
3902 Pred = CmpInst::getSwappedPredicate(Pred);
3903 if (NaNBehavior == SPNB_RETURNS_NAN)
3904 NaNBehavior = SPNB_RETURNS_OTHER;
3905 else if (NaNBehavior == SPNB_RETURNS_OTHER)
3906 NaNBehavior = SPNB_RETURNS_NAN;
3910 // ([if]cmp X, Y) ? X : Y
3911 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
3913 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
3914 case ICmpInst::ICMP_UGT:
3915 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
3916 case ICmpInst::ICMP_SGT:
3917 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
3918 case ICmpInst::ICMP_ULT:
3919 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
3920 case ICmpInst::ICMP_SLT:
3921 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
3922 case FCmpInst::FCMP_UGT:
3923 case FCmpInst::FCMP_UGE:
3924 case FCmpInst::FCMP_OGT:
3925 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
3926 case FCmpInst::FCMP_ULT:
3927 case FCmpInst::FCMP_ULE:
3928 case FCmpInst::FCMP_OLT:
3929 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
3933 if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
3934 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
3935 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
3937 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
3938 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
3939 if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
3940 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
3943 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
3944 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
3945 if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
3946 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
3950 // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
3951 if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
3952 if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
3953 (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
3954 match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
3957 return {SPF_SMIN, SPNB_NA, false};
3962 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
3964 return {SPF_UNKNOWN, SPNB_NA, false};
3967 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
3968 Instruction::CastOps *CastOp) {
3969 CastInst *CI = dyn_cast<CastInst>(V1);
3970 Constant *C = dyn_cast<Constant>(V2);
3971 CastInst *CI2 = dyn_cast<CastInst>(V2);
3974 *CastOp = CI->getOpcode();
3977 // If V1 and V2 are both the same cast from the same type, we can look
3979 if (CI2->getOpcode() == CI->getOpcode() &&
3980 CI2->getSrcTy() == CI->getSrcTy())
3981 return CI2->getOperand(0);
3987 if (isa<SExtInst>(CI) && CmpI->isSigned()) {
3988 Constant *T = ConstantExpr::getTrunc(C, CI->getSrcTy());
3989 // This is only valid if the truncated value can be sign-extended
3990 // back to the original value.
3991 if (ConstantExpr::getSExt(T, C->getType()) == C)
3995 if (isa<ZExtInst>(CI) && CmpI->isUnsigned())
3996 return ConstantExpr::getTrunc(C, CI->getSrcTy());
3998 if (isa<TruncInst>(CI))
3999 return ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
4001 if (isa<FPToUIInst>(CI))
4002 return ConstantExpr::getUIToFP(C, CI->getSrcTy(), true);
4004 if (isa<FPToSIInst>(CI))
4005 return ConstantExpr::getSIToFP(C, CI->getSrcTy(), true);
4007 if (isa<UIToFPInst>(CI))
4008 return ConstantExpr::getFPToUI(C, CI->getSrcTy(), true);
4010 if (isa<SIToFPInst>(CI))
4011 return ConstantExpr::getFPToSI(C, CI->getSrcTy(), true);
4013 if (isa<FPTruncInst>(CI))
4014 return ConstantExpr::getFPExtend(C, CI->getSrcTy(), true);
4016 if (isa<FPExtInst>(CI))
4017 return ConstantExpr::getFPTrunc(C, CI->getSrcTy(), true);
4022 SelectPatternResult llvm::matchSelectPattern(Value *V,
4023 Value *&LHS, Value *&RHS,
4024 Instruction::CastOps *CastOp) {
4025 SelectInst *SI = dyn_cast<SelectInst>(V);
4026 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
4028 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4029 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
4031 CmpInst::Predicate Pred = CmpI->getPredicate();
4032 Value *CmpLHS = CmpI->getOperand(0);
4033 Value *CmpRHS = CmpI->getOperand(1);
4034 Value *TrueVal = SI->getTrueValue();
4035 Value *FalseVal = SI->getFalseValue();
4037 if (isa<FPMathOperator>(CmpI))
4038 FMF = CmpI->getFastMathFlags();
4041 if (CmpI->isEquality())
4042 return {SPF_UNKNOWN, SPNB_NA, false};
4044 // Deal with type mismatches.
4045 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
4046 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
4047 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
4048 cast<CastInst>(TrueVal)->getOperand(0), C,
4050 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
4051 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
4052 C, cast<CastInst>(FalseVal)->getOperand(0),
4055 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
4059 ConstantRange llvm::getConstantRangeFromMetadata(MDNode &Ranges) {
4060 const unsigned NumRanges = Ranges.getNumOperands() / 2;
4061 assert(NumRanges >= 1 && "Must have at least one range!");
4062 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
4064 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
4065 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
4067 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
4069 for (unsigned i = 1; i < NumRanges; ++i) {
4070 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
4071 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
4073 // Note: unionWith will potentially create a range that contains values not
4074 // contained in any of the original N ranges.
4075 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));