74c862a88dd69f81c9df7d6c0f6b27abf7184e99
[oota-llvm.git] / lib / Analysis / ValueTracking.cpp
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Analysis/AssumptionTracker.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/MemoryBuiltins.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/MathExtras.h"
36 #include <cstring>
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39
40 const unsigned MaxDepth = 6;
41
42 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
43 /// unknown returns 0).  For vector types, returns the element type's bitwidth.
44 static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
45   if (unsigned BitWidth = Ty->getScalarSizeInBits())
46     return BitWidth;
47
48   return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
49 }
50
51 // Many of these functions have internal versions that take an assumption
52 // exclusion set. This is because of the potential for mutual recursion to
53 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
54 // classic case of this is assume(x = y), which will attempt to determine
55 // bits in x from bits in y, which will attempt to determine bits in y from
56 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
57 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
58 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
59 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
60
61 // Simplifying using an assume can only be done in a particular control-flow
62 // context (the context instruction provides that context). If an assume and
63 // the context instruction are not in the same block then the DT helps in
64 // figuring out if we can use it.
65 struct Query {
66   ExclInvsSet ExclInvs;
67   AssumptionTracker *AT;
68   const Instruction *CxtI;
69   const DominatorTree *DT;
70
71   Query(AssumptionTracker *AT = nullptr, const Instruction *CxtI = nullptr,
72         const DominatorTree *DT = nullptr)
73     : AT(AT), CxtI(CxtI), DT(DT) {}
74
75   Query(const Query &Q, const Value *NewExcl)
76     : ExclInvs(Q.ExclInvs), AT(Q.AT), CxtI(Q.CxtI), DT(Q.DT) {
77     ExclInvs.insert(NewExcl);
78   }
79 };
80
81 // Given the provided Value and, potentially, a context instruction, returned
82 // the preferred context instruction (if any).
83 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
84   // If we've been provided with a context instruction, then use that (provided
85   // it has been inserted).
86   if (CxtI && CxtI->getParent())
87     return CxtI;
88
89   // If the value is really an already-inserted instruction, then use that.
90   CxtI = dyn_cast<Instruction>(V);
91   if (CxtI && CxtI->getParent())
92     return CxtI;
93
94   return nullptr;
95 }
96
97 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
98                             const DataLayout *TD, unsigned Depth,
99                             const Query &Q);
100
101 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
102                             const DataLayout *TD, unsigned Depth,
103                             AssumptionTracker *AT, const Instruction *CxtI,
104                             const DominatorTree *DT) {
105   ::computeKnownBits(V, KnownZero, KnownOne, TD, Depth,
106                      Query(AT, safeCxtI(V, CxtI), DT));
107 }
108
109 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
110                           const DataLayout *TD, unsigned Depth,
111                           const Query &Q);
112
113 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
114                           const DataLayout *TD, unsigned Depth,
115                           AssumptionTracker *AT, const Instruction *CxtI,
116                           const DominatorTree *DT) {
117   ::ComputeSignBit(V, KnownZero, KnownOne, TD, Depth,
118                    Query(AT, safeCxtI(V, CxtI), DT));
119 }
120
121 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
122                                    const Query &Q);
123
124 bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
125                                   AssumptionTracker *AT,
126                                   const Instruction *CxtI,
127                                   const DominatorTree *DT) {
128   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
129                                   Query(AT, safeCxtI(V, CxtI), DT));
130 }
131
132 static bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
133                            const Query &Q);
134
135 bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
136                           AssumptionTracker *AT, const Instruction *CxtI,
137                           const DominatorTree *DT) {
138   return ::isKnownNonZero(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
139 }
140
141 static bool MaskedValueIsZero(Value *V, const APInt &Mask,
142                               const DataLayout *TD, unsigned Depth,
143                               const Query &Q);
144
145 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
146                              const DataLayout *TD, unsigned Depth,
147                              AssumptionTracker *AT, const Instruction *CxtI,
148                              const DominatorTree *DT) {
149   return ::MaskedValueIsZero(V, Mask, TD, Depth,
150                              Query(AT, safeCxtI(V, CxtI), DT));
151 }
152
153 static unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
154                                    unsigned Depth, const Query &Q);
155
156 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
157                                   unsigned Depth, AssumptionTracker *AT,
158                                   const Instruction *CxtI,
159                                   const DominatorTree *DT) {
160   return ::ComputeNumSignBits(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
161 }
162
163 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
164                                    APInt &KnownZero, APInt &KnownOne,
165                                    APInt &KnownZero2, APInt &KnownOne2,
166                                    const DataLayout *TD, unsigned Depth,
167                                    const Query &Q) {
168   if (!Add) {
169     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
170       // We know that the top bits of C-X are clear if X contains less bits
171       // than C (i.e. no wrap-around can happen).  For example, 20-X is
172       // positive if we can prove that X is >= 0 and < 16.
173       if (!CLHS->getValue().isNegative()) {
174         unsigned BitWidth = KnownZero.getBitWidth();
175         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
176         // NLZ can't be BitWidth with no sign bit
177         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
178         computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
179
180         // If all of the MaskV bits are known to be zero, then we know the
181         // output top bits are zero, because we now know that the output is
182         // from [0-C].
183         if ((KnownZero2 & MaskV) == MaskV) {
184           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
185           // Top bits known zero.
186           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
187         }
188       }
189     }
190   }
191
192   unsigned BitWidth = KnownZero.getBitWidth();
193
194   // If an initial sequence of bits in the result is not needed, the
195   // corresponding bits in the operands are not needed.
196   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
197   computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1, Q);
198   computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
199
200   // Carry in a 1 for a subtract, rather than a 0.
201   APInt CarryIn(BitWidth, 0);
202   if (!Add) {
203     // Sum = LHS + ~RHS + 1
204     std::swap(KnownZero2, KnownOne2);
205     CarryIn.setBit(0);
206   }
207
208   APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
209   APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
210
211   // Compute known bits of the carry.
212   APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
213   APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
214
215   // Compute set of known bits (where all three relevant bits are known).
216   APInt LHSKnown = LHSKnownZero | LHSKnownOne;
217   APInt RHSKnown = KnownZero2 | KnownOne2;
218   APInt CarryKnown = CarryKnownZero | CarryKnownOne;
219   APInt Known = LHSKnown & RHSKnown & CarryKnown;
220
221   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
222          "known bits of sum differ");
223
224   // Compute known bits of the result.
225   KnownZero = ~PossibleSumOne & Known;
226   KnownOne = PossibleSumOne & Known;
227
228   // Are we still trying to solve for the sign bit?
229   if (!Known.isNegative()) {
230     if (NSW) {
231       // Adding two non-negative numbers, or subtracting a negative number from
232       // a non-negative one, can't wrap into negative.
233       if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
234         KnownZero |= APInt::getSignBit(BitWidth);
235       // Adding two negative numbers, or subtracting a non-negative number from
236       // a negative one, can't wrap into non-negative.
237       else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
238         KnownOne |= APInt::getSignBit(BitWidth);
239     }
240   }
241 }
242
243 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
244                                 APInt &KnownZero, APInt &KnownOne,
245                                 APInt &KnownZero2, APInt &KnownOne2,
246                                 const DataLayout *TD, unsigned Depth,
247                                 const Query &Q) {
248   unsigned BitWidth = KnownZero.getBitWidth();
249   computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1, Q);
250   computeKnownBits(Op0, KnownZero2, KnownOne2, TD, Depth+1, Q);
251
252   bool isKnownNegative = false;
253   bool isKnownNonNegative = false;
254   // If the multiplication is known not to overflow, compute the sign bit.
255   if (NSW) {
256     if (Op0 == Op1) {
257       // The product of a number with itself is non-negative.
258       isKnownNonNegative = true;
259     } else {
260       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
261       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
262       bool isKnownNegativeOp1 = KnownOne.isNegative();
263       bool isKnownNegativeOp0 = KnownOne2.isNegative();
264       // The product of two numbers with the same sign is non-negative.
265       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
266         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
267       // The product of a negative number and a non-negative number is either
268       // negative or zero.
269       if (!isKnownNonNegative)
270         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
271                            isKnownNonZero(Op0, TD, Depth, Q)) ||
272                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
273                            isKnownNonZero(Op1, TD, Depth, Q));
274     }
275   }
276
277   // If low bits are zero in either operand, output low known-0 bits.
278   // Also compute a conserative estimate for high known-0 bits.
279   // More trickiness is possible, but this is sufficient for the
280   // interesting case of alignment computation.
281   KnownOne.clearAllBits();
282   unsigned TrailZ = KnownZero.countTrailingOnes() +
283                     KnownZero2.countTrailingOnes();
284   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
285                              KnownZero2.countLeadingOnes(),
286                              BitWidth) - BitWidth;
287
288   TrailZ = std::min(TrailZ, BitWidth);
289   LeadZ = std::min(LeadZ, BitWidth);
290   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
291               APInt::getHighBitsSet(BitWidth, LeadZ);
292
293   // Only make use of no-wrap flags if we failed to compute the sign bit
294   // directly.  This matters if the multiplication always overflows, in
295   // which case we prefer to follow the result of the direct computation,
296   // though as the program is invoking undefined behaviour we can choose
297   // whatever we like here.
298   if (isKnownNonNegative && !KnownOne.isNegative())
299     KnownZero.setBit(BitWidth - 1);
300   else if (isKnownNegative && !KnownZero.isNegative())
301     KnownOne.setBit(BitWidth - 1);
302 }
303
304 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
305                                              APInt &KnownZero) {
306   unsigned BitWidth = KnownZero.getBitWidth();
307   unsigned NumRanges = Ranges.getNumOperands() / 2;
308   assert(NumRanges >= 1);
309
310   // Use the high end of the ranges to find leading zeros.
311   unsigned MinLeadingZeros = BitWidth;
312   for (unsigned i = 0; i < NumRanges; ++i) {
313     ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
314     ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
315     ConstantRange Range(Lower->getValue(), Upper->getValue());
316     if (Range.isWrappedSet())
317       MinLeadingZeros = 0; // -1 has no zeros
318     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
319     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
320   }
321
322   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
323 }
324
325 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
326   SmallVector<const Value *, 16> WorkSet(1, I);
327   SmallPtrSet<const Value *, 32> Visited;
328   SmallPtrSet<const Value *, 16> EphValues;
329
330   while (!WorkSet.empty()) {
331     const Value *V = WorkSet.pop_back_val();
332     if (!Visited.insert(V))
333       continue;
334
335     // If all uses of this value are ephemeral, then so is this value.
336     bool FoundNEUse = false;
337     for (const User *I : V->users())
338       if (!EphValues.count(I)) {
339         FoundNEUse = true;
340         break;
341       }
342
343     if (!FoundNEUse) {
344       if (V == E)
345         return true;
346
347       EphValues.insert(V);
348       if (const User *U = dyn_cast<User>(V))
349         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
350              J != JE; ++J) {
351           if (isSafeToSpeculativelyExecute(*J))
352             WorkSet.push_back(*J);
353         }
354     }
355   }
356
357   return false;
358 }
359
360 // Is this an intrinsic that cannot be speculated but also cannot trap?
361 static bool isAssumeLikeIntrinsic(const Instruction *I) {
362   if (const CallInst *CI = dyn_cast<CallInst>(I))
363     if (Function *F = CI->getCalledFunction())
364       switch (F->getIntrinsicID()) {
365       default: break;
366       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
367       case Intrinsic::assume:
368       case Intrinsic::dbg_declare:
369       case Intrinsic::dbg_value:
370       case Intrinsic::invariant_start:
371       case Intrinsic::invariant_end:
372       case Intrinsic::lifetime_start:
373       case Intrinsic::lifetime_end:
374       case Intrinsic::objectsize:
375       case Intrinsic::ptr_annotation:
376       case Intrinsic::var_annotation:
377         return true;
378       }
379
380   return false;
381 }
382
383 static bool isValidAssumeForContext(Value *V, const Query &Q,
384                                     const DataLayout *DL) {
385   Instruction *Inv = cast<Instruction>(V);
386
387   // There are two restrictions on the use of an assume:
388   //  1. The assume must dominate the context (or the control flow must
389   //     reach the assume whenever it reaches the context).
390   //  2. The context must not be in the assume's set of ephemeral values
391   //     (otherwise we will use the assume to prove that the condition
392   //     feeding the assume is trivially true, thus causing the removal of
393   //     the assume).
394
395   if (Q.DT) {
396     if (Q.DT->dominates(Inv, Q.CxtI)) {
397       return true;
398     } else if (Inv->getParent() == Q.CxtI->getParent()) {
399       // The context comes first, but they're both in the same block. Make sure
400       // there is nothing in between that might interrupt the control flow.
401       for (BasicBlock::const_iterator I =
402              std::next(BasicBlock::const_iterator(Q.CxtI)),
403                                       IE(Inv); I != IE; ++I)
404         if (!isSafeToSpeculativelyExecute(I, DL) &&
405             !isAssumeLikeIntrinsic(I))
406           return false;
407
408       return !isEphemeralValueOf(Inv, Q.CxtI);
409     }
410
411     return false;
412   }
413
414   // When we don't have a DT, we do a limited search...
415   if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
416     return true;
417   } else if (Inv->getParent() == Q.CxtI->getParent()) {
418     // Search forward from the assume until we reach the context (or the end
419     // of the block); the common case is that the assume will come first.
420     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
421          IE = Inv->getParent()->end(); I != IE; ++I)
422       if (I == Q.CxtI)
423         return true;
424
425     // The context must come first...
426     for (BasicBlock::const_iterator I =
427            std::next(BasicBlock::const_iterator(Q.CxtI)),
428                                     IE(Inv); I != IE; ++I)
429       if (!isSafeToSpeculativelyExecute(I, DL) &&
430           !isAssumeLikeIntrinsic(I))
431         return false;
432
433     return !isEphemeralValueOf(Inv, Q.CxtI);
434   }
435
436   return false;
437 }
438
439 bool llvm::isValidAssumeForContext(const Instruction *I,
440                                    const Instruction *CxtI,
441                                    const DataLayout *DL,
442                                    const DominatorTree *DT) {
443   return ::isValidAssumeForContext(const_cast<Instruction*>(I),
444                                    Query(nullptr, CxtI, DT), DL);
445 }
446
447 template<typename LHS, typename RHS>
448 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
449                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
450 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
451   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
452 }
453
454 template<typename LHS, typename RHS>
455 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
456                         BinaryOp_match<RHS, LHS, Instruction::And>>
457 m_c_And(const LHS &L, const RHS &R) {
458   return m_CombineOr(m_And(L, R), m_And(R, L));
459 }
460
461 template<typename LHS, typename RHS>
462 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
463                         BinaryOp_match<RHS, LHS, Instruction::Or>>
464 m_c_Or(const LHS &L, const RHS &R) {
465   return m_CombineOr(m_Or(L, R), m_Or(R, L));
466 }
467
468 template<typename LHS, typename RHS>
469 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
470                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
471 m_c_Xor(const LHS &L, const RHS &R) {
472   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
473 }
474
475 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
476                                        APInt &KnownOne,
477                                        const DataLayout *DL,
478                                        unsigned Depth, const Query &Q) {
479   // Use of assumptions is context-sensitive. If we don't have a context, we
480   // cannot use them!
481   if (!Q.AT || !Q.CxtI)
482     return;
483
484   unsigned BitWidth = KnownZero.getBitWidth();
485
486   Function *F = const_cast<Function*>(Q.CxtI->getParent()->getParent());
487   for (auto &CI : Q.AT->assumptions(F)) {
488     CallInst *I = CI;
489     if (Q.ExclInvs.count(I))
490       continue;
491
492     if (match(I, m_Intrinsic<Intrinsic::assume>(m_Specific(V))) &&
493         isValidAssumeForContext(I, Q, DL)) {
494       assert(BitWidth == 1 && "assume operand is not i1?");
495       KnownZero.clearAllBits();
496       KnownOne.setAllBits();
497       return;
498     }
499
500     Value *A, *B;
501     auto m_V = m_CombineOr(m_Specific(V),
502                            m_CombineOr(m_PtrToInt(m_Specific(V)),
503                            m_BitCast(m_Specific(V))));
504
505     CmpInst::Predicate Pred;
506     ConstantInt *C;
507     // assume(v = a)
508     if (match(I, m_Intrinsic<Intrinsic::assume>(
509                    m_c_ICmp(Pred, m_V, m_Value(A)))) &&
510         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
511       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
512       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
513       KnownZero |= RHSKnownZero;
514       KnownOne  |= RHSKnownOne;
515     // assume(v & b = a)
516     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
517                        m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A)))) &&
518                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
519       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
520       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
521       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
522       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
523
524       // For those bits in the mask that are known to be one, we can propagate
525       // known bits from the RHS to V.
526       KnownZero |= RHSKnownZero & MaskKnownOne;
527       KnownOne  |= RHSKnownOne  & MaskKnownOne;
528     // assume(~(v & b) = a)
529     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
530                        m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
531                                 m_Value(A)))) &&
532                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
533       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
534       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
535       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
536       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
537
538       // For those bits in the mask that are known to be one, we can propagate
539       // inverted known bits from the RHS to V.
540       KnownZero |= RHSKnownOne  & MaskKnownOne;
541       KnownOne  |= RHSKnownZero & MaskKnownOne;
542     // assume(v | b = a)
543     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
544                        m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A)))) &&
545                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
546       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
547       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
548       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
549       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
550
551       // For those bits in B that are known to be zero, we can propagate known
552       // bits from the RHS to V.
553       KnownZero |= RHSKnownZero & BKnownZero;
554       KnownOne  |= RHSKnownOne  & BKnownZero;
555     // assume(~(v | b) = a)
556     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
557                        m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
558                                 m_Value(A)))) &&
559                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
560       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
561       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
562       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
563       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
564
565       // For those bits in B that are known to be zero, we can propagate
566       // inverted known bits from the RHS to V.
567       KnownZero |= RHSKnownOne  & BKnownZero;
568       KnownOne  |= RHSKnownZero & BKnownZero;
569     // assume(v ^ b = a)
570     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
571                        m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A)))) &&
572                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
573       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
574       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
575       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
576       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
577
578       // For those bits in B that are known to be zero, we can propagate known
579       // bits from the RHS to V. For those bits in B that are known to be one,
580       // we can propagate inverted known bits from the RHS to V.
581       KnownZero |= RHSKnownZero & BKnownZero;
582       KnownOne  |= RHSKnownOne  & BKnownZero;
583       KnownZero |= RHSKnownOne  & BKnownOne;
584       KnownOne  |= RHSKnownZero & BKnownOne;
585     // assume(~(v ^ b) = a)
586     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
587                        m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
588                                 m_Value(A)))) &&
589                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
590       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
591       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
592       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
593       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
594
595       // For those bits in B that are known to be zero, we can propagate
596       // inverted known bits from the RHS to V. For those bits in B that are
597       // known to be one, we can propagate known bits from the RHS to V.
598       KnownZero |= RHSKnownOne  & BKnownZero;
599       KnownOne  |= RHSKnownZero & BKnownZero;
600       KnownZero |= RHSKnownZero & BKnownOne;
601       KnownOne  |= RHSKnownOne  & BKnownOne;
602     // assume(v << c = a)
603     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
604                        m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
605                                       m_Value(A)))) &&
606                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
607       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
608       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
609       // For those bits in RHS that are known, we can propagate them to known
610       // bits in V shifted to the right by C.
611       KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
612       KnownOne  |= RHSKnownOne.lshr(C->getZExtValue());
613     // assume(~(v << c) = a)
614     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
615                        m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
616                                       m_Value(A)))) &&
617                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
618       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
619       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
620       // For those bits in RHS that are known, we can propagate them inverted
621       // to known bits in V shifted to the right by C.
622       KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
623       KnownOne  |= RHSKnownZero.lshr(C->getZExtValue());
624     // assume(v >> c = a)
625     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
626                        m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
627                                                   m_AShr(m_V,
628                                                          m_ConstantInt(C))),
629                                      m_Value(A)))) &&
630                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
631       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
632       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
633       // For those bits in RHS that are known, we can propagate them to known
634       // bits in V shifted to the right by C.
635       KnownZero |= RHSKnownZero << C->getZExtValue();
636       KnownOne  |= RHSKnownOne  << C->getZExtValue();
637     // assume(~(v >> c) = a)
638     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
639                        m_c_ICmp(Pred, m_Not(m_CombineOr(
640                                               m_LShr(m_V, m_ConstantInt(C)),
641                                               m_AShr(m_V, m_ConstantInt(C)))),
642                                      m_Value(A)))) &&
643                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
644       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
645       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
646       // For those bits in RHS that are known, we can propagate them inverted
647       // to known bits in V shifted to the right by C.
648       KnownZero |= RHSKnownOne  << C->getZExtValue();
649       KnownOne  |= RHSKnownZero << C->getZExtValue();
650     // assume(v >=_s c) where c is non-negative
651     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
652                        m_ICmp(Pred, m_V, m_Value(A)))) &&
653                Pred == ICmpInst::ICMP_SGE &&
654                isValidAssumeForContext(I, Q, DL)) {
655       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
656       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
657
658       if (RHSKnownZero.isNegative()) {
659         // We know that the sign bit is zero.
660         KnownZero |= APInt::getSignBit(BitWidth);
661       }
662     // assume(v >_s c) where c is at least -1.
663     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
664                        m_ICmp(Pred, m_V, m_Value(A)))) &&
665                Pred == ICmpInst::ICMP_SGT &&
666                isValidAssumeForContext(I, Q, DL)) {
667       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
668       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
669
670       if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
671         // We know that the sign bit is zero.
672         KnownZero |= APInt::getSignBit(BitWidth);
673       }
674     // assume(v <=_s c) where c is negative
675     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
676                        m_ICmp(Pred, m_V, m_Value(A)))) &&
677                Pred == ICmpInst::ICMP_SLE &&
678                isValidAssumeForContext(I, Q, DL)) {
679       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
680       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
681
682       if (RHSKnownOne.isNegative()) {
683         // We know that the sign bit is one.
684         KnownOne |= APInt::getSignBit(BitWidth);
685       }
686     // assume(v <_s c) where c is non-positive
687     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
688                        m_ICmp(Pred, m_V, m_Value(A)))) &&
689                Pred == ICmpInst::ICMP_SLT &&
690                isValidAssumeForContext(I, Q, DL)) {
691       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
692       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
693
694       if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
695         // We know that the sign bit is one.
696         KnownOne |= APInt::getSignBit(BitWidth);
697       }
698     // assume(v <=_u c)
699     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
700                        m_ICmp(Pred, m_V, m_Value(A)))) &&
701                Pred == ICmpInst::ICMP_ULE &&
702                isValidAssumeForContext(I, Q, DL)) {
703       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
704       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
705
706       // Whatever high bits in c are zero are known to be zero.
707       KnownZero |=
708         APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
709     // assume(v <_u c)
710     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
711                        m_ICmp(Pred, m_V, m_Value(A)))) &&
712                Pred == ICmpInst::ICMP_ULT &&
713                isValidAssumeForContext(I, Q, DL)) {
714       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
715       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
716
717       // Whatever high bits in c are zero are known to be zero (if c is a power
718       // of 2, then one more).
719       if (isKnownToBeAPowerOfTwo(A, false, Depth+1, Query(Q, I)))
720         KnownZero |=
721           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
722       else
723         KnownZero |=
724           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
725     }
726   }
727 }
728
729 /// Determine which bits of V are known to be either zero or one and return
730 /// them in the KnownZero/KnownOne bit sets.
731 ///
732 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
733 /// we cannot optimize based on the assumption that it is zero without changing
734 /// it to be an explicit zero.  If we don't change it to zero, other code could
735 /// optimized based on the contradictory assumption that it is non-zero.
736 /// Because instcombine aggressively folds operations with undef args anyway,
737 /// this won't lose us code quality.
738 ///
739 /// This function is defined on values with integer type, values with pointer
740 /// type (but only if TD is non-null), and vectors of integers.  In the case
741 /// where V is a vector, known zero, and known one values are the
742 /// same width as the vector element, and the bit is set only if it is true
743 /// for all of the elements in the vector.
744 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
745                       const DataLayout *TD, unsigned Depth,
746                       const Query &Q) {
747   assert(V && "No Value?");
748   assert(Depth <= MaxDepth && "Limit Search Depth");
749   unsigned BitWidth = KnownZero.getBitWidth();
750
751   assert((V->getType()->isIntOrIntVectorTy() ||
752           V->getType()->getScalarType()->isPointerTy()) &&
753          "Not integer or pointer type!");
754   assert((!TD ||
755           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
756          (!V->getType()->isIntOrIntVectorTy() ||
757           V->getType()->getScalarSizeInBits() == BitWidth) &&
758          KnownZero.getBitWidth() == BitWidth &&
759          KnownOne.getBitWidth() == BitWidth &&
760          "V, KnownOne and KnownZero should have same BitWidth");
761
762   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
763     // We know all of the bits for a constant!
764     KnownOne = CI->getValue();
765     KnownZero = ~KnownOne;
766     return;
767   }
768   // Null and aggregate-zero are all-zeros.
769   if (isa<ConstantPointerNull>(V) ||
770       isa<ConstantAggregateZero>(V)) {
771     KnownOne.clearAllBits();
772     KnownZero = APInt::getAllOnesValue(BitWidth);
773     return;
774   }
775   // Handle a constant vector by taking the intersection of the known bits of
776   // each element.  There is no real need to handle ConstantVector here, because
777   // we don't handle undef in any particularly useful way.
778   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
779     // We know that CDS must be a vector of integers. Take the intersection of
780     // each element.
781     KnownZero.setAllBits(); KnownOne.setAllBits();
782     APInt Elt(KnownZero.getBitWidth(), 0);
783     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
784       Elt = CDS->getElementAsInteger(i);
785       KnownZero &= ~Elt;
786       KnownOne &= Elt;
787     }
788     return;
789   }
790
791   // The address of an aligned GlobalValue has trailing zeros.
792   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
793     unsigned Align = GV->getAlignment();
794     if (Align == 0 && TD) {
795       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
796         Type *ObjectType = GVar->getType()->getElementType();
797         if (ObjectType->isSized()) {
798           // If the object is defined in the current Module, we'll be giving
799           // it the preferred alignment. Otherwise, we have to assume that it
800           // may only have the minimum ABI alignment.
801           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
802             Align = TD->getPreferredAlignment(GVar);
803           else
804             Align = TD->getABITypeAlignment(ObjectType);
805         }
806       }
807     }
808     if (Align > 0)
809       KnownZero = APInt::getLowBitsSet(BitWidth,
810                                        countTrailingZeros(Align));
811     else
812       KnownZero.clearAllBits();
813     KnownOne.clearAllBits();
814     return;
815   }
816   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
817   // the bits of its aliasee.
818   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
819     if (GA->mayBeOverridden()) {
820       KnownZero.clearAllBits(); KnownOne.clearAllBits();
821     } else {
822       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1, Q);
823     }
824     return;
825   }
826
827   if (Argument *A = dyn_cast<Argument>(V)) {
828     unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
829
830     if (!Align && TD && A->hasStructRetAttr()) {
831       // An sret parameter has at least the ABI alignment of the return type.
832       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
833       if (EltTy->isSized())
834         Align = TD->getABITypeAlignment(EltTy);
835     }
836
837     if (Align)
838       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
839
840     // Don't give up yet... there might be an assumption that provides more
841     // information...
842     computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
843     return;
844   }
845
846   // Start out not knowing anything.
847   KnownZero.clearAllBits(); KnownOne.clearAllBits();
848
849   if (Depth == MaxDepth)
850     return;  // Limit search depth.
851
852   // Check whether a nearby assume intrinsic can determine some known bits.
853   computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
854
855   Operator *I = dyn_cast<Operator>(V);
856   if (!I) return;
857
858   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
859   switch (I->getOpcode()) {
860   default: break;
861   case Instruction::Load:
862     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
863       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
864     break;
865   case Instruction::And: {
866     // If either the LHS or the RHS are Zero, the result is zero.
867     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
868     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
869
870     // Output known-1 bits are only known if set in both the LHS & RHS.
871     KnownOne &= KnownOne2;
872     // Output known-0 are known to be clear if zero in either the LHS | RHS.
873     KnownZero |= KnownZero2;
874     break;
875   }
876   case Instruction::Or: {
877     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
878     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
879
880     // Output known-0 bits are only known if clear in both the LHS & RHS.
881     KnownZero &= KnownZero2;
882     // Output known-1 are known to be set if set in either the LHS | RHS.
883     KnownOne |= KnownOne2;
884     break;
885   }
886   case Instruction::Xor: {
887     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
888     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
889
890     // Output known-0 bits are known if clear or set in both the LHS & RHS.
891     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
892     // Output known-1 are known to be set if set in only one of the LHS, RHS.
893     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
894     KnownZero = KnownZeroOut;
895     break;
896   }
897   case Instruction::Mul: {
898     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
899     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
900                          KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
901                          Depth, Q);
902     break;
903   }
904   case Instruction::UDiv: {
905     // For the purposes of computing leading zeros we can conservatively
906     // treat a udiv as a logical right shift by the power of 2 known to
907     // be less than the denominator.
908     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
909     unsigned LeadZ = KnownZero2.countLeadingOnes();
910
911     KnownOne2.clearAllBits();
912     KnownZero2.clearAllBits();
913     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
914     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
915     if (RHSUnknownLeadingOnes != BitWidth)
916       LeadZ = std::min(BitWidth,
917                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
918
919     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
920     break;
921   }
922   case Instruction::Select:
923     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
924     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
925
926     // Only known if known in both the LHS and RHS.
927     KnownOne &= KnownOne2;
928     KnownZero &= KnownZero2;
929     break;
930   case Instruction::FPTrunc:
931   case Instruction::FPExt:
932   case Instruction::FPToUI:
933   case Instruction::FPToSI:
934   case Instruction::SIToFP:
935   case Instruction::UIToFP:
936     break; // Can't work with floating point.
937   case Instruction::PtrToInt:
938   case Instruction::IntToPtr:
939   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
940     // We can't handle these if we don't know the pointer size.
941     if (!TD) break;
942     // FALL THROUGH and handle them the same as zext/trunc.
943   case Instruction::ZExt:
944   case Instruction::Trunc: {
945     Type *SrcTy = I->getOperand(0)->getType();
946
947     unsigned SrcBitWidth;
948     // Note that we handle pointer operands here because of inttoptr/ptrtoint
949     // which fall through here.
950     if(TD) {
951       SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
952     } else {
953       SrcBitWidth = SrcTy->getScalarSizeInBits();
954       if (!SrcBitWidth) break;
955     }
956
957     assert(SrcBitWidth && "SrcBitWidth can't be zero");
958     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
959     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
960     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
961     KnownZero = KnownZero.zextOrTrunc(BitWidth);
962     KnownOne = KnownOne.zextOrTrunc(BitWidth);
963     // Any top bits are known to be zero.
964     if (BitWidth > SrcBitWidth)
965       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
966     break;
967   }
968   case Instruction::BitCast: {
969     Type *SrcTy = I->getOperand(0)->getType();
970     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
971         // TODO: For now, not handling conversions like:
972         // (bitcast i64 %x to <2 x i32>)
973         !I->getType()->isVectorTy()) {
974       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
975       break;
976     }
977     break;
978   }
979   case Instruction::SExt: {
980     // Compute the bits in the result that are not present in the input.
981     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
982
983     KnownZero = KnownZero.trunc(SrcBitWidth);
984     KnownOne = KnownOne.trunc(SrcBitWidth);
985     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
986     KnownZero = KnownZero.zext(BitWidth);
987     KnownOne = KnownOne.zext(BitWidth);
988
989     // If the sign bit of the input is known set or clear, then we know the
990     // top bits of the result.
991     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
992       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
993     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
994       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
995     break;
996   }
997   case Instruction::Shl:
998     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
999     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1001       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1002       KnownZero <<= ShiftAmt;
1003       KnownOne  <<= ShiftAmt;
1004       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
1005       break;
1006     }
1007     break;
1008   case Instruction::LShr:
1009     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1010     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1011       // Compute the new bits that are at the top now.
1012       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1013
1014       // Unsigned shift right.
1015       computeKnownBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1, Q);
1016       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1017       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
1018       // high bits known zero.
1019       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
1020       break;
1021     }
1022     break;
1023   case Instruction::AShr:
1024     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1025     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1026       // Compute the new bits that are at the top now.
1027       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
1028
1029       // Signed shift right.
1030       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1031       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1032       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
1033
1034       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1035       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
1036         KnownZero |= HighBits;
1037       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
1038         KnownOne |= HighBits;
1039       break;
1040     }
1041     break;
1042   case Instruction::Sub: {
1043     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1044     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1045                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
1046                             Depth, Q);
1047     break;
1048   }
1049   case Instruction::Add: {
1050     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1051     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1052                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
1053                             Depth, Q);
1054     break;
1055   }
1056   case Instruction::SRem:
1057     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1058       APInt RA = Rem->getValue().abs();
1059       if (RA.isPowerOf2()) {
1060         APInt LowBits = RA - 1;
1061         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD,
1062                          Depth+1, Q);
1063
1064         // The low bits of the first operand are unchanged by the srem.
1065         KnownZero = KnownZero2 & LowBits;
1066         KnownOne = KnownOne2 & LowBits;
1067
1068         // If the first operand is non-negative or has all low bits zero, then
1069         // the upper bits are all zero.
1070         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1071           KnownZero |= ~LowBits;
1072
1073         // If the first operand is negative and not all low bits are zero, then
1074         // the upper bits are all one.
1075         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1076           KnownOne |= ~LowBits;
1077
1078         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1079       }
1080     }
1081
1082     // The sign bit is the LHS's sign bit, except when the result of the
1083     // remainder is zero.
1084     if (KnownZero.isNonNegative()) {
1085       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1086       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
1087                        Depth+1, Q);
1088       // If it's known zero, our sign bit is also zero.
1089       if (LHSKnownZero.isNegative())
1090         KnownZero.setBit(BitWidth - 1);
1091     }
1092
1093     break;
1094   case Instruction::URem: {
1095     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1096       APInt RA = Rem->getValue();
1097       if (RA.isPowerOf2()) {
1098         APInt LowBits = (RA - 1);
1099         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
1100                          Depth+1, Q);
1101         KnownZero |= ~LowBits;
1102         KnownOne &= LowBits;
1103         break;
1104       }
1105     }
1106
1107     // Since the result is less than or equal to either operand, any leading
1108     // zero bits in either operand must also exist in the result.
1109     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1110     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
1111
1112     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1113                                 KnownZero2.countLeadingOnes());
1114     KnownOne.clearAllBits();
1115     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1116     break;
1117   }
1118
1119   case Instruction::Alloca: {
1120     AllocaInst *AI = cast<AllocaInst>(V);
1121     unsigned Align = AI->getAlignment();
1122     if (Align == 0 && TD)
1123       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1124
1125     if (Align > 0)
1126       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1127     break;
1128   }
1129   case Instruction::GetElementPtr: {
1130     // Analyze all of the subscripts of this getelementptr instruction
1131     // to determine if we can prove known low zero bits.
1132     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1133     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
1134                      Depth+1, Q);
1135     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1136
1137     gep_type_iterator GTI = gep_type_begin(I);
1138     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1139       Value *Index = I->getOperand(i);
1140       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1141         // Handle struct member offset arithmetic.
1142         if (!TD) {
1143           TrailZ = 0;
1144           break;
1145         }
1146
1147         // Handle case when index is vector zeroinitializer
1148         Constant *CIndex = cast<Constant>(Index);
1149         if (CIndex->isZeroValue())
1150           continue;
1151
1152         if (CIndex->getType()->isVectorTy())
1153           Index = CIndex->getSplatValue();
1154
1155         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1156         const StructLayout *SL = TD->getStructLayout(STy);
1157         uint64_t Offset = SL->getElementOffset(Idx);
1158         TrailZ = std::min<unsigned>(TrailZ,
1159                                     countTrailingZeros(Offset));
1160       } else {
1161         // Handle array index arithmetic.
1162         Type *IndexedTy = GTI.getIndexedType();
1163         if (!IndexedTy->isSized()) {
1164           TrailZ = 0;
1165           break;
1166         }
1167         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1168         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
1169         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1170         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1, Q);
1171         TrailZ = std::min(TrailZ,
1172                           unsigned(countTrailingZeros(TypeSize) +
1173                                    LocalKnownZero.countTrailingOnes()));
1174       }
1175     }
1176
1177     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1178     break;
1179   }
1180   case Instruction::PHI: {
1181     PHINode *P = cast<PHINode>(I);
1182     // Handle the case of a simple two-predecessor recurrence PHI.
1183     // There's a lot more that could theoretically be done here, but
1184     // this is sufficient to catch some interesting cases.
1185     if (P->getNumIncomingValues() == 2) {
1186       for (unsigned i = 0; i != 2; ++i) {
1187         Value *L = P->getIncomingValue(i);
1188         Value *R = P->getIncomingValue(!i);
1189         Operator *LU = dyn_cast<Operator>(L);
1190         if (!LU)
1191           continue;
1192         unsigned Opcode = LU->getOpcode();
1193         // Check for operations that have the property that if
1194         // both their operands have low zero bits, the result
1195         // will have low zero bits.
1196         if (Opcode == Instruction::Add ||
1197             Opcode == Instruction::Sub ||
1198             Opcode == Instruction::And ||
1199             Opcode == Instruction::Or ||
1200             Opcode == Instruction::Mul) {
1201           Value *LL = LU->getOperand(0);
1202           Value *LR = LU->getOperand(1);
1203           // Find a recurrence.
1204           if (LL == I)
1205             L = LR;
1206           else if (LR == I)
1207             L = LL;
1208           else
1209             break;
1210           // Ok, we have a PHI of the form L op= R. Check for low
1211           // zero bits.
1212           computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1, Q);
1213
1214           // We need to take the minimum number of known bits
1215           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1216           computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1, Q);
1217
1218           KnownZero = APInt::getLowBitsSet(BitWidth,
1219                                            std::min(KnownZero2.countTrailingOnes(),
1220                                                     KnownZero3.countTrailingOnes()));
1221           break;
1222         }
1223       }
1224     }
1225
1226     // Unreachable blocks may have zero-operand PHI nodes.
1227     if (P->getNumIncomingValues() == 0)
1228       break;
1229
1230     // Otherwise take the unions of the known bit sets of the operands,
1231     // taking conservative care to avoid excessive recursion.
1232     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1233       // Skip if every incoming value references to ourself.
1234       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1235         break;
1236
1237       KnownZero = APInt::getAllOnesValue(BitWidth);
1238       KnownOne = APInt::getAllOnesValue(BitWidth);
1239       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1240         // Skip direct self references.
1241         if (P->getIncomingValue(i) == P) continue;
1242
1243         KnownZero2 = APInt(BitWidth, 0);
1244         KnownOne2 = APInt(BitWidth, 0);
1245         // Recurse, but cap the recursion to one level, because we don't
1246         // want to waste time spinning around in loops.
1247         computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
1248                          MaxDepth-1, Q);
1249         KnownZero &= KnownZero2;
1250         KnownOne &= KnownOne2;
1251         // If all bits have been ruled out, there's no need to check
1252         // more operands.
1253         if (!KnownZero && !KnownOne)
1254           break;
1255       }
1256     }
1257     break;
1258   }
1259   case Instruction::Call:
1260   case Instruction::Invoke:
1261     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1262       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1263     // If a range metadata is attached to this IntrinsicInst, intersect the
1264     // explicit range specified by the metadata and the implicit range of
1265     // the intrinsic.
1266     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1267       switch (II->getIntrinsicID()) {
1268       default: break;
1269       case Intrinsic::ctlz:
1270       case Intrinsic::cttz: {
1271         unsigned LowBits = Log2_32(BitWidth)+1;
1272         // If this call is undefined for 0, the result will be less than 2^n.
1273         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1274           LowBits -= 1;
1275         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1276         break;
1277       }
1278       case Intrinsic::ctpop: {
1279         unsigned LowBits = Log2_32(BitWidth)+1;
1280         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1281         break;
1282       }
1283       case Intrinsic::x86_sse42_crc32_64_64:
1284         KnownZero |= APInt::getHighBitsSet(64, 32);
1285         break;
1286       }
1287     }
1288     break;
1289   case Instruction::ExtractValue:
1290     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1291       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1292       if (EVI->getNumIndices() != 1) break;
1293       if (EVI->getIndices()[0] == 0) {
1294         switch (II->getIntrinsicID()) {
1295         default: break;
1296         case Intrinsic::uadd_with_overflow:
1297         case Intrinsic::sadd_with_overflow:
1298           computeKnownBitsAddSub(true, II->getArgOperand(0),
1299                                  II->getArgOperand(1), false, KnownZero,
1300                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
1301           break;
1302         case Intrinsic::usub_with_overflow:
1303         case Intrinsic::ssub_with_overflow:
1304           computeKnownBitsAddSub(false, II->getArgOperand(0),
1305                                  II->getArgOperand(1), false, KnownZero,
1306                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
1307           break;
1308         case Intrinsic::umul_with_overflow:
1309         case Intrinsic::smul_with_overflow:
1310           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
1311                               false, KnownZero, KnownOne,
1312                               KnownZero2, KnownOne2, TD, Depth, Q);
1313           break;
1314         }
1315       }
1316     }
1317   }
1318
1319   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1320 }
1321
1322 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
1323 /// one.  Convenience wrapper around computeKnownBits.
1324 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1325                     const DataLayout *TD, unsigned Depth,
1326                     const Query &Q) {
1327   unsigned BitWidth = getBitWidth(V->getType(), TD);
1328   if (!BitWidth) {
1329     KnownZero = false;
1330     KnownOne = false;
1331     return;
1332   }
1333   APInt ZeroBits(BitWidth, 0);
1334   APInt OneBits(BitWidth, 0);
1335   computeKnownBits(V, ZeroBits, OneBits, TD, Depth, Q);
1336   KnownOne = OneBits[BitWidth - 1];
1337   KnownZero = ZeroBits[BitWidth - 1];
1338 }
1339
1340 /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have exactly one
1341 /// bit set when defined. For vectors return true if every element is known to
1342 /// be a power of two when defined.  Supports values with integer or pointer
1343 /// types and vectors of integers.
1344 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1345                             const Query &Q) {
1346   if (Constant *C = dyn_cast<Constant>(V)) {
1347     if (C->isNullValue())
1348       return OrZero;
1349     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1350       return CI->getValue().isPowerOf2();
1351     // TODO: Handle vector constants.
1352   }
1353
1354   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
1355   // it is shifted off the end then the result is undefined.
1356   if (match(V, m_Shl(m_One(), m_Value())))
1357     return true;
1358
1359   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1360   // bottom.  If it is shifted off the bottom then the result is undefined.
1361   if (match(V, m_LShr(m_SignBit(), m_Value())))
1362     return true;
1363
1364   // The remaining tests are all recursive, so bail out if we hit the limit.
1365   if (Depth++ == MaxDepth)
1366     return false;
1367
1368   Value *X = nullptr, *Y = nullptr;
1369   // A shift of a power of two is a power of two or zero.
1370   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1371                  match(V, m_Shr(m_Value(X), m_Value()))))
1372     return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q);
1373
1374   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1375     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1376
1377   if (SelectInst *SI = dyn_cast<SelectInst>(V))
1378     return
1379       isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1380       isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1381
1382   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1383     // A power of two and'd with anything is a power of two or zero.
1384     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q) ||
1385         isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth, Q))
1386       return true;
1387     // X & (-X) is always a power of two or zero.
1388     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1389       return true;
1390     return false;
1391   }
1392
1393   // Adding a power-of-two or zero to the same power-of-two or zero yields
1394   // either the original power-of-two, a larger power-of-two or zero.
1395   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1396     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1397     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1398       if (match(X, m_And(m_Specific(Y), m_Value())) ||
1399           match(X, m_And(m_Value(), m_Specific(Y))))
1400         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1401           return true;
1402       if (match(Y, m_And(m_Specific(X), m_Value())) ||
1403           match(Y, m_And(m_Value(), m_Specific(X))))
1404         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1405           return true;
1406
1407       unsigned BitWidth = V->getType()->getScalarSizeInBits();
1408       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1409       computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth, Q);
1410
1411       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1412       computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth, Q);
1413       // If i8 V is a power of two or zero:
1414       //  ZeroBits: 1 1 1 0 1 1 1 1
1415       // ~ZeroBits: 0 0 0 1 0 0 0 0
1416       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1417         // If OrZero isn't set, we cannot give back a zero result.
1418         // Make sure either the LHS or RHS has a bit set.
1419         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1420           return true;
1421     }
1422   }
1423
1424   // An exact divide or right shift can only shift off zero bits, so the result
1425   // is a power of two only if the first operand is a power of two and not
1426   // copying a sign bit (sdiv int_min, 2).
1427   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1428       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1429     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1430                                   Depth, Q);
1431   }
1432
1433   return false;
1434 }
1435
1436 /// \brief Test whether a GEP's result is known to be non-null.
1437 ///
1438 /// Uses properties inherent in a GEP to try to determine whether it is known
1439 /// to be non-null.
1440 ///
1441 /// Currently this routine does not support vector GEPs.
1442 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
1443                               unsigned Depth, const Query &Q) {
1444   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1445     return false;
1446
1447   // FIXME: Support vector-GEPs.
1448   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1449
1450   // If the base pointer is non-null, we cannot walk to a null address with an
1451   // inbounds GEP in address space zero.
1452   if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
1453     return true;
1454
1455   // Past this, if we don't have DataLayout, we can't do much.
1456   if (!DL)
1457     return false;
1458
1459   // Walk the GEP operands and see if any operand introduces a non-zero offset.
1460   // If so, then the GEP cannot produce a null pointer, as doing so would
1461   // inherently violate the inbounds contract within address space zero.
1462   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1463        GTI != GTE; ++GTI) {
1464     // Struct types are easy -- they must always be indexed by a constant.
1465     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1466       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1467       unsigned ElementIdx = OpC->getZExtValue();
1468       const StructLayout *SL = DL->getStructLayout(STy);
1469       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1470       if (ElementOffset > 0)
1471         return true;
1472       continue;
1473     }
1474
1475     // If we have a zero-sized type, the index doesn't matter. Keep looping.
1476     if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
1477       continue;
1478
1479     // Fast path the constant operand case both for efficiency and so we don't
1480     // increment Depth when just zipping down an all-constant GEP.
1481     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1482       if (!OpC->isZero())
1483         return true;
1484       continue;
1485     }
1486
1487     // We post-increment Depth here because while isKnownNonZero increments it
1488     // as well, when we pop back up that increment won't persist. We don't want
1489     // to recurse 10k times just because we have 10k GEP operands. We don't
1490     // bail completely out because we want to handle constant GEPs regardless
1491     // of depth.
1492     if (Depth++ >= MaxDepth)
1493       continue;
1494
1495     if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
1496       return true;
1497   }
1498
1499   return false;
1500 }
1501
1502 /// isKnownNonZero - Return true if the given value is known to be non-zero
1503 /// when defined.  For vectors return true if every element is known to be
1504 /// non-zero when defined.  Supports values with integer or pointer type and
1505 /// vectors of integers.
1506 bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
1507                     const Query &Q) {
1508   if (Constant *C = dyn_cast<Constant>(V)) {
1509     if (C->isNullValue())
1510       return false;
1511     if (isa<ConstantInt>(C))
1512       // Must be non-zero due to null test above.
1513       return true;
1514     // TODO: Handle vectors
1515     return false;
1516   }
1517
1518   // The remaining tests are all recursive, so bail out if we hit the limit.
1519   if (Depth++ >= MaxDepth)
1520     return false;
1521
1522   // Check for pointer simplifications.
1523   if (V->getType()->isPointerTy()) {
1524     if (isKnownNonNull(V))
1525       return true; 
1526     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1527       if (isGEPKnownNonNull(GEP, TD, Depth, Q))
1528         return true;
1529   }
1530
1531   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
1532
1533   // X | Y != 0 if X != 0 or Y != 0.
1534   Value *X = nullptr, *Y = nullptr;
1535   if (match(V, m_Or(m_Value(X), m_Value(Y))))
1536     return isKnownNonZero(X, TD, Depth, Q) ||
1537            isKnownNonZero(Y, TD, Depth, Q);
1538
1539   // ext X != 0 if X != 0.
1540   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1541     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
1542
1543   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
1544   // if the lowest bit is shifted off the end.
1545   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1546     // shl nuw can't remove any non-zero bits.
1547     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1548     if (BO->hasNoUnsignedWrap())
1549       return isKnownNonZero(X, TD, Depth, Q);
1550
1551     APInt KnownZero(BitWidth, 0);
1552     APInt KnownOne(BitWidth, 0);
1553     computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
1554     if (KnownOne[0])
1555       return true;
1556   }
1557   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
1558   // defined if the sign bit is shifted off the end.
1559   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1560     // shr exact can only shift out zero bits.
1561     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1562     if (BO->isExact())
1563       return isKnownNonZero(X, TD, Depth, Q);
1564
1565     bool XKnownNonNegative, XKnownNegative;
1566     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
1567     if (XKnownNegative)
1568       return true;
1569   }
1570   // div exact can only produce a zero if the dividend is zero.
1571   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1572     return isKnownNonZero(X, TD, Depth, Q);
1573   }
1574   // X + Y.
1575   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1576     bool XKnownNonNegative, XKnownNegative;
1577     bool YKnownNonNegative, YKnownNegative;
1578     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
1579     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
1580
1581     // If X and Y are both non-negative (as signed values) then their sum is not
1582     // zero unless both X and Y are zero.
1583     if (XKnownNonNegative && YKnownNonNegative)
1584       if (isKnownNonZero(X, TD, Depth, Q) ||
1585           isKnownNonZero(Y, TD, Depth, Q))
1586         return true;
1587
1588     // If X and Y are both negative (as signed values) then their sum is not
1589     // zero unless both X and Y equal INT_MIN.
1590     if (BitWidth && XKnownNegative && YKnownNegative) {
1591       APInt KnownZero(BitWidth, 0);
1592       APInt KnownOne(BitWidth, 0);
1593       APInt Mask = APInt::getSignedMaxValue(BitWidth);
1594       // The sign bit of X is set.  If some other bit is set then X is not equal
1595       // to INT_MIN.
1596       computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
1597       if ((KnownOne & Mask) != 0)
1598         return true;
1599       // The sign bit of Y is set.  If some other bit is set then Y is not equal
1600       // to INT_MIN.
1601       computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
1602       if ((KnownOne & Mask) != 0)
1603         return true;
1604     }
1605
1606     // The sum of a non-negative number and a power of two is not zero.
1607     if (XKnownNonNegative &&
1608         isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
1609       return true;
1610     if (YKnownNonNegative &&
1611         isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
1612       return true;
1613   }
1614   // X * Y.
1615   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1616     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1617     // If X and Y are non-zero then so is X * Y as long as the multiplication
1618     // does not overflow.
1619     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1620         isKnownNonZero(X, TD, Depth, Q) &&
1621         isKnownNonZero(Y, TD, Depth, Q))
1622       return true;
1623   }
1624   // (C ? X : Y) != 0 if X != 0 and Y != 0.
1625   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1626     if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
1627         isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
1628       return true;
1629   }
1630
1631   if (!BitWidth) return false;
1632   APInt KnownZero(BitWidth, 0);
1633   APInt KnownOne(BitWidth, 0);
1634   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1635   return KnownOne != 0;
1636 }
1637
1638 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1639 /// this predicate to simplify operations downstream.  Mask is known to be zero
1640 /// for bits that V cannot have.
1641 ///
1642 /// This function is defined on values with integer type, values with pointer
1643 /// type (but only if TD is non-null), and vectors of integers.  In the case
1644 /// where V is a vector, the mask, known zero, and known one values are the
1645 /// same width as the vector element, and the bit is set only if it is true
1646 /// for all of the elements in the vector.
1647 bool MaskedValueIsZero(Value *V, const APInt &Mask,
1648                        const DataLayout *TD, unsigned Depth,
1649                        const Query &Q) {
1650   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1651   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1652   return (KnownZero & Mask) == Mask;
1653 }
1654
1655
1656
1657 /// ComputeNumSignBits - Return the number of times the sign bit of the
1658 /// register is replicated into the other bits.  We know that at least 1 bit
1659 /// is always equal to the sign bit (itself), but other cases can give us
1660 /// information.  For example, immediately after an "ashr X, 2", we know that
1661 /// the top 3 bits are all equal to each other, so we return 3.
1662 ///
1663 /// 'Op' must have a scalar integer type.
1664 ///
1665 unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
1666                             unsigned Depth, const Query &Q) {
1667   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
1668          "ComputeNumSignBits requires a DataLayout object to operate "
1669          "on non-integer values!");
1670   Type *Ty = V->getType();
1671   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1672                          Ty->getScalarSizeInBits();
1673   unsigned Tmp, Tmp2;
1674   unsigned FirstAnswer = 1;
1675
1676   // Note that ConstantInt is handled by the general computeKnownBits case
1677   // below.
1678
1679   if (Depth == 6)
1680     return 1;  // Limit search depth.
1681
1682   Operator *U = dyn_cast<Operator>(V);
1683   switch (Operator::getOpcode(V)) {
1684   default: break;
1685   case Instruction::SExt:
1686     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1687     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
1688
1689   case Instruction::AShr: {
1690     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1691     // ashr X, C   -> adds C sign bits.  Vectors too.
1692     const APInt *ShAmt;
1693     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1694       Tmp += ShAmt->getZExtValue();
1695       if (Tmp > TyBits) Tmp = TyBits;
1696     }
1697     return Tmp;
1698   }
1699   case Instruction::Shl: {
1700     const APInt *ShAmt;
1701     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1702       // shl destroys sign bits.
1703       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1704       Tmp2 = ShAmt->getZExtValue();
1705       if (Tmp2 >= TyBits ||      // Bad shift.
1706           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
1707       return Tmp - Tmp2;
1708     }
1709     break;
1710   }
1711   case Instruction::And:
1712   case Instruction::Or:
1713   case Instruction::Xor:    // NOT is handled here.
1714     // Logical binary ops preserve the number of sign bits at the worst.
1715     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1716     if (Tmp != 1) {
1717       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1718       FirstAnswer = std::min(Tmp, Tmp2);
1719       // We computed what we know about the sign bits as our first
1720       // answer. Now proceed to the generic code that uses
1721       // computeKnownBits, and pick whichever answer is better.
1722     }
1723     break;
1724
1725   case Instruction::Select:
1726     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1727     if (Tmp == 1) return 1;  // Early out.
1728     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
1729     return std::min(Tmp, Tmp2);
1730
1731   case Instruction::Add:
1732     // Add can have at most one carry bit.  Thus we know that the output
1733     // is, at worst, one more bit than the inputs.
1734     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1735     if (Tmp == 1) return 1;  // Early out.
1736
1737     // Special case decrementing a value (ADD X, -1):
1738     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
1739       if (CRHS->isAllOnesValue()) {
1740         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1741         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1742
1743         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1744         // sign bits set.
1745         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1746           return TyBits;
1747
1748         // If we are subtracting one from a positive number, there is no carry
1749         // out of the result.
1750         if (KnownZero.isNegative())
1751           return Tmp;
1752       }
1753
1754     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1755     if (Tmp2 == 1) return 1;
1756     return std::min(Tmp, Tmp2)-1;
1757
1758   case Instruction::Sub:
1759     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1760     if (Tmp2 == 1) return 1;
1761
1762     // Handle NEG.
1763     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1764       if (CLHS->isNullValue()) {
1765         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1766         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
1767         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1768         // sign bits set.
1769         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1770           return TyBits;
1771
1772         // If the input is known to be positive (the sign bit is known clear),
1773         // the output of the NEG has the same number of sign bits as the input.
1774         if (KnownZero.isNegative())
1775           return Tmp2;
1776
1777         // Otherwise, we treat this like a SUB.
1778       }
1779
1780     // Sub can have at most one carry bit.  Thus we know that the output
1781     // is, at worst, one more bit than the inputs.
1782     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1783     if (Tmp == 1) return 1;  // Early out.
1784     return std::min(Tmp, Tmp2)-1;
1785
1786   case Instruction::PHI: {
1787     PHINode *PN = cast<PHINode>(U);
1788     // Don't analyze large in-degree PHIs.
1789     if (PN->getNumIncomingValues() > 4) break;
1790
1791     // Take the minimum of all incoming values.  This can't infinitely loop
1792     // because of our depth threshold.
1793     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
1794     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1795       if (Tmp == 1) return Tmp;
1796       Tmp = std::min(Tmp,
1797                      ComputeNumSignBits(PN->getIncomingValue(i), TD,
1798                                         Depth+1, Q));
1799     }
1800     return Tmp;
1801   }
1802
1803   case Instruction::Trunc:
1804     // FIXME: it's tricky to do anything useful for this, but it is an important
1805     // case for targets like X86.
1806     break;
1807   }
1808
1809   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1810   // use this information.
1811   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1812   APInt Mask;
1813   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1814
1815   if (KnownZero.isNegative()) {        // sign bit is 0
1816     Mask = KnownZero;
1817   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1818     Mask = KnownOne;
1819   } else {
1820     // Nothing known.
1821     return FirstAnswer;
1822   }
1823
1824   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1825   // the number of identical bits in the top of the input value.
1826   Mask = ~Mask;
1827   Mask <<= Mask.getBitWidth()-TyBits;
1828   // Return # leading zeros.  We use 'min' here in case Val was zero before
1829   // shifting.  We don't want to return '64' as for an i32 "0".
1830   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1831 }
1832
1833 /// ComputeMultiple - This function computes the integer multiple of Base that
1834 /// equals V.  If successful, it returns true and returns the multiple in
1835 /// Multiple.  If unsuccessful, it returns false. It looks
1836 /// through SExt instructions only if LookThroughSExt is true.
1837 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
1838                            bool LookThroughSExt, unsigned Depth) {
1839   const unsigned MaxDepth = 6;
1840
1841   assert(V && "No Value?");
1842   assert(Depth <= MaxDepth && "Limit Search Depth");
1843   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
1844
1845   Type *T = V->getType();
1846
1847   ConstantInt *CI = dyn_cast<ConstantInt>(V);
1848
1849   if (Base == 0)
1850     return false;
1851
1852   if (Base == 1) {
1853     Multiple = V;
1854     return true;
1855   }
1856
1857   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1858   Constant *BaseVal = ConstantInt::get(T, Base);
1859   if (CO && CO == BaseVal) {
1860     // Multiple is 1.
1861     Multiple = ConstantInt::get(T, 1);
1862     return true;
1863   }
1864
1865   if (CI && CI->getZExtValue() % Base == 0) {
1866     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1867     return true;
1868   }
1869
1870   if (Depth == MaxDepth) return false;  // Limit search depth.
1871
1872   Operator *I = dyn_cast<Operator>(V);
1873   if (!I) return false;
1874
1875   switch (I->getOpcode()) {
1876   default: break;
1877   case Instruction::SExt:
1878     if (!LookThroughSExt) return false;
1879     // otherwise fall through to ZExt
1880   case Instruction::ZExt:
1881     return ComputeMultiple(I->getOperand(0), Base, Multiple,
1882                            LookThroughSExt, Depth+1);
1883   case Instruction::Shl:
1884   case Instruction::Mul: {
1885     Value *Op0 = I->getOperand(0);
1886     Value *Op1 = I->getOperand(1);
1887
1888     if (I->getOpcode() == Instruction::Shl) {
1889       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1890       if (!Op1CI) return false;
1891       // Turn Op0 << Op1 into Op0 * 2^Op1
1892       APInt Op1Int = Op1CI->getValue();
1893       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
1894       APInt API(Op1Int.getBitWidth(), 0);
1895       API.setBit(BitToSet);
1896       Op1 = ConstantInt::get(V->getContext(), API);
1897     }
1898
1899     Value *Mul0 = nullptr;
1900     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1901       if (Constant *Op1C = dyn_cast<Constant>(Op1))
1902         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1903           if (Op1C->getType()->getPrimitiveSizeInBits() <
1904               MulC->getType()->getPrimitiveSizeInBits())
1905             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1906           if (Op1C->getType()->getPrimitiveSizeInBits() >
1907               MulC->getType()->getPrimitiveSizeInBits())
1908             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1909
1910           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1911           Multiple = ConstantExpr::getMul(MulC, Op1C);
1912           return true;
1913         }
1914
1915       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1916         if (Mul0CI->getValue() == 1) {
1917           // V == Base * Op1, so return Op1
1918           Multiple = Op1;
1919           return true;
1920         }
1921     }
1922
1923     Value *Mul1 = nullptr;
1924     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1925       if (Constant *Op0C = dyn_cast<Constant>(Op0))
1926         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1927           if (Op0C->getType()->getPrimitiveSizeInBits() <
1928               MulC->getType()->getPrimitiveSizeInBits())
1929             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1930           if (Op0C->getType()->getPrimitiveSizeInBits() >
1931               MulC->getType()->getPrimitiveSizeInBits())
1932             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1933
1934           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1935           Multiple = ConstantExpr::getMul(MulC, Op0C);
1936           return true;
1937         }
1938
1939       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1940         if (Mul1CI->getValue() == 1) {
1941           // V == Base * Op0, so return Op0
1942           Multiple = Op0;
1943           return true;
1944         }
1945     }
1946   }
1947   }
1948
1949   // We could not determine if V is a multiple of Base.
1950   return false;
1951 }
1952
1953 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
1954 /// value is never equal to -0.0.
1955 ///
1956 /// NOTE: this function will need to be revisited when we support non-default
1957 /// rounding modes!
1958 ///
1959 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1960   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1961     return !CFP->getValueAPF().isNegZero();
1962
1963   if (Depth == 6)
1964     return 1;  // Limit search depth.
1965
1966   const Operator *I = dyn_cast<Operator>(V);
1967   if (!I) return false;
1968
1969   // Check if the nsz fast-math flag is set
1970   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
1971     if (FPO->hasNoSignedZeros())
1972       return true;
1973
1974   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1975   if (I->getOpcode() == Instruction::FAdd)
1976     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
1977       if (CFP->isNullValue())
1978         return true;
1979
1980   // sitofp and uitofp turn into +0.0 for zero.
1981   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1982     return true;
1983
1984   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1985     // sqrt(-0.0) = -0.0, no other negative results are possible.
1986     if (II->getIntrinsicID() == Intrinsic::sqrt)
1987       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
1988
1989   if (const CallInst *CI = dyn_cast<CallInst>(I))
1990     if (const Function *F = CI->getCalledFunction()) {
1991       if (F->isDeclaration()) {
1992         // abs(x) != -0.0
1993         if (F->getName() == "abs") return true;
1994         // fabs[lf](x) != -0.0
1995         if (F->getName() == "fabs") return true;
1996         if (F->getName() == "fabsf") return true;
1997         if (F->getName() == "fabsl") return true;
1998         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1999             F->getName() == "sqrtl")
2000           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
2001       }
2002     }
2003
2004   return false;
2005 }
2006
2007 /// isBytewiseValue - If the specified value can be set by repeating the same
2008 /// byte in memory, return the i8 value that it is represented with.  This is
2009 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2010 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
2011 /// byte store (e.g. i16 0x1234), return null.
2012 Value *llvm::isBytewiseValue(Value *V) {
2013   // All byte-wide stores are splatable, even of arbitrary variables.
2014   if (V->getType()->isIntegerTy(8)) return V;
2015
2016   // Handle 'null' ConstantArrayZero etc.
2017   if (Constant *C = dyn_cast<Constant>(V))
2018     if (C->isNullValue())
2019       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2020
2021   // Constant float and double values can be handled as integer values if the
2022   // corresponding integer value is "byteable".  An important case is 0.0.
2023   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2024     if (CFP->getType()->isFloatTy())
2025       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2026     if (CFP->getType()->isDoubleTy())
2027       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2028     // Don't handle long double formats, which have strange constraints.
2029   }
2030
2031   // We can handle constant integers that are power of two in size and a
2032   // multiple of 8 bits.
2033   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2034     unsigned Width = CI->getBitWidth();
2035     if (isPowerOf2_32(Width) && Width > 8) {
2036       // We can handle this value if the recursive binary decomposition is the
2037       // same at all levels.
2038       APInt Val = CI->getValue();
2039       APInt Val2;
2040       while (Val.getBitWidth() != 8) {
2041         unsigned NextWidth = Val.getBitWidth()/2;
2042         Val2  = Val.lshr(NextWidth);
2043         Val2 = Val2.trunc(Val.getBitWidth()/2);
2044         Val = Val.trunc(Val.getBitWidth()/2);
2045
2046         // If the top/bottom halves aren't the same, reject it.
2047         if (Val != Val2)
2048           return nullptr;
2049       }
2050       return ConstantInt::get(V->getContext(), Val);
2051     }
2052   }
2053
2054   // A ConstantDataArray/Vector is splatable if all its members are equal and
2055   // also splatable.
2056   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2057     Value *Elt = CA->getElementAsConstant(0);
2058     Value *Val = isBytewiseValue(Elt);
2059     if (!Val)
2060       return nullptr;
2061
2062     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2063       if (CA->getElementAsConstant(I) != Elt)
2064         return nullptr;
2065
2066     return Val;
2067   }
2068
2069   // Conceptually, we could handle things like:
2070   //   %a = zext i8 %X to i16
2071   //   %b = shl i16 %a, 8
2072   //   %c = or i16 %a, %b
2073   // but until there is an example that actually needs this, it doesn't seem
2074   // worth worrying about.
2075   return nullptr;
2076 }
2077
2078
2079 // This is the recursive version of BuildSubAggregate. It takes a few different
2080 // arguments. Idxs is the index within the nested struct From that we are
2081 // looking at now (which is of type IndexedType). IdxSkip is the number of
2082 // indices from Idxs that should be left out when inserting into the resulting
2083 // struct. To is the result struct built so far, new insertvalue instructions
2084 // build on that.
2085 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2086                                 SmallVectorImpl<unsigned> &Idxs,
2087                                 unsigned IdxSkip,
2088                                 Instruction *InsertBefore) {
2089   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2090   if (STy) {
2091     // Save the original To argument so we can modify it
2092     Value *OrigTo = To;
2093     // General case, the type indexed by Idxs is a struct
2094     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2095       // Process each struct element recursively
2096       Idxs.push_back(i);
2097       Value *PrevTo = To;
2098       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2099                              InsertBefore);
2100       Idxs.pop_back();
2101       if (!To) {
2102         // Couldn't find any inserted value for this index? Cleanup
2103         while (PrevTo != OrigTo) {
2104           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2105           PrevTo = Del->getAggregateOperand();
2106           Del->eraseFromParent();
2107         }
2108         // Stop processing elements
2109         break;
2110       }
2111     }
2112     // If we successfully found a value for each of our subaggregates
2113     if (To)
2114       return To;
2115   }
2116   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2117   // the struct's elements had a value that was inserted directly. In the latter
2118   // case, perhaps we can't determine each of the subelements individually, but
2119   // we might be able to find the complete struct somewhere.
2120
2121   // Find the value that is at that particular spot
2122   Value *V = FindInsertedValue(From, Idxs);
2123
2124   if (!V)
2125     return nullptr;
2126
2127   // Insert the value in the new (sub) aggregrate
2128   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2129                                        "tmp", InsertBefore);
2130 }
2131
2132 // This helper takes a nested struct and extracts a part of it (which is again a
2133 // struct) into a new value. For example, given the struct:
2134 // { a, { b, { c, d }, e } }
2135 // and the indices "1, 1" this returns
2136 // { c, d }.
2137 //
2138 // It does this by inserting an insertvalue for each element in the resulting
2139 // struct, as opposed to just inserting a single struct. This will only work if
2140 // each of the elements of the substruct are known (ie, inserted into From by an
2141 // insertvalue instruction somewhere).
2142 //
2143 // All inserted insertvalue instructions are inserted before InsertBefore
2144 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2145                                 Instruction *InsertBefore) {
2146   assert(InsertBefore && "Must have someplace to insert!");
2147   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2148                                                              idx_range);
2149   Value *To = UndefValue::get(IndexedType);
2150   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2151   unsigned IdxSkip = Idxs.size();
2152
2153   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2154 }
2155
2156 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
2157 /// the scalar value indexed is already around as a register, for example if it
2158 /// were inserted directly into the aggregrate.
2159 ///
2160 /// If InsertBefore is not null, this function will duplicate (modified)
2161 /// insertvalues when a part of a nested struct is extracted.
2162 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2163                                Instruction *InsertBefore) {
2164   // Nothing to index? Just return V then (this is useful at the end of our
2165   // recursion).
2166   if (idx_range.empty())
2167     return V;
2168   // We have indices, so V should have an indexable type.
2169   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2170          "Not looking at a struct or array?");
2171   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2172          "Invalid indices for type?");
2173
2174   if (Constant *C = dyn_cast<Constant>(V)) {
2175     C = C->getAggregateElement(idx_range[0]);
2176     if (!C) return nullptr;
2177     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2178   }
2179
2180   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2181     // Loop the indices for the insertvalue instruction in parallel with the
2182     // requested indices
2183     const unsigned *req_idx = idx_range.begin();
2184     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2185          i != e; ++i, ++req_idx) {
2186       if (req_idx == idx_range.end()) {
2187         // We can't handle this without inserting insertvalues
2188         if (!InsertBefore)
2189           return nullptr;
2190
2191         // The requested index identifies a part of a nested aggregate. Handle
2192         // this specially. For example,
2193         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2194         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2195         // %C = extractvalue {i32, { i32, i32 } } %B, 1
2196         // This can be changed into
2197         // %A = insertvalue {i32, i32 } undef, i32 10, 0
2198         // %C = insertvalue {i32, i32 } %A, i32 11, 1
2199         // which allows the unused 0,0 element from the nested struct to be
2200         // removed.
2201         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2202                                  InsertBefore);
2203       }
2204
2205       // This insert value inserts something else than what we are looking for.
2206       // See if the (aggregrate) value inserted into has the value we are
2207       // looking for, then.
2208       if (*req_idx != *i)
2209         return FindInsertedValue(I->getAggregateOperand(), idx_range,
2210                                  InsertBefore);
2211     }
2212     // If we end up here, the indices of the insertvalue match with those
2213     // requested (though possibly only partially). Now we recursively look at
2214     // the inserted value, passing any remaining indices.
2215     return FindInsertedValue(I->getInsertedValueOperand(),
2216                              makeArrayRef(req_idx, idx_range.end()),
2217                              InsertBefore);
2218   }
2219
2220   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2221     // If we're extracting a value from an aggregrate that was extracted from
2222     // something else, we can extract from that something else directly instead.
2223     // However, we will need to chain I's indices with the requested indices.
2224
2225     // Calculate the number of indices required
2226     unsigned size = I->getNumIndices() + idx_range.size();
2227     // Allocate some space to put the new indices in
2228     SmallVector<unsigned, 5> Idxs;
2229     Idxs.reserve(size);
2230     // Add indices from the extract value instruction
2231     Idxs.append(I->idx_begin(), I->idx_end());
2232
2233     // Add requested indices
2234     Idxs.append(idx_range.begin(), idx_range.end());
2235
2236     assert(Idxs.size() == size
2237            && "Number of indices added not correct?");
2238
2239     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2240   }
2241   // Otherwise, we don't know (such as, extracting from a function return value
2242   // or load instruction)
2243   return nullptr;
2244 }
2245
2246 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
2247 /// it can be expressed as a base pointer plus a constant offset.  Return the
2248 /// base and offset to the caller.
2249 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2250                                               const DataLayout *DL) {
2251   // Without DataLayout, conservatively assume 64-bit offsets, which is
2252   // the widest we support.
2253   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
2254   APInt ByteOffset(BitWidth, 0);
2255   while (1) {
2256     if (Ptr->getType()->isVectorTy())
2257       break;
2258
2259     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2260       if (DL) {
2261         APInt GEPOffset(BitWidth, 0);
2262         if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
2263           break;
2264
2265         ByteOffset += GEPOffset;
2266       }
2267
2268       Ptr = GEP->getPointerOperand();
2269     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2270                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2271       Ptr = cast<Operator>(Ptr)->getOperand(0);
2272     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2273       if (GA->mayBeOverridden())
2274         break;
2275       Ptr = GA->getAliasee();
2276     } else {
2277       break;
2278     }
2279   }
2280   Offset = ByteOffset.getSExtValue();
2281   return Ptr;
2282 }
2283
2284
2285 /// getConstantStringInfo - This function computes the length of a
2286 /// null-terminated C string pointed to by V.  If successful, it returns true
2287 /// and returns the string in Str.  If unsuccessful, it returns false.
2288 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2289                                  uint64_t Offset, bool TrimAtNul) {
2290   assert(V);
2291
2292   // Look through bitcast instructions and geps.
2293   V = V->stripPointerCasts();
2294
2295   // If the value is a GEP instructionor  constant expression, treat it as an
2296   // offset.
2297   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2298     // Make sure the GEP has exactly three arguments.
2299     if (GEP->getNumOperands() != 3)
2300       return false;
2301
2302     // Make sure the index-ee is a pointer to array of i8.
2303     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2304     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
2305     if (!AT || !AT->getElementType()->isIntegerTy(8))
2306       return false;
2307
2308     // Check to make sure that the first operand of the GEP is an integer and
2309     // has value 0 so that we are sure we're indexing into the initializer.
2310     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2311     if (!FirstIdx || !FirstIdx->isZero())
2312       return false;
2313
2314     // If the second index isn't a ConstantInt, then this is a variable index
2315     // into the array.  If this occurs, we can't say anything meaningful about
2316     // the string.
2317     uint64_t StartIdx = 0;
2318     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2319       StartIdx = CI->getZExtValue();
2320     else
2321       return false;
2322     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
2323   }
2324
2325   // The GEP instruction, constant or instruction, must reference a global
2326   // variable that is a constant and is initialized. The referenced constant
2327   // initializer is the array that we'll use for optimization.
2328   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2329   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2330     return false;
2331
2332   // Handle the all-zeros case
2333   if (GV->getInitializer()->isNullValue()) {
2334     // This is a degenerate case. The initializer is constant zero so the
2335     // length of the string must be zero.
2336     Str = "";
2337     return true;
2338   }
2339
2340   // Must be a Constant Array
2341   const ConstantDataArray *Array =
2342     dyn_cast<ConstantDataArray>(GV->getInitializer());
2343   if (!Array || !Array->isString())
2344     return false;
2345
2346   // Get the number of elements in the array
2347   uint64_t NumElts = Array->getType()->getArrayNumElements();
2348
2349   // Start out with the entire array in the StringRef.
2350   Str = Array->getAsString();
2351
2352   if (Offset > NumElts)
2353     return false;
2354
2355   // Skip over 'offset' bytes.
2356   Str = Str.substr(Offset);
2357
2358   if (TrimAtNul) {
2359     // Trim off the \0 and anything after it.  If the array is not nul
2360     // terminated, we just return the whole end of string.  The client may know
2361     // some other way that the string is length-bound.
2362     Str = Str.substr(0, Str.find('\0'));
2363   }
2364   return true;
2365 }
2366
2367 // These next two are very similar to the above, but also look through PHI
2368 // nodes.
2369 // TODO: See if we can integrate these two together.
2370
2371 /// GetStringLengthH - If we can compute the length of the string pointed to by
2372 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2373 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2374   // Look through noop bitcast instructions.
2375   V = V->stripPointerCasts();
2376
2377   // If this is a PHI node, there are two cases: either we have already seen it
2378   // or we haven't.
2379   if (PHINode *PN = dyn_cast<PHINode>(V)) {
2380     if (!PHIs.insert(PN))
2381       return ~0ULL;  // already in the set.
2382
2383     // If it was new, see if all the input strings are the same length.
2384     uint64_t LenSoFar = ~0ULL;
2385     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2386       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2387       if (Len == 0) return 0; // Unknown length -> unknown.
2388
2389       if (Len == ~0ULL) continue;
2390
2391       if (Len != LenSoFar && LenSoFar != ~0ULL)
2392         return 0;    // Disagree -> unknown.
2393       LenSoFar = Len;
2394     }
2395
2396     // Success, all agree.
2397     return LenSoFar;
2398   }
2399
2400   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2401   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2402     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2403     if (Len1 == 0) return 0;
2404     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2405     if (Len2 == 0) return 0;
2406     if (Len1 == ~0ULL) return Len2;
2407     if (Len2 == ~0ULL) return Len1;
2408     if (Len1 != Len2) return 0;
2409     return Len1;
2410   }
2411
2412   // Otherwise, see if we can read the string.
2413   StringRef StrData;
2414   if (!getConstantStringInfo(V, StrData))
2415     return 0;
2416
2417   return StrData.size()+1;
2418 }
2419
2420 /// GetStringLength - If we can compute the length of the string pointed to by
2421 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2422 uint64_t llvm::GetStringLength(Value *V) {
2423   if (!V->getType()->isPointerTy()) return 0;
2424
2425   SmallPtrSet<PHINode*, 32> PHIs;
2426   uint64_t Len = GetStringLengthH(V, PHIs);
2427   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2428   // an empty string as a length.
2429   return Len == ~0ULL ? 1 : Len;
2430 }
2431
2432 Value *
2433 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
2434   if (!V->getType()->isPointerTy())
2435     return V;
2436   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2437     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2438       V = GEP->getPointerOperand();
2439     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2440                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
2441       V = cast<Operator>(V)->getOperand(0);
2442     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2443       if (GA->mayBeOverridden())
2444         return V;
2445       V = GA->getAliasee();
2446     } else {
2447       // See if InstructionSimplify knows any relevant tricks.
2448       if (Instruction *I = dyn_cast<Instruction>(V))
2449         // TODO: Acquire a DominatorTree and AssumptionTracker and use them.
2450         if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
2451           V = Simplified;
2452           continue;
2453         }
2454
2455       return V;
2456     }
2457     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2458   }
2459   return V;
2460 }
2461
2462 void
2463 llvm::GetUnderlyingObjects(Value *V,
2464                            SmallVectorImpl<Value *> &Objects,
2465                            const DataLayout *TD,
2466                            unsigned MaxLookup) {
2467   SmallPtrSet<Value *, 4> Visited;
2468   SmallVector<Value *, 4> Worklist;
2469   Worklist.push_back(V);
2470   do {
2471     Value *P = Worklist.pop_back_val();
2472     P = GetUnderlyingObject(P, TD, MaxLookup);
2473
2474     if (!Visited.insert(P))
2475       continue;
2476
2477     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2478       Worklist.push_back(SI->getTrueValue());
2479       Worklist.push_back(SI->getFalseValue());
2480       continue;
2481     }
2482
2483     if (PHINode *PN = dyn_cast<PHINode>(P)) {
2484       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2485         Worklist.push_back(PN->getIncomingValue(i));
2486       continue;
2487     }
2488
2489     Objects.push_back(P);
2490   } while (!Worklist.empty());
2491 }
2492
2493 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
2494 /// are lifetime markers.
2495 ///
2496 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
2497   for (const User *U : V->users()) {
2498     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2499     if (!II) return false;
2500
2501     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2502         II->getIntrinsicID() != Intrinsic::lifetime_end)
2503       return false;
2504   }
2505   return true;
2506 }
2507
2508 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
2509                                         const DataLayout *TD) {
2510   const Operator *Inst = dyn_cast<Operator>(V);
2511   if (!Inst)
2512     return false;
2513
2514   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2515     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2516       if (C->canTrap())
2517         return false;
2518
2519   switch (Inst->getOpcode()) {
2520   default:
2521     return true;
2522   case Instruction::UDiv:
2523   case Instruction::URem:
2524     // x / y is undefined if y == 0, but calculations like x / 3 are safe.
2525     return isKnownNonZero(Inst->getOperand(1), TD);
2526   case Instruction::SDiv:
2527   case Instruction::SRem: {
2528     Value *Op = Inst->getOperand(1);
2529     // x / y is undefined if y == 0
2530     if (!isKnownNonZero(Op, TD))
2531       return false;
2532     // x / y might be undefined if y == -1
2533     unsigned BitWidth = getBitWidth(Op->getType(), TD);
2534     if (BitWidth == 0)
2535       return false;
2536     APInt KnownZero(BitWidth, 0);
2537     APInt KnownOne(BitWidth, 0);
2538     computeKnownBits(Op, KnownZero, KnownOne, TD);
2539     return !!KnownZero;
2540   }
2541   case Instruction::Load: {
2542     const LoadInst *LI = cast<LoadInst>(Inst);
2543     if (!LI->isUnordered() ||
2544         // Speculative load may create a race that did not exist in the source.
2545         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
2546       return false;
2547     return LI->getPointerOperand()->isDereferenceablePointer(TD);
2548   }
2549   case Instruction::Call: {
2550    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2551      switch (II->getIntrinsicID()) {
2552        // These synthetic intrinsics have no side-effects and just mark
2553        // information about their operands.
2554        // FIXME: There are other no-op synthetic instructions that potentially
2555        // should be considered at least *safe* to speculate...
2556        case Intrinsic::dbg_declare:
2557        case Intrinsic::dbg_value:
2558          return true;
2559
2560        case Intrinsic::bswap:
2561        case Intrinsic::ctlz:
2562        case Intrinsic::ctpop:
2563        case Intrinsic::cttz:
2564        case Intrinsic::objectsize:
2565        case Intrinsic::sadd_with_overflow:
2566        case Intrinsic::smul_with_overflow:
2567        case Intrinsic::ssub_with_overflow:
2568        case Intrinsic::uadd_with_overflow:
2569        case Intrinsic::umul_with_overflow:
2570        case Intrinsic::usub_with_overflow:
2571          return true;
2572        // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2573        // errno like libm sqrt would.
2574        case Intrinsic::sqrt:
2575        case Intrinsic::fma:
2576        case Intrinsic::fmuladd:
2577        case Intrinsic::fabs:
2578          return true;
2579        // TODO: some fp intrinsics are marked as having the same error handling
2580        // as libm. They're safe to speculate when they won't error.
2581        // TODO: are convert_{from,to}_fp16 safe?
2582        // TODO: can we list target-specific intrinsics here?
2583        default: break;
2584      }
2585    }
2586     return false; // The called function could have undefined behavior or
2587                   // side-effects, even if marked readnone nounwind.
2588   }
2589   case Instruction::VAArg:
2590   case Instruction::Alloca:
2591   case Instruction::Invoke:
2592   case Instruction::PHI:
2593   case Instruction::Store:
2594   case Instruction::Ret:
2595   case Instruction::Br:
2596   case Instruction::IndirectBr:
2597   case Instruction::Switch:
2598   case Instruction::Unreachable:
2599   case Instruction::Fence:
2600   case Instruction::LandingPad:
2601   case Instruction::AtomicRMW:
2602   case Instruction::AtomicCmpXchg:
2603   case Instruction::Resume:
2604     return false; // Misc instructions which have effects
2605   }
2606 }
2607
2608 /// isKnownNonNull - Return true if we know that the specified value is never
2609 /// null.
2610 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
2611   // Alloca never returns null, malloc might.
2612   if (isa<AllocaInst>(V)) return true;
2613
2614   // A byval, inalloca, or nonnull argument is never null.
2615   if (const Argument *A = dyn_cast<Argument>(V))
2616     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
2617
2618   // Global values are not null unless extern weak.
2619   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2620     return !GV->hasExternalWeakLinkage();
2621
2622   if (ImmutableCallSite CS = V)
2623     if (CS.isReturnNonNull())
2624       return true;
2625
2626   // operator new never returns null.
2627   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
2628     return true;
2629
2630   return false;
2631 }