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