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