Fix for pr24866
[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/Analysis/LoopInfo.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/GetElementPtrTypeIterator.h"
27 #include "llvm/IR/GlobalAlias.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <cstring>
39 using namespace llvm;
40 using namespace llvm::PatternMatch;
41
42 const unsigned MaxDepth = 6;
43
44 /// Enable an experimental feature to leverage information about dominating
45 /// conditions to compute known bits.  The individual options below control how
46 /// hard we search.  The defaults are chosen to be fairly aggressive.  If you
47 /// run into compile time problems when testing, scale them back and report
48 /// your findings.
49 static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
50                                          cl::Hidden, cl::init(false));
51
52 // This is expensive, so we only do it for the top level query value.
53 // (TODO: evaluate cost vs profit, consider higher thresholds)
54 static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
55                                                cl::Hidden, cl::init(1));
56
57 /// How many dominating blocks should be scanned looking for dominating
58 /// conditions?
59 static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
60                                                    cl::Hidden,
61                                                    cl::init(20000));
62
63 // Controls the number of uses of the value searched for possible
64 // dominating comparisons.
65 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
66                                               cl::Hidden, cl::init(2000));
67
68 // If true, don't consider only compares whose only use is a branch.
69 static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
70                                                cl::Hidden, cl::init(false));
71
72 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
73 /// 0). For vector types, returns the element type's bitwidth.
74 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
75   if (unsigned BitWidth = Ty->getScalarSizeInBits())
76     return BitWidth;
77
78   return DL.getPointerTypeSizeInBits(Ty);
79 }
80
81 // Many of these functions have internal versions that take an assumption
82 // exclusion set. This is because of the potential for mutual recursion to
83 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
84 // classic case of this is assume(x = y), which will attempt to determine
85 // bits in x from bits in y, which will attempt to determine bits in y from
86 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
87 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
88 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
89 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
90
91 namespace {
92 // Simplifying using an assume can only be done in a particular control-flow
93 // context (the context instruction provides that context). If an assume and
94 // the context instruction are not in the same block then the DT helps in
95 // figuring out if we can use it.
96 struct Query {
97   ExclInvsSet ExclInvs;
98   AssumptionCache *AC;
99   const Instruction *CxtI;
100   const DominatorTree *DT;
101
102   Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
103         const DominatorTree *DT = nullptr)
104       : AC(AC), CxtI(CxtI), DT(DT) {}
105
106   Query(const Query &Q, const Value *NewExcl)
107       : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
108     ExclInvs.insert(NewExcl);
109   }
110 };
111 } // end anonymous namespace
112
113 // Given the provided Value and, potentially, a context instruction, return
114 // the preferred context instruction (if any).
115 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
116   // If we've been provided with a context instruction, then use that (provided
117   // it has been inserted).
118   if (CxtI && CxtI->getParent())
119     return CxtI;
120
121   // If the value is really an already-inserted instruction, then use that.
122   CxtI = dyn_cast<Instruction>(V);
123   if (CxtI && CxtI->getParent())
124     return CxtI;
125
126   return nullptr;
127 }
128
129 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
130                              const DataLayout &DL, unsigned Depth,
131                              const Query &Q);
132
133 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
134                             const DataLayout &DL, unsigned Depth,
135                             AssumptionCache *AC, const Instruction *CxtI,
136                             const DominatorTree *DT) {
137   ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
138                      Query(AC, safeCxtI(V, CxtI), DT));
139 }
140
141 bool llvm::haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
142                                AssumptionCache *AC, const Instruction *CxtI,
143                                const DominatorTree *DT) {
144   assert(LHS->getType() == RHS->getType() &&
145          "LHS and RHS should have the same type");
146   assert(LHS->getType()->isIntOrIntVectorTy() &&
147          "LHS and RHS should be integers");
148   IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
149   APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
150   APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
151   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
152   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
153   return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
154 }
155
156 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
157                            const DataLayout &DL, unsigned Depth,
158                            const Query &Q);
159
160 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
161                           const DataLayout &DL, unsigned Depth,
162                           AssumptionCache *AC, const Instruction *CxtI,
163                           const DominatorTree *DT) {
164   ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
165                    Query(AC, safeCxtI(V, CxtI), DT));
166 }
167
168 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
169                                    const Query &Q, const DataLayout &DL);
170
171 bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
172                                   unsigned Depth, AssumptionCache *AC,
173                                   const Instruction *CxtI,
174                                   const DominatorTree *DT) {
175   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
176                                   Query(AC, safeCxtI(V, CxtI), DT), DL);
177 }
178
179 static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
180                            const Query &Q);
181
182 bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
183                           AssumptionCache *AC, const Instruction *CxtI,
184                           const DominatorTree *DT) {
185   return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
186 }
187
188 bool llvm::isKnownNonNegative(Value *V, const DataLayout &DL, unsigned Depth,
189                               AssumptionCache *AC, const Instruction *CxtI,
190                               const DominatorTree *DT) {
191   bool NonNegative, Negative;
192   ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
193   return NonNegative;
194 }
195
196 static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
197                               unsigned Depth, const Query &Q);
198
199 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
200                              unsigned Depth, AssumptionCache *AC,
201                              const Instruction *CxtI, const DominatorTree *DT) {
202   return ::MaskedValueIsZero(V, Mask, DL, Depth,
203                              Query(AC, safeCxtI(V, CxtI), DT));
204 }
205
206 static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
207                                    unsigned Depth, const Query &Q);
208
209 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
210                                   unsigned Depth, AssumptionCache *AC,
211                                   const Instruction *CxtI,
212                                   const DominatorTree *DT) {
213   return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
214 }
215
216 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
217                                    APInt &KnownZero, APInt &KnownOne,
218                                    APInt &KnownZero2, APInt &KnownOne2,
219                                    const DataLayout &DL, unsigned Depth,
220                                    const Query &Q) {
221   if (!Add) {
222     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
223       // We know that the top bits of C-X are clear if X contains less bits
224       // than C (i.e. no wrap-around can happen).  For example, 20-X is
225       // positive if we can prove that X is >= 0 and < 16.
226       if (!CLHS->getValue().isNegative()) {
227         unsigned BitWidth = KnownZero.getBitWidth();
228         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
229         // NLZ can't be BitWidth with no sign bit
230         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
231         computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
232
233         // If all of the MaskV bits are known to be zero, then we know the
234         // output top bits are zero, because we now know that the output is
235         // from [0-C].
236         if ((KnownZero2 & MaskV) == MaskV) {
237           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
238           // Top bits known zero.
239           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
240         }
241       }
242     }
243   }
244
245   unsigned BitWidth = KnownZero.getBitWidth();
246
247   // If an initial sequence of bits in the result is not needed, the
248   // corresponding bits in the operands are not needed.
249   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
250   computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
251   computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
252
253   // Carry in a 1 for a subtract, rather than a 0.
254   APInt CarryIn(BitWidth, 0);
255   if (!Add) {
256     // Sum = LHS + ~RHS + 1
257     std::swap(KnownZero2, KnownOne2);
258     CarryIn.setBit(0);
259   }
260
261   APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
262   APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
263
264   // Compute known bits of the carry.
265   APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
266   APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
267
268   // Compute set of known bits (where all three relevant bits are known).
269   APInt LHSKnown = LHSKnownZero | LHSKnownOne;
270   APInt RHSKnown = KnownZero2 | KnownOne2;
271   APInt CarryKnown = CarryKnownZero | CarryKnownOne;
272   APInt Known = LHSKnown & RHSKnown & CarryKnown;
273
274   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
275          "known bits of sum differ");
276
277   // Compute known bits of the result.
278   KnownZero = ~PossibleSumOne & Known;
279   KnownOne = PossibleSumOne & Known;
280
281   // Are we still trying to solve for the sign bit?
282   if (!Known.isNegative()) {
283     if (NSW) {
284       // Adding two non-negative numbers, or subtracting a negative number from
285       // a non-negative one, can't wrap into negative.
286       if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
287         KnownZero |= APInt::getSignBit(BitWidth);
288       // Adding two negative numbers, or subtracting a non-negative number from
289       // a negative one, can't wrap into non-negative.
290       else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
291         KnownOne |= APInt::getSignBit(BitWidth);
292     }
293   }
294 }
295
296 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
297                                 APInt &KnownZero, APInt &KnownOne,
298                                 APInt &KnownZero2, APInt &KnownOne2,
299                                 const DataLayout &DL, unsigned Depth,
300                                 const Query &Q) {
301   unsigned BitWidth = KnownZero.getBitWidth();
302   computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
303   computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
304
305   bool isKnownNegative = false;
306   bool isKnownNonNegative = false;
307   // If the multiplication is known not to overflow, compute the sign bit.
308   if (NSW) {
309     if (Op0 == Op1) {
310       // The product of a number with itself is non-negative.
311       isKnownNonNegative = true;
312     } else {
313       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
314       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
315       bool isKnownNegativeOp1 = KnownOne.isNegative();
316       bool isKnownNegativeOp0 = KnownOne2.isNegative();
317       // The product of two numbers with the same sign is non-negative.
318       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
319         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
320       // The product of a negative number and a non-negative number is either
321       // negative or zero.
322       if (!isKnownNonNegative)
323         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
324                            isKnownNonZero(Op0, DL, Depth, Q)) ||
325                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
326                            isKnownNonZero(Op1, DL, Depth, Q));
327     }
328   }
329
330   // If low bits are zero in either operand, output low known-0 bits.
331   // Also compute a conservative estimate for high known-0 bits.
332   // More trickiness is possible, but this is sufficient for the
333   // interesting case of alignment computation.
334   KnownOne.clearAllBits();
335   unsigned TrailZ = KnownZero.countTrailingOnes() +
336                     KnownZero2.countTrailingOnes();
337   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
338                              KnownZero2.countLeadingOnes(),
339                              BitWidth) - BitWidth;
340
341   TrailZ = std::min(TrailZ, BitWidth);
342   LeadZ = std::min(LeadZ, BitWidth);
343   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
344               APInt::getHighBitsSet(BitWidth, LeadZ);
345
346   // Only make use of no-wrap flags if we failed to compute the sign bit
347   // directly.  This matters if the multiplication always overflows, in
348   // which case we prefer to follow the result of the direct computation,
349   // though as the program is invoking undefined behaviour we can choose
350   // whatever we like here.
351   if (isKnownNonNegative && !KnownOne.isNegative())
352     KnownZero.setBit(BitWidth - 1);
353   else if (isKnownNegative && !KnownZero.isNegative())
354     KnownOne.setBit(BitWidth - 1);
355 }
356
357 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
358                                              APInt &KnownZero) {
359   unsigned BitWidth = KnownZero.getBitWidth();
360   unsigned NumRanges = Ranges.getNumOperands() / 2;
361   assert(NumRanges >= 1);
362
363   // Use the high end of the ranges to find leading zeros.
364   unsigned MinLeadingZeros = BitWidth;
365   for (unsigned i = 0; i < NumRanges; ++i) {
366     ConstantInt *Lower =
367         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
368     ConstantInt *Upper =
369         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
370     ConstantRange Range(Lower->getValue(), Upper->getValue());
371     if (Range.isWrappedSet())
372       MinLeadingZeros = 0; // -1 has no zeros
373     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
374     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
375   }
376
377   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
378 }
379
380 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
381   SmallVector<const Value *, 16> WorkSet(1, I);
382   SmallPtrSet<const Value *, 32> Visited;
383   SmallPtrSet<const Value *, 16> EphValues;
384
385   while (!WorkSet.empty()) {
386     const Value *V = WorkSet.pop_back_val();
387     if (!Visited.insert(V).second)
388       continue;
389
390     // If all uses of this value are ephemeral, then so is this value.
391     bool FoundNEUse = false;
392     for (const User *I : V->users())
393       if (!EphValues.count(I)) {
394         FoundNEUse = true;
395         break;
396       }
397
398     if (!FoundNEUse) {
399       if (V == E)
400         return true;
401
402       EphValues.insert(V);
403       if (const User *U = dyn_cast<User>(V))
404         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
405              J != JE; ++J) {
406           if (isSafeToSpeculativelyExecute(*J))
407             WorkSet.push_back(*J);
408         }
409     }
410   }
411
412   return false;
413 }
414
415 // Is this an intrinsic that cannot be speculated but also cannot trap?
416 static bool isAssumeLikeIntrinsic(const Instruction *I) {
417   if (const CallInst *CI = dyn_cast<CallInst>(I))
418     if (Function *F = CI->getCalledFunction())
419       switch (F->getIntrinsicID()) {
420       default: break;
421       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
422       case Intrinsic::assume:
423       case Intrinsic::dbg_declare:
424       case Intrinsic::dbg_value:
425       case Intrinsic::invariant_start:
426       case Intrinsic::invariant_end:
427       case Intrinsic::lifetime_start:
428       case Intrinsic::lifetime_end:
429       case Intrinsic::objectsize:
430       case Intrinsic::ptr_annotation:
431       case Intrinsic::var_annotation:
432         return true;
433       }
434
435   return false;
436 }
437
438 static bool isValidAssumeForContext(Value *V, const Query &Q) {
439   Instruction *Inv = cast<Instruction>(V);
440
441   // There are two restrictions on the use of an assume:
442   //  1. The assume must dominate the context (or the control flow must
443   //     reach the assume whenever it reaches the context).
444   //  2. The context must not be in the assume's set of ephemeral values
445   //     (otherwise we will use the assume to prove that the condition
446   //     feeding the assume is trivially true, thus causing the removal of
447   //     the assume).
448
449   if (Q.DT) {
450     if (Q.DT->dominates(Inv, Q.CxtI)) {
451       return true;
452     } else if (Inv->getParent() == Q.CxtI->getParent()) {
453       // The context comes first, but they're both in the same block. Make sure
454       // there is nothing in between that might interrupt the control flow.
455       for (BasicBlock::const_iterator I =
456              std::next(BasicBlock::const_iterator(Q.CxtI)),
457                                       IE(Inv); I != IE; ++I)
458         if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
459           return false;
460
461       return !isEphemeralValueOf(Inv, Q.CxtI);
462     }
463
464     return false;
465   }
466
467   // When we don't have a DT, we do a limited search...
468   if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
469     return true;
470   } else if (Inv->getParent() == Q.CxtI->getParent()) {
471     // Search forward from the assume until we reach the context (or the end
472     // of the block); the common case is that the assume will come first.
473     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
474          IE = Inv->getParent()->end(); I != IE; ++I)
475       if (I == Q.CxtI)
476         return true;
477
478     // The context must come first...
479     for (BasicBlock::const_iterator I =
480            std::next(BasicBlock::const_iterator(Q.CxtI)),
481                                     IE(Inv); I != IE; ++I)
482       if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
483         return false;
484
485     return !isEphemeralValueOf(Inv, Q.CxtI);
486   }
487
488   return false;
489 }
490
491 bool llvm::isValidAssumeForContext(const Instruction *I,
492                                    const Instruction *CxtI,
493                                    const DominatorTree *DT) {
494   return ::isValidAssumeForContext(const_cast<Instruction *>(I),
495                                    Query(nullptr, CxtI, DT));
496 }
497
498 template<typename LHS, typename RHS>
499 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
500                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
501 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
502   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
503 }
504
505 template<typename LHS, typename RHS>
506 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
507                         BinaryOp_match<RHS, LHS, Instruction::And>>
508 m_c_And(const LHS &L, const RHS &R) {
509   return m_CombineOr(m_And(L, R), m_And(R, L));
510 }
511
512 template<typename LHS, typename RHS>
513 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
514                         BinaryOp_match<RHS, LHS, Instruction::Or>>
515 m_c_Or(const LHS &L, const RHS &R) {
516   return m_CombineOr(m_Or(L, R), m_Or(R, L));
517 }
518
519 template<typename LHS, typename RHS>
520 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
521                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
522 m_c_Xor(const LHS &L, const RHS &R) {
523   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
524 }
525
526 /// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
527 /// true (at the context instruction.)  This is mostly a utility function for
528 /// the prototype dominating conditions reasoning below.
529 static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
530                                               APInt &KnownZero,
531                                               APInt &KnownOne,
532                                               const DataLayout &DL,
533                                               unsigned Depth, const Query &Q) {
534   Value *LHS = Cmp->getOperand(0);
535   Value *RHS = Cmp->getOperand(1);
536   // TODO: We could potentially be more aggressive here.  This would be worth
537   // evaluating.  If we can, explore commoning this code with the assume
538   // handling logic.
539   if (LHS != V && RHS != V)
540     return;
541
542   const unsigned BitWidth = KnownZero.getBitWidth();
543
544   switch (Cmp->getPredicate()) {
545   default:
546     // We know nothing from this condition
547     break;
548   // TODO: implement unsigned bound from below (known one bits)
549   // TODO: common condition check implementations with assumes
550   // TODO: implement other patterns from assume (e.g. V & B == A)
551   case ICmpInst::ICMP_SGT:
552     if (LHS == V) {
553       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
554       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
555       if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
556         // We know that the sign bit is zero.
557         KnownZero |= APInt::getSignBit(BitWidth);
558       }
559     }
560     break;
561   case ICmpInst::ICMP_EQ:
562     {
563       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
564       if (LHS == V)
565         computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
566       else if (RHS == V)
567         computeKnownBits(LHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
568       else
569         llvm_unreachable("missing use?");
570       KnownZero |= KnownZeroTemp;
571       KnownOne |= KnownOneTemp;
572     }
573     break;
574   case ICmpInst::ICMP_ULE:
575     if (LHS == V) {
576       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
577       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
578       // The known zero bits carry over
579       unsigned SignBits = KnownZeroTemp.countLeadingOnes();
580       KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
581     }
582     break;
583   case ICmpInst::ICMP_ULT:
584     if (LHS == V) {
585       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
586       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
587       // Whatever high bits in rhs are zero are known to be zero (if rhs is a
588       // power of 2, then one more).
589       unsigned SignBits = KnownZeroTemp.countLeadingOnes();
590       if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp), DL))
591         SignBits++;
592       KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
593     }
594     break;
595   };
596 }
597
598 /// Compute known bits in 'V' from conditions which are known to be true along
599 /// all paths leading to the context instruction.  In particular, look for
600 /// cases where one branch of an interesting condition dominates the context
601 /// instruction.  This does not do general dataflow.
602 /// NOTE: This code is EXPERIMENTAL and currently off by default.
603 static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
604                                                     APInt &KnownOne,
605                                                     const DataLayout &DL,
606                                                     unsigned Depth,
607                                                     const Query &Q) {
608   // Need both the dominator tree and the query location to do anything useful
609   if (!Q.DT || !Q.CxtI)
610     return;
611   Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
612   // The context instruction might be in a statically unreachable block.  If
613   // so, asking dominator queries may yield suprising results.  (e.g. the block
614   // may not have a dom tree node)
615   if (!Q.DT->isReachableFromEntry(Cxt->getParent()))
616     return;
617
618   // Avoid useless work
619   if (auto VI = dyn_cast<Instruction>(V))
620     if (VI->getParent() == Cxt->getParent())
621       return;
622
623   // Note: We currently implement two options.  It's not clear which of these
624   // will survive long term, we need data for that.
625   // Option 1 - Try walking the dominator tree looking for conditions which
626   // might apply.  This works well for local conditions (loop guards, etc..),
627   // but not as well for things far from the context instruction (presuming a
628   // low max blocks explored).  If we can set an high enough limit, this would
629   // be all we need.
630   // Option 2 - We restrict out search to those conditions which are uses of
631   // the value we're interested in.  This is independent of dom structure,
632   // but is slightly less powerful without looking through lots of use chains.
633   // It does handle conditions far from the context instruction (e.g. early
634   // function exits on entry) really well though.
635
636   // Option 1 - Search the dom tree
637   unsigned NumBlocksExplored = 0;
638   BasicBlock *Current = Cxt->getParent();
639   while (true) {
640     // Stop searching if we've gone too far up the chain
641     if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
642       break;
643     NumBlocksExplored++;
644
645     if (!Q.DT->getNode(Current)->getIDom())
646       break;
647     Current = Q.DT->getNode(Current)->getIDom()->getBlock();
648     if (!Current)
649       // found function entry
650       break;
651
652     BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
653     if (!BI || BI->isUnconditional())
654       continue;
655     ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
656     if (!Cmp)
657       continue;
658
659     // We're looking for conditions that are guaranteed to hold at the context
660     // instruction.  Finding a condition where one path dominates the context
661     // isn't enough because both the true and false cases could merge before
662     // the context instruction we're actually interested in.  Instead, we need
663     // to ensure that the taken *edge* dominates the context instruction.  We
664     // know that the edge must be reachable since we started from a reachable
665     // block.
666     BasicBlock *BB0 = BI->getSuccessor(0);
667     BasicBlockEdge Edge(BI->getParent(), BB0);
668     if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
669       continue;
670
671     computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
672                                       Q);
673   }
674
675   // Option 2 - Search the other uses of V
676   unsigned NumUsesExplored = 0;
677   for (auto U : V->users()) {
678     // Avoid massive lists
679     if (NumUsesExplored >= DomConditionsMaxUses)
680       break;
681     NumUsesExplored++;
682     // Consider only compare instructions uniquely controlling a branch
683     ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
684     if (!Cmp)
685       continue;
686
687     if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
688       continue;
689
690     for (auto *CmpU : Cmp->users()) {
691       BranchInst *BI = dyn_cast<BranchInst>(CmpU);
692       if (!BI || BI->isUnconditional())
693         continue;
694       // We're looking for conditions that are guaranteed to hold at the
695       // context instruction.  Finding a condition where one path dominates
696       // the context isn't enough because both the true and false cases could
697       // merge before the context instruction we're actually interested in.
698       // Instead, we need to ensure that the taken *edge* dominates the context
699       // instruction. 
700       BasicBlock *BB0 = BI->getSuccessor(0);
701       BasicBlockEdge Edge(BI->getParent(), BB0);
702       if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
703         continue;
704
705       computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
706                                         Q);
707     }
708   }
709 }
710
711 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
712                                        APInt &KnownOne, const DataLayout &DL,
713                                        unsigned Depth, const Query &Q) {
714   // Use of assumptions is context-sensitive. If we don't have a context, we
715   // cannot use them!
716   if (!Q.AC || !Q.CxtI)
717     return;
718
719   unsigned BitWidth = KnownZero.getBitWidth();
720
721   for (auto &AssumeVH : Q.AC->assumptions()) {
722     if (!AssumeVH)
723       continue;
724     CallInst *I = cast<CallInst>(AssumeVH);
725     assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
726            "Got assumption for the wrong function!");
727     if (Q.ExclInvs.count(I))
728       continue;
729
730     // Warning: This loop can end up being somewhat performance sensetive.
731     // We're running this loop for once for each value queried resulting in a
732     // runtime of ~O(#assumes * #values).
733
734     assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
735            "must be an assume intrinsic");
736
737     Value *Arg = I->getArgOperand(0);
738
739     if (Arg == V && isValidAssumeForContext(I, Q)) {
740       assert(BitWidth == 1 && "assume operand is not i1?");
741       KnownZero.clearAllBits();
742       KnownOne.setAllBits();
743       return;
744     }
745
746     // The remaining tests are all recursive, so bail out if we hit the limit.
747     if (Depth == MaxDepth)
748       continue;
749
750     Value *A, *B;
751     auto m_V = m_CombineOr(m_Specific(V),
752                            m_CombineOr(m_PtrToInt(m_Specific(V)),
753                            m_BitCast(m_Specific(V))));
754
755     CmpInst::Predicate Pred;
756     ConstantInt *C;
757     // assume(v = a)
758     if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
759         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
760       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
761       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
762       KnownZero |= RHSKnownZero;
763       KnownOne  |= RHSKnownOne;
764     // assume(v & b = a)
765     } else if (match(Arg,
766                      m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
767                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
768       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
769       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
770       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
771       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
772
773       // For those bits in the mask that are known to be one, we can propagate
774       // known bits from the RHS to V.
775       KnownZero |= RHSKnownZero & MaskKnownOne;
776       KnownOne  |= RHSKnownOne  & MaskKnownOne;
777     // assume(~(v & b) = a)
778     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
779                                    m_Value(A))) &&
780                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
781       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
782       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
783       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
784       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
785
786       // For those bits in the mask that are known to be one, we can propagate
787       // inverted known bits from the RHS to V.
788       KnownZero |= RHSKnownOne  & MaskKnownOne;
789       KnownOne  |= RHSKnownZero & MaskKnownOne;
790     // assume(v | b = a)
791     } else if (match(Arg,
792                      m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
793                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
794       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
795       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
796       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
797       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
798
799       // For those bits in B that are known to be zero, we can propagate known
800       // bits from the RHS to V.
801       KnownZero |= RHSKnownZero & BKnownZero;
802       KnownOne  |= RHSKnownOne  & BKnownZero;
803     // assume(~(v | b) = a)
804     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
805                                    m_Value(A))) &&
806                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
807       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
808       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
809       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
810       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
811
812       // For those bits in B that are known to be zero, we can propagate
813       // inverted known bits from the RHS to V.
814       KnownZero |= RHSKnownOne  & BKnownZero;
815       KnownOne  |= RHSKnownZero & BKnownZero;
816     // assume(v ^ b = a)
817     } else if (match(Arg,
818                      m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
819                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
820       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
821       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
822       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
823       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
824
825       // For those bits in B that are known to be zero, we can propagate known
826       // bits from the RHS to V. For those bits in B that are known to be one,
827       // we can propagate inverted known bits from the RHS to V.
828       KnownZero |= RHSKnownZero & BKnownZero;
829       KnownOne  |= RHSKnownOne  & BKnownZero;
830       KnownZero |= RHSKnownOne  & BKnownOne;
831       KnownOne  |= RHSKnownZero & BKnownOne;
832     // assume(~(v ^ b) = a)
833     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
834                                    m_Value(A))) &&
835                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
836       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
837       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
838       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
839       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
840
841       // For those bits in B that are known to be zero, we can propagate
842       // inverted known bits from the RHS to V. For those bits in B that are
843       // known to be one, we can propagate known bits from the RHS to V.
844       KnownZero |= RHSKnownOne  & BKnownZero;
845       KnownOne  |= RHSKnownZero & BKnownZero;
846       KnownZero |= RHSKnownZero & BKnownOne;
847       KnownOne  |= RHSKnownOne  & BKnownOne;
848     // assume(v << c = a)
849     } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
850                                    m_Value(A))) &&
851                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
852       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
853       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
854       // For those bits in RHS that are known, we can propagate them to known
855       // bits in V shifted to the right by C.
856       KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
857       KnownOne  |= RHSKnownOne.lshr(C->getZExtValue());
858     // assume(~(v << c) = a)
859     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
860                                    m_Value(A))) &&
861                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
862       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
863       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
864       // For those bits in RHS that are known, we can propagate them inverted
865       // to known bits in V shifted to the right by C.
866       KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
867       KnownOne  |= RHSKnownZero.lshr(C->getZExtValue());
868     // assume(v >> c = a)
869     } else if (match(Arg,
870                      m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
871                                                 m_AShr(m_V, m_ConstantInt(C))),
872                               m_Value(A))) &&
873                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
874       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
875       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
876       // For those bits in RHS that are known, we can propagate them to known
877       // bits in V shifted to the right by C.
878       KnownZero |= RHSKnownZero << C->getZExtValue();
879       KnownOne  |= RHSKnownOne  << C->getZExtValue();
880     // assume(~(v >> c) = a)
881     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
882                                              m_LShr(m_V, m_ConstantInt(C)),
883                                              m_AShr(m_V, m_ConstantInt(C)))),
884                                    m_Value(A))) &&
885                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
886       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
887       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
888       // For those bits in RHS that are known, we can propagate them inverted
889       // to known bits in V shifted to the right by C.
890       KnownZero |= RHSKnownOne  << C->getZExtValue();
891       KnownOne  |= RHSKnownZero << C->getZExtValue();
892     // assume(v >=_s c) where c is non-negative
893     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
894                Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
895       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
896       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
897
898       if (RHSKnownZero.isNegative()) {
899         // We know that the sign bit is zero.
900         KnownZero |= APInt::getSignBit(BitWidth);
901       }
902     // assume(v >_s c) where c is at least -1.
903     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
904                Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
905       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
906       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
907
908       if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
909         // We know that the sign bit is zero.
910         KnownZero |= APInt::getSignBit(BitWidth);
911       }
912     // assume(v <=_s c) where c is negative
913     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
914                Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
915       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
916       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
917
918       if (RHSKnownOne.isNegative()) {
919         // We know that the sign bit is one.
920         KnownOne |= APInt::getSignBit(BitWidth);
921       }
922     // assume(v <_s c) where c is non-positive
923     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
924                Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
925       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
926       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
927
928       if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
929         // We know that the sign bit is one.
930         KnownOne |= APInt::getSignBit(BitWidth);
931       }
932     // assume(v <=_u c)
933     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
934                Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
935       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
936       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
937
938       // Whatever high bits in c are zero are known to be zero.
939       KnownZero |=
940         APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
941     // assume(v <_u c)
942     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
943                Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
944       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
945       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
946
947       // Whatever high bits in c are zero are known to be zero (if c is a power
948       // of 2, then one more).
949       if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
950         KnownZero |=
951           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
952       else
953         KnownZero |=
954           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
955     }
956   }
957 }
958
959 static void computeKnownBitsFromOperator(Operator *I, APInt &KnownZero,
960                                          APInt &KnownOne, const DataLayout &DL,
961                                          unsigned Depth, const Query &Q) {
962   unsigned BitWidth = KnownZero.getBitWidth();
963
964   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
965   switch (I->getOpcode()) {
966   default: break;
967   case Instruction::Load:
968     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
969       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
970     break;
971   case Instruction::And: {
972     // If either the LHS or the RHS are Zero, the result is zero.
973     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
974     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
975
976     // Output known-1 bits are only known if set in both the LHS & RHS.
977     KnownOne &= KnownOne2;
978     // Output known-0 are known to be clear if zero in either the LHS | RHS.
979     KnownZero |= KnownZero2;
980     break;
981   }
982   case Instruction::Or: {
983     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
984     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
985
986     // Output known-0 bits are only known if clear in both the LHS & RHS.
987     KnownZero &= KnownZero2;
988     // Output known-1 are known to be set if set in either the LHS | RHS.
989     KnownOne |= KnownOne2;
990     break;
991   }
992   case Instruction::Xor: {
993     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
994     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
995
996     // Output known-0 bits are known if clear or set in both the LHS & RHS.
997     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
998     // Output known-1 are known to be set if set in only one of the LHS, RHS.
999     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1000     KnownZero = KnownZeroOut;
1001     break;
1002   }
1003   case Instruction::Mul: {
1004     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1005     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
1006                         KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1007     break;
1008   }
1009   case Instruction::UDiv: {
1010     // For the purposes of computing leading zeros we can conservatively
1011     // treat a udiv as a logical right shift by the power of 2 known to
1012     // be less than the denominator.
1013     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1014     unsigned LeadZ = KnownZero2.countLeadingOnes();
1015
1016     KnownOne2.clearAllBits();
1017     KnownZero2.clearAllBits();
1018     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1019     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1020     if (RHSUnknownLeadingOnes != BitWidth)
1021       LeadZ = std::min(BitWidth,
1022                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1023
1024     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1025     break;
1026   }
1027   case Instruction::Select:
1028     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
1029     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1030
1031     // Only known if known in both the LHS and RHS.
1032     KnownOne &= KnownOne2;
1033     KnownZero &= KnownZero2;
1034     break;
1035   case Instruction::FPTrunc:
1036   case Instruction::FPExt:
1037   case Instruction::FPToUI:
1038   case Instruction::FPToSI:
1039   case Instruction::SIToFP:
1040   case Instruction::UIToFP:
1041     break; // Can't work with floating point.
1042   case Instruction::PtrToInt:
1043   case Instruction::IntToPtr:
1044   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
1045     // FALL THROUGH and handle them the same as zext/trunc.
1046   case Instruction::ZExt:
1047   case Instruction::Trunc: {
1048     Type *SrcTy = I->getOperand(0)->getType();
1049
1050     unsigned SrcBitWidth;
1051     // Note that we handle pointer operands here because of inttoptr/ptrtoint
1052     // which fall through here.
1053     SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
1054
1055     assert(SrcBitWidth && "SrcBitWidth can't be zero");
1056     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1057     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
1058     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1059     KnownZero = KnownZero.zextOrTrunc(BitWidth);
1060     KnownOne = KnownOne.zextOrTrunc(BitWidth);
1061     // Any top bits are known to be zero.
1062     if (BitWidth > SrcBitWidth)
1063       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1064     break;
1065   }
1066   case Instruction::BitCast: {
1067     Type *SrcTy = I->getOperand(0)->getType();
1068     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
1069         // TODO: For now, not handling conversions like:
1070         // (bitcast i64 %x to <2 x i32>)
1071         !I->getType()->isVectorTy()) {
1072       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1073       break;
1074     }
1075     break;
1076   }
1077   case Instruction::SExt: {
1078     // Compute the bits in the result that are not present in the input.
1079     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1080
1081     KnownZero = KnownZero.trunc(SrcBitWidth);
1082     KnownOne = KnownOne.trunc(SrcBitWidth);
1083     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1084     KnownZero = KnownZero.zext(BitWidth);
1085     KnownOne = KnownOne.zext(BitWidth);
1086
1087     // If the sign bit of the input is known set or clear, then we know the
1088     // top bits of the result.
1089     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
1090       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1091     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
1092       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1093     break;
1094   }
1095   case Instruction::Shl:
1096     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1097     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1098       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1099       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1100       KnownZero <<= ShiftAmt;
1101       KnownOne  <<= ShiftAmt;
1102       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
1103     }
1104     break;
1105   case Instruction::LShr:
1106     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1107     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1108       // Compute the new bits that are at the top now.
1109       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1110
1111       // Unsigned shift right.
1112       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1113       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1114       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
1115       // high bits known zero.
1116       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
1117     }
1118     break;
1119   case Instruction::AShr:
1120     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1121     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1122       // Compute the new bits that are at the top now.
1123       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
1124
1125       // Signed shift right.
1126       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1127       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1128       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
1129
1130       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1131       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
1132         KnownZero |= HighBits;
1133       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
1134         KnownOne |= HighBits;
1135     }
1136     break;
1137   case Instruction::Sub: {
1138     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1139     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1140                            KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1141                            Depth, Q);
1142     break;
1143   }
1144   case Instruction::Add: {
1145     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1146     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1147                            KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1148                            Depth, Q);
1149     break;
1150   }
1151   case Instruction::SRem:
1152     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1153       APInt RA = Rem->getValue().abs();
1154       if (RA.isPowerOf2()) {
1155         APInt LowBits = RA - 1;
1156         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
1157                          Q);
1158
1159         // The low bits of the first operand are unchanged by the srem.
1160         KnownZero = KnownZero2 & LowBits;
1161         KnownOne = KnownOne2 & LowBits;
1162
1163         // If the first operand is non-negative or has all low bits zero, then
1164         // the upper bits are all zero.
1165         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1166           KnownZero |= ~LowBits;
1167
1168         // If the first operand is negative and not all low bits are zero, then
1169         // the upper bits are all one.
1170         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1171           KnownOne |= ~LowBits;
1172
1173         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1174       }
1175     }
1176
1177     // The sign bit is the LHS's sign bit, except when the result of the
1178     // remainder is zero.
1179     if (KnownZero.isNonNegative()) {
1180       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1181       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
1182                        Depth + 1, Q);
1183       // If it's known zero, our sign bit is also zero.
1184       if (LHSKnownZero.isNegative())
1185         KnownZero.setBit(BitWidth - 1);
1186     }
1187
1188     break;
1189   case Instruction::URem: {
1190     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1191       APInt RA = Rem->getValue();
1192       if (RA.isPowerOf2()) {
1193         APInt LowBits = (RA - 1);
1194         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1195                          Q);
1196         KnownZero |= ~LowBits;
1197         KnownOne &= LowBits;
1198         break;
1199       }
1200     }
1201
1202     // Since the result is less than or equal to either operand, any leading
1203     // zero bits in either operand must also exist in the result.
1204     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1205     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1206
1207     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1208                                 KnownZero2.countLeadingOnes());
1209     KnownOne.clearAllBits();
1210     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1211     break;
1212   }
1213
1214   case Instruction::Alloca: {
1215     AllocaInst *AI = cast<AllocaInst>(I);
1216     unsigned Align = AI->getAlignment();
1217     if (Align == 0)
1218       Align = DL.getABITypeAlignment(AI->getType()->getElementType());
1219
1220     if (Align > 0)
1221       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1222     break;
1223   }
1224   case Instruction::GetElementPtr: {
1225     // Analyze all of the subscripts of this getelementptr instruction
1226     // to determine if we can prove known low zero bits.
1227     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1228     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
1229                      Depth + 1, Q);
1230     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1231
1232     gep_type_iterator GTI = gep_type_begin(I);
1233     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1234       Value *Index = I->getOperand(i);
1235       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1236         // Handle struct member offset arithmetic.
1237
1238         // Handle case when index is vector zeroinitializer
1239         Constant *CIndex = cast<Constant>(Index);
1240         if (CIndex->isZeroValue())
1241           continue;
1242
1243         if (CIndex->getType()->isVectorTy())
1244           Index = CIndex->getSplatValue();
1245
1246         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1247         const StructLayout *SL = DL.getStructLayout(STy);
1248         uint64_t Offset = SL->getElementOffset(Idx);
1249         TrailZ = std::min<unsigned>(TrailZ,
1250                                     countTrailingZeros(Offset));
1251       } else {
1252         // Handle array index arithmetic.
1253         Type *IndexedTy = GTI.getIndexedType();
1254         if (!IndexedTy->isSized()) {
1255           TrailZ = 0;
1256           break;
1257         }
1258         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1259         uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
1260         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1261         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
1262                          Q);
1263         TrailZ = std::min(TrailZ,
1264                           unsigned(countTrailingZeros(TypeSize) +
1265                                    LocalKnownZero.countTrailingOnes()));
1266       }
1267     }
1268
1269     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1270     break;
1271   }
1272   case Instruction::PHI: {
1273     PHINode *P = cast<PHINode>(I);
1274     // Handle the case of a simple two-predecessor recurrence PHI.
1275     // There's a lot more that could theoretically be done here, but
1276     // this is sufficient to catch some interesting cases.
1277     if (P->getNumIncomingValues() == 2) {
1278       for (unsigned i = 0; i != 2; ++i) {
1279         Value *L = P->getIncomingValue(i);
1280         Value *R = P->getIncomingValue(!i);
1281         Operator *LU = dyn_cast<Operator>(L);
1282         if (!LU)
1283           continue;
1284         unsigned Opcode = LU->getOpcode();
1285         // Check for operations that have the property that if
1286         // both their operands have low zero bits, the result
1287         // will have low zero bits.
1288         if (Opcode == Instruction::Add ||
1289             Opcode == Instruction::Sub ||
1290             Opcode == Instruction::And ||
1291             Opcode == Instruction::Or ||
1292             Opcode == Instruction::Mul) {
1293           Value *LL = LU->getOperand(0);
1294           Value *LR = LU->getOperand(1);
1295           // Find a recurrence.
1296           if (LL == I)
1297             L = LR;
1298           else if (LR == I)
1299             L = LL;
1300           else
1301             break;
1302           // Ok, we have a PHI of the form L op= R. Check for low
1303           // zero bits.
1304           computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
1305
1306           // We need to take the minimum number of known bits
1307           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1308           computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
1309
1310           KnownZero = APInt::getLowBitsSet(BitWidth,
1311                                            std::min(KnownZero2.countTrailingOnes(),
1312                                                     KnownZero3.countTrailingOnes()));
1313           break;
1314         }
1315       }
1316     }
1317
1318     // Unreachable blocks may have zero-operand PHI nodes.
1319     if (P->getNumIncomingValues() == 0)
1320       break;
1321
1322     // Otherwise take the unions of the known bit sets of the operands,
1323     // taking conservative care to avoid excessive recursion.
1324     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1325       // Skip if every incoming value references to ourself.
1326       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1327         break;
1328
1329       KnownZero = APInt::getAllOnesValue(BitWidth);
1330       KnownOne = APInt::getAllOnesValue(BitWidth);
1331       for (Value *IncValue : P->incoming_values()) {
1332         // Skip direct self references.
1333         if (IncValue == P) continue;
1334
1335         KnownZero2 = APInt(BitWidth, 0);
1336         KnownOne2 = APInt(BitWidth, 0);
1337         // Recurse, but cap the recursion to one level, because we don't
1338         // want to waste time spinning around in loops.
1339         computeKnownBits(IncValue, KnownZero2, KnownOne2, DL,
1340                          MaxDepth - 1, Q);
1341         KnownZero &= KnownZero2;
1342         KnownOne &= KnownOne2;
1343         // If all bits have been ruled out, there's no need to check
1344         // more operands.
1345         if (!KnownZero && !KnownOne)
1346           break;
1347       }
1348     }
1349     break;
1350   }
1351   case Instruction::Call:
1352   case Instruction::Invoke:
1353     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1354       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1355     // If a range metadata is attached to this IntrinsicInst, intersect the
1356     // explicit range specified by the metadata and the implicit range of
1357     // the intrinsic.
1358     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1359       switch (II->getIntrinsicID()) {
1360       default: break;
1361       case Intrinsic::ctlz:
1362       case Intrinsic::cttz: {
1363         unsigned LowBits = Log2_32(BitWidth)+1;
1364         // If this call is undefined for 0, the result will be less than 2^n.
1365         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1366           LowBits -= 1;
1367         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1368         break;
1369       }
1370       case Intrinsic::ctpop: {
1371         unsigned LowBits = Log2_32(BitWidth)+1;
1372         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1373         break;
1374       }
1375       case Intrinsic::x86_sse42_crc32_64_64:
1376         KnownZero |= APInt::getHighBitsSet(64, 32);
1377         break;
1378       }
1379     }
1380     break;
1381   case Instruction::ExtractValue:
1382     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1383       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1384       if (EVI->getNumIndices() != 1) break;
1385       if (EVI->getIndices()[0] == 0) {
1386         switch (II->getIntrinsicID()) {
1387         default: break;
1388         case Intrinsic::uadd_with_overflow:
1389         case Intrinsic::sadd_with_overflow:
1390           computeKnownBitsAddSub(true, II->getArgOperand(0),
1391                                  II->getArgOperand(1), false, KnownZero,
1392                                  KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1393           break;
1394         case Intrinsic::usub_with_overflow:
1395         case Intrinsic::ssub_with_overflow:
1396           computeKnownBitsAddSub(false, II->getArgOperand(0),
1397                                  II->getArgOperand(1), false, KnownZero,
1398                                  KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1399           break;
1400         case Intrinsic::umul_with_overflow:
1401         case Intrinsic::smul_with_overflow:
1402           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1403                               KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1404                               Depth, Q);
1405           break;
1406         }
1407       }
1408     }
1409   }
1410 }
1411
1412 /// Determine which bits of V are known to be either zero or one and return
1413 /// them in the KnownZero/KnownOne bit sets.
1414 ///
1415 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
1416 /// we cannot optimize based on the assumption that it is zero without changing
1417 /// it to be an explicit zero.  If we don't change it to zero, other code could
1418 /// optimized based on the contradictory assumption that it is non-zero.
1419 /// Because instcombine aggressively folds operations with undef args anyway,
1420 /// this won't lose us code quality.
1421 ///
1422 /// This function is defined on values with integer type, values with pointer
1423 /// type, and vectors of integers.  In the case
1424 /// where V is a vector, known zero, and known one values are the
1425 /// same width as the vector element, and the bit is set only if it is true
1426 /// for all of the elements in the vector.
1427 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
1428                       const DataLayout &DL, unsigned Depth, const Query &Q) {
1429   assert(V && "No Value?");
1430   assert(Depth <= MaxDepth && "Limit Search Depth");
1431   unsigned BitWidth = KnownZero.getBitWidth();
1432
1433   assert((V->getType()->isIntOrIntVectorTy() ||
1434           V->getType()->getScalarType()->isPointerTy()) &&
1435          "Not integer or pointer type!");
1436   assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
1437          (!V->getType()->isIntOrIntVectorTy() ||
1438           V->getType()->getScalarSizeInBits() == BitWidth) &&
1439          KnownZero.getBitWidth() == BitWidth &&
1440          KnownOne.getBitWidth() == BitWidth &&
1441          "V, KnownOne and KnownZero should have same BitWidth");
1442
1443   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1444     // We know all of the bits for a constant!
1445     KnownOne = CI->getValue();
1446     KnownZero = ~KnownOne;
1447     return;
1448   }
1449   // Null and aggregate-zero are all-zeros.
1450   if (isa<ConstantPointerNull>(V) ||
1451       isa<ConstantAggregateZero>(V)) {
1452     KnownOne.clearAllBits();
1453     KnownZero = APInt::getAllOnesValue(BitWidth);
1454     return;
1455   }
1456   // Handle a constant vector by taking the intersection of the known bits of
1457   // each element.  There is no real need to handle ConstantVector here, because
1458   // we don't handle undef in any particularly useful way.
1459   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1460     // We know that CDS must be a vector of integers. Take the intersection of
1461     // each element.
1462     KnownZero.setAllBits(); KnownOne.setAllBits();
1463     APInt Elt(KnownZero.getBitWidth(), 0);
1464     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1465       Elt = CDS->getElementAsInteger(i);
1466       KnownZero &= ~Elt;
1467       KnownOne &= Elt;
1468     }
1469     return;
1470   }
1471
1472   // The address of an aligned GlobalValue has trailing zeros.
1473   if (auto *GO = dyn_cast<GlobalObject>(V)) {
1474     unsigned Align = GO->getAlignment();
1475     if (Align == 0) {
1476       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
1477         Type *ObjectType = GVar->getType()->getElementType();
1478         if (ObjectType->isSized()) {
1479           // If the object is defined in the current Module, we'll be giving
1480           // it the preferred alignment. Otherwise, we have to assume that it
1481           // may only have the minimum ABI alignment.
1482           if (GVar->isStrongDefinitionForLinker())
1483             Align = DL.getPreferredAlignment(GVar);
1484           else
1485             Align = DL.getABITypeAlignment(ObjectType);
1486         }
1487       }
1488     }
1489     if (Align > 0)
1490       KnownZero = APInt::getLowBitsSet(BitWidth,
1491                                        countTrailingZeros(Align));
1492     else
1493       KnownZero.clearAllBits();
1494     KnownOne.clearAllBits();
1495     return;
1496   }
1497
1498   if (Argument *A = dyn_cast<Argument>(V)) {
1499     unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
1500
1501     if (!Align && A->hasStructRetAttr()) {
1502       // An sret parameter has at least the ABI alignment of the return type.
1503       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
1504       if (EltTy->isSized())
1505         Align = DL.getABITypeAlignment(EltTy);
1506     }
1507
1508     if (Align)
1509       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1510     else
1511       KnownZero.clearAllBits();
1512     KnownOne.clearAllBits();
1513
1514     // Don't give up yet... there might be an assumption that provides more
1515     // information...
1516     computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
1517
1518     // Or a dominating condition for that matter
1519     if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1520       computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL,
1521                                               Depth, Q);
1522     return;
1523   }
1524
1525   // Start out not knowing anything.
1526   KnownZero.clearAllBits(); KnownOne.clearAllBits();
1527
1528   // Limit search depth.
1529   // All recursive calls that increase depth must come after this.
1530   if (Depth == MaxDepth)
1531     return;
1532
1533   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1534   // the bits of its aliasee.
1535   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1536     if (!GA->mayBeOverridden())
1537       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
1538     return;
1539   }
1540
1541   if (Operator *I = dyn_cast<Operator>(V))
1542     computeKnownBitsFromOperator(I, KnownZero, KnownOne, DL, Depth, Q);
1543   // computeKnownBitsFromAssume and computeKnownBitsFromDominatingCondition
1544   // strictly refines KnownZero and KnownOne. Therefore, we run them after
1545   // computeKnownBitsFromOperator.
1546
1547   // Check whether a nearby assume intrinsic can determine some known bits.
1548   computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
1549
1550   // Check whether there's a dominating condition which implies something about
1551   // this value at the given context.
1552   if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1553     computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL, Depth,
1554                                             Q);
1555
1556   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1557 }
1558
1559 /// Determine whether the sign bit is known to be zero or one.
1560 /// Convenience wrapper around computeKnownBits.
1561 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1562                     const DataLayout &DL, unsigned Depth, const Query &Q) {
1563   unsigned BitWidth = getBitWidth(V->getType(), DL);
1564   if (!BitWidth) {
1565     KnownZero = false;
1566     KnownOne = false;
1567     return;
1568   }
1569   APInt ZeroBits(BitWidth, 0);
1570   APInt OneBits(BitWidth, 0);
1571   computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
1572   KnownOne = OneBits[BitWidth - 1];
1573   KnownZero = ZeroBits[BitWidth - 1];
1574 }
1575
1576 /// Return true if the given value is known to have exactly one
1577 /// bit set when defined. For vectors return true if every element is known to
1578 /// be a power of two when defined. Supports values with integer or pointer
1579 /// types and vectors of integers.
1580 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1581                             const Query &Q, const DataLayout &DL) {
1582   if (Constant *C = dyn_cast<Constant>(V)) {
1583     if (C->isNullValue())
1584       return OrZero;
1585     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1586       return CI->getValue().isPowerOf2();
1587     // TODO: Handle vector constants.
1588   }
1589
1590   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
1591   // it is shifted off the end then the result is undefined.
1592   if (match(V, m_Shl(m_One(), m_Value())))
1593     return true;
1594
1595   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1596   // bottom.  If it is shifted off the bottom then the result is undefined.
1597   if (match(V, m_LShr(m_SignBit(), m_Value())))
1598     return true;
1599
1600   // The remaining tests are all recursive, so bail out if we hit the limit.
1601   if (Depth++ == MaxDepth)
1602     return false;
1603
1604   Value *X = nullptr, *Y = nullptr;
1605   // A shift of a power of two is a power of two or zero.
1606   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1607                  match(V, m_Shr(m_Value(X), m_Value()))))
1608     return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
1609
1610   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1611     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
1612
1613   if (SelectInst *SI = dyn_cast<SelectInst>(V))
1614     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
1615            isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
1616
1617   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1618     // A power of two and'd with anything is a power of two or zero.
1619     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
1620         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
1621       return true;
1622     // X & (-X) is always a power of two or zero.
1623     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1624       return true;
1625     return false;
1626   }
1627
1628   // Adding a power-of-two or zero to the same power-of-two or zero yields
1629   // either the original power-of-two, a larger power-of-two or zero.
1630   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1631     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1632     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1633       if (match(X, m_And(m_Specific(Y), m_Value())) ||
1634           match(X, m_And(m_Value(), m_Specific(Y))))
1635         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
1636           return true;
1637       if (match(Y, m_And(m_Specific(X), m_Value())) ||
1638           match(Y, m_And(m_Value(), m_Specific(X))))
1639         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
1640           return true;
1641
1642       unsigned BitWidth = V->getType()->getScalarSizeInBits();
1643       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1644       computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
1645
1646       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1647       computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
1648       // If i8 V is a power of two or zero:
1649       //  ZeroBits: 1 1 1 0 1 1 1 1
1650       // ~ZeroBits: 0 0 0 1 0 0 0 0
1651       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1652         // If OrZero isn't set, we cannot give back a zero result.
1653         // Make sure either the LHS or RHS has a bit set.
1654         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1655           return true;
1656     }
1657   }
1658
1659   // An exact divide or right shift can only shift off zero bits, so the result
1660   // is a power of two only if the first operand is a power of two and not
1661   // copying a sign bit (sdiv int_min, 2).
1662   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1663       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1664     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1665                                   Depth, Q, DL);
1666   }
1667
1668   return false;
1669 }
1670
1671 /// \brief Test whether a GEP's result is known to be non-null.
1672 ///
1673 /// Uses properties inherent in a GEP to try to determine whether it is known
1674 /// to be non-null.
1675 ///
1676 /// Currently this routine does not support vector GEPs.
1677 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
1678                               unsigned Depth, const Query &Q) {
1679   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1680     return false;
1681
1682   // FIXME: Support vector-GEPs.
1683   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1684
1685   // If the base pointer is non-null, we cannot walk to a null address with an
1686   // inbounds GEP in address space zero.
1687   if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
1688     return true;
1689
1690   // Walk the GEP operands and see if any operand introduces a non-zero offset.
1691   // If so, then the GEP cannot produce a null pointer, as doing so would
1692   // inherently violate the inbounds contract within address space zero.
1693   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1694        GTI != GTE; ++GTI) {
1695     // Struct types are easy -- they must always be indexed by a constant.
1696     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1697       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1698       unsigned ElementIdx = OpC->getZExtValue();
1699       const StructLayout *SL = DL.getStructLayout(STy);
1700       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1701       if (ElementOffset > 0)
1702         return true;
1703       continue;
1704     }
1705
1706     // If we have a zero-sized type, the index doesn't matter. Keep looping.
1707     if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1708       continue;
1709
1710     // Fast path the constant operand case both for efficiency and so we don't
1711     // increment Depth when just zipping down an all-constant GEP.
1712     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1713       if (!OpC->isZero())
1714         return true;
1715       continue;
1716     }
1717
1718     // We post-increment Depth here because while isKnownNonZero increments it
1719     // as well, when we pop back up that increment won't persist. We don't want
1720     // to recurse 10k times just because we have 10k GEP operands. We don't
1721     // bail completely out because we want to handle constant GEPs regardless
1722     // of depth.
1723     if (Depth++ >= MaxDepth)
1724       continue;
1725
1726     if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
1727       return true;
1728   }
1729
1730   return false;
1731 }
1732
1733 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1734 /// ensure that the value it's attached to is never Value?  'RangeType' is
1735 /// is the type of the value described by the range.
1736 static bool rangeMetadataExcludesValue(MDNode* Ranges,
1737                                        const APInt& Value) {
1738   const unsigned NumRanges = Ranges->getNumOperands() / 2;
1739   assert(NumRanges >= 1);
1740   for (unsigned i = 0; i < NumRanges; ++i) {
1741     ConstantInt *Lower =
1742         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1743     ConstantInt *Upper =
1744         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1745     ConstantRange Range(Lower->getValue(), Upper->getValue());
1746     if (Range.contains(Value))
1747       return false;
1748   }
1749   return true;
1750 }
1751
1752 /// Return true if the given value is known to be non-zero when defined.
1753 /// For vectors return true if every element is known to be non-zero when
1754 /// defined. Supports values with integer or pointer type and vectors of
1755 /// integers.
1756 bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
1757                     const Query &Q) {
1758   if (Constant *C = dyn_cast<Constant>(V)) {
1759     if (C->isNullValue())
1760       return false;
1761     if (isa<ConstantInt>(C))
1762       // Must be non-zero due to null test above.
1763       return true;
1764     // TODO: Handle vectors
1765     return false;
1766   }
1767
1768   if (Instruction* I = dyn_cast<Instruction>(V)) {
1769     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1770       // If the possible ranges don't contain zero, then the value is
1771       // definitely non-zero.
1772       if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1773         const APInt ZeroValue(Ty->getBitWidth(), 0);
1774         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1775           return true;
1776       }
1777     }
1778   }
1779
1780   // The remaining tests are all recursive, so bail out if we hit the limit.
1781   if (Depth++ >= MaxDepth)
1782     return false;
1783
1784   // Check for pointer simplifications.
1785   if (V->getType()->isPointerTy()) {
1786     if (isKnownNonNull(V))
1787       return true; 
1788     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1789       if (isGEPKnownNonNull(GEP, DL, Depth, Q))
1790         return true;
1791   }
1792
1793   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
1794
1795   // X | Y != 0 if X != 0 or Y != 0.
1796   Value *X = nullptr, *Y = nullptr;
1797   if (match(V, m_Or(m_Value(X), m_Value(Y))))
1798     return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
1799
1800   // ext X != 0 if X != 0.
1801   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1802     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
1803
1804   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
1805   // if the lowest bit is shifted off the end.
1806   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1807     // shl nuw can't remove any non-zero bits.
1808     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1809     if (BO->hasNoUnsignedWrap())
1810       return isKnownNonZero(X, DL, Depth, Q);
1811
1812     APInt KnownZero(BitWidth, 0);
1813     APInt KnownOne(BitWidth, 0);
1814     computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1815     if (KnownOne[0])
1816       return true;
1817   }
1818   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
1819   // defined if the sign bit is shifted off the end.
1820   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1821     // shr exact can only shift out zero bits.
1822     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1823     if (BO->isExact())
1824       return isKnownNonZero(X, DL, Depth, Q);
1825
1826     bool XKnownNonNegative, XKnownNegative;
1827     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1828     if (XKnownNegative)
1829       return true;
1830   }
1831   // div exact can only produce a zero if the dividend is zero.
1832   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1833     return isKnownNonZero(X, DL, Depth, Q);
1834   }
1835   // X + Y.
1836   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1837     bool XKnownNonNegative, XKnownNegative;
1838     bool YKnownNonNegative, YKnownNegative;
1839     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1840     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
1841
1842     // If X and Y are both non-negative (as signed values) then their sum is not
1843     // zero unless both X and Y are zero.
1844     if (XKnownNonNegative && YKnownNonNegative)
1845       if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
1846         return true;
1847
1848     // If X and Y are both negative (as signed values) then their sum is not
1849     // zero unless both X and Y equal INT_MIN.
1850     if (BitWidth && XKnownNegative && YKnownNegative) {
1851       APInt KnownZero(BitWidth, 0);
1852       APInt KnownOne(BitWidth, 0);
1853       APInt Mask = APInt::getSignedMaxValue(BitWidth);
1854       // The sign bit of X is set.  If some other bit is set then X is not equal
1855       // to INT_MIN.
1856       computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1857       if ((KnownOne & Mask) != 0)
1858         return true;
1859       // The sign bit of Y is set.  If some other bit is set then Y is not equal
1860       // to INT_MIN.
1861       computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
1862       if ((KnownOne & Mask) != 0)
1863         return true;
1864     }
1865
1866     // The sum of a non-negative number and a power of two is not zero.
1867     if (XKnownNonNegative &&
1868         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
1869       return true;
1870     if (YKnownNonNegative &&
1871         isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
1872       return true;
1873   }
1874   // X * Y.
1875   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1876     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1877     // If X and Y are non-zero then so is X * Y as long as the multiplication
1878     // does not overflow.
1879     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1880         isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
1881       return true;
1882   }
1883   // (C ? X : Y) != 0 if X != 0 and Y != 0.
1884   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1885     if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
1886         isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
1887       return true;
1888   }
1889
1890   if (!BitWidth) return false;
1891   APInt KnownZero(BitWidth, 0);
1892   APInt KnownOne(BitWidth, 0);
1893   computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
1894   return KnownOne != 0;
1895 }
1896
1897 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
1898 /// simplify operations downstream. Mask is known to be zero for bits that V
1899 /// cannot have.
1900 ///
1901 /// This function is defined on values with integer type, values with pointer
1902 /// type, and vectors of integers.  In the case
1903 /// where V is a vector, the mask, known zero, and known one values are the
1904 /// same width as the vector element, and the bit is set only if it is true
1905 /// for all of the elements in the vector.
1906 bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
1907                        unsigned Depth, const Query &Q) {
1908   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1909   computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
1910   return (KnownZero & Mask) == Mask;
1911 }
1912
1913
1914
1915 /// Return the number of times the sign bit of the register is replicated into
1916 /// the other bits. We know that at least 1 bit is always equal to the sign bit
1917 /// (itself), but other cases can give us information. For example, immediately
1918 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
1919 /// other, so we return 3.
1920 ///
1921 /// 'Op' must have a scalar integer type.
1922 ///
1923 unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
1924                             const Query &Q) {
1925   unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
1926   unsigned Tmp, Tmp2;
1927   unsigned FirstAnswer = 1;
1928
1929   // Note that ConstantInt is handled by the general computeKnownBits case
1930   // below.
1931
1932   if (Depth == 6)
1933     return 1;  // Limit search depth.
1934
1935   Operator *U = dyn_cast<Operator>(V);
1936   switch (Operator::getOpcode(V)) {
1937   default: break;
1938   case Instruction::SExt:
1939     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1940     return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
1941
1942   case Instruction::SDiv: {
1943     const APInt *Denominator;
1944     // sdiv X, C -> adds log(C) sign bits.
1945     if (match(U->getOperand(1), m_APInt(Denominator))) {
1946
1947       // Ignore non-positive denominator.
1948       if (!Denominator->isStrictlyPositive())
1949         break;
1950
1951       // Calculate the incoming numerator bits.
1952       unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1953
1954       // Add floor(log(C)) bits to the numerator bits.
1955       return std::min(TyBits, NumBits + Denominator->logBase2());
1956     }
1957     break;
1958   }
1959
1960   case Instruction::SRem: {
1961     const APInt *Denominator;
1962     // srem X, C -> we know that the result is within [-C+1,C) when C is a
1963     // positive constant.  This let us put a lower bound on the number of sign
1964     // bits.
1965     if (match(U->getOperand(1), m_APInt(Denominator))) {
1966
1967       // Ignore non-positive denominator.
1968       if (!Denominator->isStrictlyPositive())
1969         break;
1970
1971       // Calculate the incoming numerator bits. SRem by a positive constant
1972       // can't lower the number of sign bits.
1973       unsigned NumrBits =
1974           ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1975
1976       // Calculate the leading sign bit constraints by examining the
1977       // denominator.  Given that the denominator is positive, there are two
1978       // cases:
1979       //
1980       //  1. the numerator is positive.  The result range is [0,C) and [0,C) u<
1981       //     (1 << ceilLogBase2(C)).
1982       //
1983       //  2. the numerator is negative.  Then the result range is (-C,0] and
1984       //     integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
1985       //
1986       // Thus a lower bound on the number of sign bits is `TyBits -
1987       // ceilLogBase2(C)`.
1988
1989       unsigned ResBits = TyBits - Denominator->ceilLogBase2();
1990       return std::max(NumrBits, ResBits);
1991     }
1992     break;
1993   }
1994
1995   case Instruction::AShr: {
1996     Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1997     // ashr X, C   -> adds C sign bits.  Vectors too.
1998     const APInt *ShAmt;
1999     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2000       Tmp += ShAmt->getZExtValue();
2001       if (Tmp > TyBits) Tmp = TyBits;
2002     }
2003     return Tmp;
2004   }
2005   case Instruction::Shl: {
2006     const APInt *ShAmt;
2007     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2008       // shl destroys sign bits.
2009       Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2010       Tmp2 = ShAmt->getZExtValue();
2011       if (Tmp2 >= TyBits ||      // Bad shift.
2012           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
2013       return Tmp - Tmp2;
2014     }
2015     break;
2016   }
2017   case Instruction::And:
2018   case Instruction::Or:
2019   case Instruction::Xor:    // NOT is handled here.
2020     // Logical binary ops preserve the number of sign bits at the worst.
2021     Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2022     if (Tmp != 1) {
2023       Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2024       FirstAnswer = std::min(Tmp, Tmp2);
2025       // We computed what we know about the sign bits as our first
2026       // answer. Now proceed to the generic code that uses
2027       // computeKnownBits, and pick whichever answer is better.
2028     }
2029     break;
2030
2031   case Instruction::Select:
2032     Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2033     if (Tmp == 1) return 1;  // Early out.
2034     Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
2035     return std::min(Tmp, Tmp2);
2036
2037   case Instruction::Add:
2038     // Add can have at most one carry bit.  Thus we know that the output
2039     // is, at worst, one more bit than the inputs.
2040     Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2041     if (Tmp == 1) return 1;  // Early out.
2042
2043     // Special case decrementing a value (ADD X, -1):
2044     if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2045       if (CRHS->isAllOnesValue()) {
2046         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2047         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
2048                          Q);
2049
2050         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2051         // sign bits set.
2052         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2053           return TyBits;
2054
2055         // If we are subtracting one from a positive number, there is no carry
2056         // out of the result.
2057         if (KnownZero.isNegative())
2058           return Tmp;
2059       }
2060
2061     Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2062     if (Tmp2 == 1) return 1;
2063     return std::min(Tmp, Tmp2)-1;
2064
2065   case Instruction::Sub:
2066     Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2067     if (Tmp2 == 1) return 1;
2068
2069     // Handle NEG.
2070     if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2071       if (CLHS->isNullValue()) {
2072         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2073         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
2074                          Q);
2075         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2076         // sign bits set.
2077         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2078           return TyBits;
2079
2080         // If the input is known to be positive (the sign bit is known clear),
2081         // the output of the NEG has the same number of sign bits as the input.
2082         if (KnownZero.isNegative())
2083           return Tmp2;
2084
2085         // Otherwise, we treat this like a SUB.
2086       }
2087
2088     // Sub can have at most one carry bit.  Thus we know that the output
2089     // is, at worst, one more bit than the inputs.
2090     Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2091     if (Tmp == 1) return 1;  // Early out.
2092     return std::min(Tmp, Tmp2)-1;
2093
2094   case Instruction::PHI: {
2095     PHINode *PN = cast<PHINode>(U);
2096     unsigned NumIncomingValues = PN->getNumIncomingValues();
2097     // Don't analyze large in-degree PHIs.
2098     if (NumIncomingValues > 4) break;
2099     // Unreachable blocks may have zero-operand PHI nodes.
2100     if (NumIncomingValues == 0) break;
2101
2102     // Take the minimum of all incoming values.  This can't infinitely loop
2103     // because of our depth threshold.
2104     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
2105     for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2106       if (Tmp == 1) return Tmp;
2107       Tmp = std::min(
2108           Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
2109     }
2110     return Tmp;
2111   }
2112
2113   case Instruction::Trunc:
2114     // FIXME: it's tricky to do anything useful for this, but it is an important
2115     // case for targets like X86.
2116     break;
2117   }
2118
2119   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2120   // use this information.
2121   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2122   APInt Mask;
2123   computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
2124
2125   if (KnownZero.isNegative()) {        // sign bit is 0
2126     Mask = KnownZero;
2127   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2128     Mask = KnownOne;
2129   } else {
2130     // Nothing known.
2131     return FirstAnswer;
2132   }
2133
2134   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2135   // the number of identical bits in the top of the input value.
2136   Mask = ~Mask;
2137   Mask <<= Mask.getBitWidth()-TyBits;
2138   // Return # leading zeros.  We use 'min' here in case Val was zero before
2139   // shifting.  We don't want to return '64' as for an i32 "0".
2140   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2141 }
2142
2143 /// This function computes the integer multiple of Base that equals V.
2144 /// If successful, it returns true and returns the multiple in
2145 /// Multiple. If unsuccessful, it returns false. It looks
2146 /// through SExt instructions only if LookThroughSExt is true.
2147 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2148                            bool LookThroughSExt, unsigned Depth) {
2149   const unsigned MaxDepth = 6;
2150
2151   assert(V && "No Value?");
2152   assert(Depth <= MaxDepth && "Limit Search Depth");
2153   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2154
2155   Type *T = V->getType();
2156
2157   ConstantInt *CI = dyn_cast<ConstantInt>(V);
2158
2159   if (Base == 0)
2160     return false;
2161
2162   if (Base == 1) {
2163     Multiple = V;
2164     return true;
2165   }
2166
2167   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2168   Constant *BaseVal = ConstantInt::get(T, Base);
2169   if (CO && CO == BaseVal) {
2170     // Multiple is 1.
2171     Multiple = ConstantInt::get(T, 1);
2172     return true;
2173   }
2174
2175   if (CI && CI->getZExtValue() % Base == 0) {
2176     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2177     return true;
2178   }
2179
2180   if (Depth == MaxDepth) return false;  // Limit search depth.
2181
2182   Operator *I = dyn_cast<Operator>(V);
2183   if (!I) return false;
2184
2185   switch (I->getOpcode()) {
2186   default: break;
2187   case Instruction::SExt:
2188     if (!LookThroughSExt) return false;
2189     // otherwise fall through to ZExt
2190   case Instruction::ZExt:
2191     return ComputeMultiple(I->getOperand(0), Base, Multiple,
2192                            LookThroughSExt, Depth+1);
2193   case Instruction::Shl:
2194   case Instruction::Mul: {
2195     Value *Op0 = I->getOperand(0);
2196     Value *Op1 = I->getOperand(1);
2197
2198     if (I->getOpcode() == Instruction::Shl) {
2199       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2200       if (!Op1CI) return false;
2201       // Turn Op0 << Op1 into Op0 * 2^Op1
2202       APInt Op1Int = Op1CI->getValue();
2203       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2204       APInt API(Op1Int.getBitWidth(), 0);
2205       API.setBit(BitToSet);
2206       Op1 = ConstantInt::get(V->getContext(), API);
2207     }
2208
2209     Value *Mul0 = nullptr;
2210     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2211       if (Constant *Op1C = dyn_cast<Constant>(Op1))
2212         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2213           if (Op1C->getType()->getPrimitiveSizeInBits() <
2214               MulC->getType()->getPrimitiveSizeInBits())
2215             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2216           if (Op1C->getType()->getPrimitiveSizeInBits() >
2217               MulC->getType()->getPrimitiveSizeInBits())
2218             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2219
2220           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2221           Multiple = ConstantExpr::getMul(MulC, Op1C);
2222           return true;
2223         }
2224
2225       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2226         if (Mul0CI->getValue() == 1) {
2227           // V == Base * Op1, so return Op1
2228           Multiple = Op1;
2229           return true;
2230         }
2231     }
2232
2233     Value *Mul1 = nullptr;
2234     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2235       if (Constant *Op0C = dyn_cast<Constant>(Op0))
2236         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2237           if (Op0C->getType()->getPrimitiveSizeInBits() <
2238               MulC->getType()->getPrimitiveSizeInBits())
2239             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2240           if (Op0C->getType()->getPrimitiveSizeInBits() >
2241               MulC->getType()->getPrimitiveSizeInBits())
2242             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2243
2244           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2245           Multiple = ConstantExpr::getMul(MulC, Op0C);
2246           return true;
2247         }
2248
2249       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2250         if (Mul1CI->getValue() == 1) {
2251           // V == Base * Op0, so return Op0
2252           Multiple = Op0;
2253           return true;
2254         }
2255     }
2256   }
2257   }
2258
2259   // We could not determine if V is a multiple of Base.
2260   return false;
2261 }
2262
2263 /// Return true if we can prove that the specified FP value is never equal to
2264 /// -0.0.
2265 ///
2266 /// NOTE: this function will need to be revisited when we support non-default
2267 /// rounding modes!
2268 ///
2269 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2270   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2271     return !CFP->getValueAPF().isNegZero();
2272
2273   // FIXME: Magic number! At the least, this should be given a name because it's
2274   // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2275   // expose it as a parameter, so it can be used for testing / experimenting.
2276   if (Depth == 6)
2277     return false;  // Limit search depth.
2278
2279   const Operator *I = dyn_cast<Operator>(V);
2280   if (!I) return false;
2281
2282   // Check if the nsz fast-math flag is set
2283   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2284     if (FPO->hasNoSignedZeros())
2285       return true;
2286
2287   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2288   if (I->getOpcode() == Instruction::FAdd)
2289     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2290       if (CFP->isNullValue())
2291         return true;
2292
2293   // sitofp and uitofp turn into +0.0 for zero.
2294   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2295     return true;
2296
2297   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2298     // sqrt(-0.0) = -0.0, no other negative results are possible.
2299     if (II->getIntrinsicID() == Intrinsic::sqrt)
2300       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
2301
2302   if (const CallInst *CI = dyn_cast<CallInst>(I))
2303     if (const Function *F = CI->getCalledFunction()) {
2304       if (F->isDeclaration()) {
2305         // abs(x) != -0.0
2306         if (F->getName() == "abs") return true;
2307         // fabs[lf](x) != -0.0
2308         if (F->getName() == "fabs") return true;
2309         if (F->getName() == "fabsf") return true;
2310         if (F->getName() == "fabsl") return true;
2311         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2312             F->getName() == "sqrtl")
2313           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
2314       }
2315     }
2316
2317   return false;
2318 }
2319
2320 bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2321   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2322     return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2323
2324   // FIXME: Magic number! At the least, this should be given a name because it's
2325   // used similarly in CannotBeNegativeZero(). A better fix may be to
2326   // expose it as a parameter, so it can be used for testing / experimenting.
2327   if (Depth == 6)
2328     return false;  // Limit search depth.
2329
2330   const Operator *I = dyn_cast<Operator>(V);
2331   if (!I) return false;
2332
2333   switch (I->getOpcode()) {
2334   default: break;
2335   case Instruction::FMul:
2336     // x*x is always non-negative or a NaN.
2337     if (I->getOperand(0) == I->getOperand(1)) 
2338       return true;
2339     // Fall through
2340   case Instruction::FAdd:
2341   case Instruction::FDiv:
2342   case Instruction::FRem:
2343     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2344            CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2345   case Instruction::FPExt:
2346   case Instruction::FPTrunc:
2347     // Widening/narrowing never change sign.
2348     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2349   case Instruction::Call: 
2350     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 
2351       switch (II->getIntrinsicID()) {
2352       default: break;
2353       case Intrinsic::exp:
2354       case Intrinsic::exp2:
2355       case Intrinsic::fabs:
2356       case Intrinsic::sqrt:
2357         return true;
2358       case Intrinsic::powi: 
2359         if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2360           // powi(x,n) is non-negative if n is even.
2361           if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2362             return true;
2363         }
2364         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2365       case Intrinsic::fma:
2366       case Intrinsic::fmuladd:
2367         // x*x+y is non-negative if y is non-negative.
2368         return I->getOperand(0) == I->getOperand(1) && 
2369                CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2370       }
2371     break;
2372   }
2373   return false; 
2374 }
2375
2376 /// If the specified value can be set by repeating the same byte in memory,
2377 /// return the i8 value that it is represented with.  This is
2378 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2379 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
2380 /// byte store (e.g. i16 0x1234), return null.
2381 Value *llvm::isBytewiseValue(Value *V) {
2382   // All byte-wide stores are splatable, even of arbitrary variables.
2383   if (V->getType()->isIntegerTy(8)) return V;
2384
2385   // Handle 'null' ConstantArrayZero etc.
2386   if (Constant *C = dyn_cast<Constant>(V))
2387     if (C->isNullValue())
2388       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2389
2390   // Constant float and double values can be handled as integer values if the
2391   // corresponding integer value is "byteable".  An important case is 0.0.
2392   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2393     if (CFP->getType()->isFloatTy())
2394       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2395     if (CFP->getType()->isDoubleTy())
2396       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2397     // Don't handle long double formats, which have strange constraints.
2398   }
2399
2400   // We can handle constant integers that are multiple of 8 bits.
2401   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2402     if (CI->getBitWidth() % 8 == 0) {
2403       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
2404
2405       if (!CI->getValue().isSplat(8))
2406         return nullptr;
2407       return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
2408     }
2409   }
2410
2411   // A ConstantDataArray/Vector is splatable if all its members are equal and
2412   // also splatable.
2413   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2414     Value *Elt = CA->getElementAsConstant(0);
2415     Value *Val = isBytewiseValue(Elt);
2416     if (!Val)
2417       return nullptr;
2418
2419     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2420       if (CA->getElementAsConstant(I) != Elt)
2421         return nullptr;
2422
2423     return Val;
2424   }
2425
2426   // Conceptually, we could handle things like:
2427   //   %a = zext i8 %X to i16
2428   //   %b = shl i16 %a, 8
2429   //   %c = or i16 %a, %b
2430   // but until there is an example that actually needs this, it doesn't seem
2431   // worth worrying about.
2432   return nullptr;
2433 }
2434
2435
2436 // This is the recursive version of BuildSubAggregate. It takes a few different
2437 // arguments. Idxs is the index within the nested struct From that we are
2438 // looking at now (which is of type IndexedType). IdxSkip is the number of
2439 // indices from Idxs that should be left out when inserting into the resulting
2440 // struct. To is the result struct built so far, new insertvalue instructions
2441 // build on that.
2442 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2443                                 SmallVectorImpl<unsigned> &Idxs,
2444                                 unsigned IdxSkip,
2445                                 Instruction *InsertBefore) {
2446   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2447   if (STy) {
2448     // Save the original To argument so we can modify it
2449     Value *OrigTo = To;
2450     // General case, the type indexed by Idxs is a struct
2451     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2452       // Process each struct element recursively
2453       Idxs.push_back(i);
2454       Value *PrevTo = To;
2455       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2456                              InsertBefore);
2457       Idxs.pop_back();
2458       if (!To) {
2459         // Couldn't find any inserted value for this index? Cleanup
2460         while (PrevTo != OrigTo) {
2461           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2462           PrevTo = Del->getAggregateOperand();
2463           Del->eraseFromParent();
2464         }
2465         // Stop processing elements
2466         break;
2467       }
2468     }
2469     // If we successfully found a value for each of our subaggregates
2470     if (To)
2471       return To;
2472   }
2473   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2474   // the struct's elements had a value that was inserted directly. In the latter
2475   // case, perhaps we can't determine each of the subelements individually, but
2476   // we might be able to find the complete struct somewhere.
2477
2478   // Find the value that is at that particular spot
2479   Value *V = FindInsertedValue(From, Idxs);
2480
2481   if (!V)
2482     return nullptr;
2483
2484   // Insert the value in the new (sub) aggregrate
2485   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2486                                        "tmp", InsertBefore);
2487 }
2488
2489 // This helper takes a nested struct and extracts a part of it (which is again a
2490 // struct) into a new value. For example, given the struct:
2491 // { a, { b, { c, d }, e } }
2492 // and the indices "1, 1" this returns
2493 // { c, d }.
2494 //
2495 // It does this by inserting an insertvalue for each element in the resulting
2496 // struct, as opposed to just inserting a single struct. This will only work if
2497 // each of the elements of the substruct are known (ie, inserted into From by an
2498 // insertvalue instruction somewhere).
2499 //
2500 // All inserted insertvalue instructions are inserted before InsertBefore
2501 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2502                                 Instruction *InsertBefore) {
2503   assert(InsertBefore && "Must have someplace to insert!");
2504   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2505                                                              idx_range);
2506   Value *To = UndefValue::get(IndexedType);
2507   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2508   unsigned IdxSkip = Idxs.size();
2509
2510   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2511 }
2512
2513 /// Given an aggregrate and an sequence of indices, see if
2514 /// the scalar value indexed is already around as a register, for example if it
2515 /// were inserted directly into the aggregrate.
2516 ///
2517 /// If InsertBefore is not null, this function will duplicate (modified)
2518 /// insertvalues when a part of a nested struct is extracted.
2519 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2520                                Instruction *InsertBefore) {
2521   // Nothing to index? Just return V then (this is useful at the end of our
2522   // recursion).
2523   if (idx_range.empty())
2524     return V;
2525   // We have indices, so V should have an indexable type.
2526   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2527          "Not looking at a struct or array?");
2528   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2529          "Invalid indices for type?");
2530
2531   if (Constant *C = dyn_cast<Constant>(V)) {
2532     C = C->getAggregateElement(idx_range[0]);
2533     if (!C) return nullptr;
2534     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2535   }
2536
2537   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2538     // Loop the indices for the insertvalue instruction in parallel with the
2539     // requested indices
2540     const unsigned *req_idx = idx_range.begin();
2541     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2542          i != e; ++i, ++req_idx) {
2543       if (req_idx == idx_range.end()) {
2544         // We can't handle this without inserting insertvalues
2545         if (!InsertBefore)
2546           return nullptr;
2547
2548         // The requested index identifies a part of a nested aggregate. Handle
2549         // this specially. For example,
2550         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2551         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2552         // %C = extractvalue {i32, { i32, i32 } } %B, 1
2553         // This can be changed into
2554         // %A = insertvalue {i32, i32 } undef, i32 10, 0
2555         // %C = insertvalue {i32, i32 } %A, i32 11, 1
2556         // which allows the unused 0,0 element from the nested struct to be
2557         // removed.
2558         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2559                                  InsertBefore);
2560       }
2561
2562       // This insert value inserts something else than what we are looking for.
2563       // See if the (aggregate) value inserted into has the value we are
2564       // looking for, then.
2565       if (*req_idx != *i)
2566         return FindInsertedValue(I->getAggregateOperand(), idx_range,
2567                                  InsertBefore);
2568     }
2569     // If we end up here, the indices of the insertvalue match with those
2570     // requested (though possibly only partially). Now we recursively look at
2571     // the inserted value, passing any remaining indices.
2572     return FindInsertedValue(I->getInsertedValueOperand(),
2573                              makeArrayRef(req_idx, idx_range.end()),
2574                              InsertBefore);
2575   }
2576
2577   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2578     // If we're extracting a value from an aggregate that was extracted from
2579     // something else, we can extract from that something else directly instead.
2580     // However, we will need to chain I's indices with the requested indices.
2581
2582     // Calculate the number of indices required
2583     unsigned size = I->getNumIndices() + idx_range.size();
2584     // Allocate some space to put the new indices in
2585     SmallVector<unsigned, 5> Idxs;
2586     Idxs.reserve(size);
2587     // Add indices from the extract value instruction
2588     Idxs.append(I->idx_begin(), I->idx_end());
2589
2590     // Add requested indices
2591     Idxs.append(idx_range.begin(), idx_range.end());
2592
2593     assert(Idxs.size() == size
2594            && "Number of indices added not correct?");
2595
2596     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2597   }
2598   // Otherwise, we don't know (such as, extracting from a function return value
2599   // or load instruction)
2600   return nullptr;
2601 }
2602
2603 /// Analyze the specified pointer to see if it can be expressed as a base
2604 /// pointer plus a constant offset. Return the base and offset to the caller.
2605 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2606                                               const DataLayout &DL) {
2607   unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
2608   APInt ByteOffset(BitWidth, 0);
2609   while (1) {
2610     if (Ptr->getType()->isVectorTy())
2611       break;
2612
2613     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2614       APInt GEPOffset(BitWidth, 0);
2615       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2616         break;
2617
2618       ByteOffset += GEPOffset;
2619
2620       Ptr = GEP->getPointerOperand();
2621     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2622                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2623       Ptr = cast<Operator>(Ptr)->getOperand(0);
2624     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2625       if (GA->mayBeOverridden())
2626         break;
2627       Ptr = GA->getAliasee();
2628     } else {
2629       break;
2630     }
2631   }
2632   Offset = ByteOffset.getSExtValue();
2633   return Ptr;
2634 }
2635
2636
2637 /// This function computes the length of a null-terminated C string pointed to
2638 /// by V. If successful, it returns true and returns the string in Str.
2639 /// If unsuccessful, it returns false.
2640 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2641                                  uint64_t Offset, bool TrimAtNul) {
2642   assert(V);
2643
2644   // Look through bitcast instructions and geps.
2645   V = V->stripPointerCasts();
2646
2647   // If the value is a GEP instruction or constant expression, treat it as an
2648   // offset.
2649   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2650     // Make sure the GEP has exactly three arguments.
2651     if (GEP->getNumOperands() != 3)
2652       return false;
2653
2654     // Make sure the index-ee is a pointer to array of i8.
2655     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2656     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
2657     if (!AT || !AT->getElementType()->isIntegerTy(8))
2658       return false;
2659
2660     // Check to make sure that the first operand of the GEP is an integer and
2661     // has value 0 so that we are sure we're indexing into the initializer.
2662     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2663     if (!FirstIdx || !FirstIdx->isZero())
2664       return false;
2665
2666     // If the second index isn't a ConstantInt, then this is a variable index
2667     // into the array.  If this occurs, we can't say anything meaningful about
2668     // the string.
2669     uint64_t StartIdx = 0;
2670     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2671       StartIdx = CI->getZExtValue();
2672     else
2673       return false;
2674     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
2675                                  TrimAtNul);
2676   }
2677
2678   // The GEP instruction, constant or instruction, must reference a global
2679   // variable that is a constant and is initialized. The referenced constant
2680   // initializer is the array that we'll use for optimization.
2681   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2682   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2683     return false;
2684
2685   // Handle the all-zeros case
2686   if (GV->getInitializer()->isNullValue()) {
2687     // This is a degenerate case. The initializer is constant zero so the
2688     // length of the string must be zero.
2689     Str = "";
2690     return true;
2691   }
2692
2693   // Must be a Constant Array
2694   const ConstantDataArray *Array =
2695     dyn_cast<ConstantDataArray>(GV->getInitializer());
2696   if (!Array || !Array->isString())
2697     return false;
2698
2699   // Get the number of elements in the array
2700   uint64_t NumElts = Array->getType()->getArrayNumElements();
2701
2702   // Start out with the entire array in the StringRef.
2703   Str = Array->getAsString();
2704
2705   if (Offset > NumElts)
2706     return false;
2707
2708   // Skip over 'offset' bytes.
2709   Str = Str.substr(Offset);
2710
2711   if (TrimAtNul) {
2712     // Trim off the \0 and anything after it.  If the array is not nul
2713     // terminated, we just return the whole end of string.  The client may know
2714     // some other way that the string is length-bound.
2715     Str = Str.substr(0, Str.find('\0'));
2716   }
2717   return true;
2718 }
2719
2720 // These next two are very similar to the above, but also look through PHI
2721 // nodes.
2722 // TODO: See if we can integrate these two together.
2723
2724 /// If we can compute the length of the string pointed to by
2725 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2726 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2727   // Look through noop bitcast instructions.
2728   V = V->stripPointerCasts();
2729
2730   // If this is a PHI node, there are two cases: either we have already seen it
2731   // or we haven't.
2732   if (PHINode *PN = dyn_cast<PHINode>(V)) {
2733     if (!PHIs.insert(PN).second)
2734       return ~0ULL;  // already in the set.
2735
2736     // If it was new, see if all the input strings are the same length.
2737     uint64_t LenSoFar = ~0ULL;
2738     for (Value *IncValue : PN->incoming_values()) {
2739       uint64_t Len = GetStringLengthH(IncValue, PHIs);
2740       if (Len == 0) return 0; // Unknown length -> unknown.
2741
2742       if (Len == ~0ULL) continue;
2743
2744       if (Len != LenSoFar && LenSoFar != ~0ULL)
2745         return 0;    // Disagree -> unknown.
2746       LenSoFar = Len;
2747     }
2748
2749     // Success, all agree.
2750     return LenSoFar;
2751   }
2752
2753   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2754   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2755     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2756     if (Len1 == 0) return 0;
2757     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2758     if (Len2 == 0) return 0;
2759     if (Len1 == ~0ULL) return Len2;
2760     if (Len2 == ~0ULL) return Len1;
2761     if (Len1 != Len2) return 0;
2762     return Len1;
2763   }
2764
2765   // Otherwise, see if we can read the string.
2766   StringRef StrData;
2767   if (!getConstantStringInfo(V, StrData))
2768     return 0;
2769
2770   return StrData.size()+1;
2771 }
2772
2773 /// If we can compute the length of the string pointed to by
2774 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2775 uint64_t llvm::GetStringLength(Value *V) {
2776   if (!V->getType()->isPointerTy()) return 0;
2777
2778   SmallPtrSet<PHINode*, 32> PHIs;
2779   uint64_t Len = GetStringLengthH(V, PHIs);
2780   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2781   // an empty string as a length.
2782   return Len == ~0ULL ? 1 : Len;
2783 }
2784
2785 /// \brief \p PN defines a loop-variant pointer to an object.  Check if the
2786 /// previous iteration of the loop was referring to the same object as \p PN.
2787 static bool isSameUnderlyingObjectInLoop(PHINode *PN, LoopInfo *LI) {
2788   // Find the loop-defined value.
2789   Loop *L = LI->getLoopFor(PN->getParent());
2790   if (PN->getNumIncomingValues() != 2)
2791     return true;
2792
2793   // Find the value from previous iteration.
2794   auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
2795   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
2796     PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
2797   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
2798     return true;
2799
2800   // If a new pointer is loaded in the loop, the pointer references a different
2801   // object in every iteration.  E.g.:
2802   //    for (i)
2803   //       int *p = a[i];
2804   //       ...
2805   if (auto *Load = dyn_cast<LoadInst>(PrevValue))
2806     if (!L->isLoopInvariant(Load->getPointerOperand()))
2807       return false;
2808   return true;
2809 }
2810
2811 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
2812                                  unsigned MaxLookup) {
2813   if (!V->getType()->isPointerTy())
2814     return V;
2815   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2816     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2817       V = GEP->getPointerOperand();
2818     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2819                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
2820       V = cast<Operator>(V)->getOperand(0);
2821     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2822       if (GA->mayBeOverridden())
2823         return V;
2824       V = GA->getAliasee();
2825     } else {
2826       // See if InstructionSimplify knows any relevant tricks.
2827       if (Instruction *I = dyn_cast<Instruction>(V))
2828         // TODO: Acquire a DominatorTree and AssumptionCache and use them.
2829         if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
2830           V = Simplified;
2831           continue;
2832         }
2833
2834       return V;
2835     }
2836     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2837   }
2838   return V;
2839 }
2840
2841 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
2842                                 const DataLayout &DL, LoopInfo *LI,
2843                                 unsigned MaxLookup) {
2844   SmallPtrSet<Value *, 4> Visited;
2845   SmallVector<Value *, 4> Worklist;
2846   Worklist.push_back(V);
2847   do {
2848     Value *P = Worklist.pop_back_val();
2849     P = GetUnderlyingObject(P, DL, MaxLookup);
2850
2851     if (!Visited.insert(P).second)
2852       continue;
2853
2854     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2855       Worklist.push_back(SI->getTrueValue());
2856       Worklist.push_back(SI->getFalseValue());
2857       continue;
2858     }
2859
2860     if (PHINode *PN = dyn_cast<PHINode>(P)) {
2861       // If this PHI changes the underlying object in every iteration of the
2862       // loop, don't look through it.  Consider:
2863       //   int **A;
2864       //   for (i) {
2865       //     Prev = Curr;     // Prev = PHI (Prev_0, Curr)
2866       //     Curr = A[i];
2867       //     *Prev, *Curr;
2868       //
2869       // Prev is tracking Curr one iteration behind so they refer to different
2870       // underlying objects.
2871       if (!LI || !LI->isLoopHeader(PN->getParent()) ||
2872           isSameUnderlyingObjectInLoop(PN, LI))
2873         for (Value *IncValue : PN->incoming_values())
2874           Worklist.push_back(IncValue);
2875       continue;
2876     }
2877
2878     Objects.push_back(P);
2879   } while (!Worklist.empty());
2880 }
2881
2882 /// Return true if the only users of this pointer are lifetime markers.
2883 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
2884   for (const User *U : V->users()) {
2885     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2886     if (!II) return false;
2887
2888     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2889         II->getIntrinsicID() != Intrinsic::lifetime_end)
2890       return false;
2891   }
2892   return true;
2893 }
2894
2895 static bool isDereferenceableFromAttribute(const Value *BV, APInt Offset,
2896                                            Type *Ty, const DataLayout &DL,
2897                                            const Instruction *CtxI,
2898                                            const DominatorTree *DT,
2899                                            const TargetLibraryInfo *TLI) {
2900   assert(Offset.isNonNegative() && "offset can't be negative");
2901   assert(Ty->isSized() && "must be sized");
2902   
2903   APInt DerefBytes(Offset.getBitWidth(), 0);
2904   bool CheckForNonNull = false;
2905   if (const Argument *A = dyn_cast<Argument>(BV)) {
2906     DerefBytes = A->getDereferenceableBytes();
2907     if (!DerefBytes.getBoolValue()) {
2908       DerefBytes = A->getDereferenceableOrNullBytes();
2909       CheckForNonNull = true;
2910     }
2911   } else if (auto CS = ImmutableCallSite(BV)) {
2912     DerefBytes = CS.getDereferenceableBytes(0);
2913     if (!DerefBytes.getBoolValue()) {
2914       DerefBytes = CS.getDereferenceableOrNullBytes(0);
2915       CheckForNonNull = true;
2916     }
2917   } else if (const LoadInst *LI = dyn_cast<LoadInst>(BV)) {
2918     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
2919       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
2920       DerefBytes = CI->getLimitedValue();
2921     }
2922     if (!DerefBytes.getBoolValue()) {
2923       if (MDNode *MD = 
2924               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
2925         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
2926         DerefBytes = CI->getLimitedValue();
2927       }
2928       CheckForNonNull = true;
2929     }
2930   }
2931   
2932   if (DerefBytes.getBoolValue())
2933     if (DerefBytes.uge(Offset + DL.getTypeStoreSize(Ty)))
2934       if (!CheckForNonNull || isKnownNonNullAt(BV, CtxI, DT, TLI))
2935         return true;
2936
2937   return false;
2938 }
2939
2940 static bool isDereferenceableFromAttribute(const Value *V, const DataLayout &DL,
2941                                            const Instruction *CtxI,
2942                                            const DominatorTree *DT,
2943                                            const TargetLibraryInfo *TLI) {
2944   Type *VTy = V->getType();
2945   Type *Ty = VTy->getPointerElementType();
2946   if (!Ty->isSized())
2947     return false;
2948   
2949   APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
2950   return isDereferenceableFromAttribute(V, Offset, Ty, DL, CtxI, DT, TLI);
2951 }
2952
2953 static bool isAligned(const Value *Base, APInt Offset, unsigned Align,
2954                       const DataLayout &DL) {
2955   APInt BaseAlign(Offset.getBitWidth(), 0);
2956   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base))
2957     BaseAlign = AI->getAlignment();
2958   else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base))
2959     BaseAlign = GV->getAlignment();
2960   else if (const Argument *A = dyn_cast<Argument>(Base))
2961     BaseAlign = A->getParamAlignment();
2962   else if (auto CS = ImmutableCallSite(Base))
2963     BaseAlign = CS.getAttributes().getParamAlignment(AttributeSet::ReturnIndex);
2964
2965   if (!BaseAlign) {
2966     Type *Ty = Base->getType()->getPointerElementType();
2967     BaseAlign = DL.getABITypeAlignment(Ty);
2968   }
2969
2970   APInt Alignment(Offset.getBitWidth(), Align);
2971
2972   assert(Alignment.isPowerOf2() && "must be a power of 2!");
2973   return BaseAlign.uge(Alignment) && !(Offset & (Alignment-1));
2974 }
2975
2976 static bool isAligned(const Value *Base, unsigned Align, const DataLayout &DL) {
2977   APInt Offset(DL.getTypeStoreSizeInBits(Base->getType()), 0);
2978   return isAligned(Base, Offset, Align, DL);
2979 }
2980
2981 /// Test if V is always a pointer to allocated and suitably aligned memory for
2982 /// a simple load or store.
2983 static bool isDereferenceableAndAlignedPointer(
2984     const Value *V, unsigned Align, const DataLayout &DL,
2985     const Instruction *CtxI, const DominatorTree *DT,
2986     const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited) {
2987   // Note that it is not safe to speculate into a malloc'd region because
2988   // malloc may return null.
2989
2990   // These are obviously ok if aligned.
2991   if (isa<AllocaInst>(V))
2992     return isAligned(V, Align, DL);
2993
2994   // It's not always safe to follow a bitcast, for example:
2995   //   bitcast i8* (alloca i8) to i32*
2996   // would result in a 4-byte load from a 1-byte alloca. However,
2997   // if we're casting from a pointer from a type of larger size
2998   // to a type of smaller size (or the same size), and the alignment
2999   // is at least as large as for the resulting pointer type, then
3000   // we can look through the bitcast.
3001   if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
3002     Type *STy = BC->getSrcTy()->getPointerElementType(),
3003          *DTy = BC->getDestTy()->getPointerElementType();
3004     if (STy->isSized() && DTy->isSized() &&
3005         (DL.getTypeStoreSize(STy) >= DL.getTypeStoreSize(DTy)) &&
3006         (DL.getABITypeAlignment(STy) >= DL.getABITypeAlignment(DTy)))
3007       return isDereferenceableAndAlignedPointer(BC->getOperand(0), Align, DL,
3008                                                 CtxI, DT, TLI, Visited);
3009   }
3010
3011   // Global variables which can't collapse to null are ok.
3012   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
3013     if (!GV->hasExternalWeakLinkage())
3014       return isAligned(V, Align, DL);
3015
3016   // byval arguments are okay.
3017   if (const Argument *A = dyn_cast<Argument>(V))
3018     if (A->hasByValAttr())
3019       return isAligned(V, Align, DL);
3020
3021   if (isDereferenceableFromAttribute(V, DL, CtxI, DT, TLI))
3022     return isAligned(V, Align, DL);
3023
3024   // For GEPs, determine if the indexing lands within the allocated object.
3025   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3026     Type *VTy = GEP->getType();
3027     Type *Ty = VTy->getPointerElementType();
3028     const Value *Base = GEP->getPointerOperand();
3029
3030     // Conservatively require that the base pointer be fully dereferenceable
3031     // and aligned.
3032     if (!Visited.insert(Base).second)
3033       return false;
3034     if (!isDereferenceableAndAlignedPointer(Base, Align, DL, CtxI, DT, TLI,
3035                                             Visited))
3036       return false;
3037
3038     APInt Offset(DL.getPointerTypeSizeInBits(VTy), 0);
3039     if (!GEP->accumulateConstantOffset(DL, Offset))
3040       return false;
3041
3042     // Check if the load is within the bounds of the underlying object
3043     // and offset is aligned.
3044     uint64_t LoadSize = DL.getTypeStoreSize(Ty);
3045     Type *BaseType = Base->getType()->getPointerElementType();
3046     assert(isPowerOf2_32(Align) && "must be a power of 2!");
3047     return (Offset + LoadSize).ule(DL.getTypeAllocSize(BaseType)) && 
3048            !(Offset & APInt(Offset.getBitWidth(), Align-1));
3049   }
3050
3051   // For gc.relocate, look through relocations
3052   if (const IntrinsicInst *I = dyn_cast<IntrinsicInst>(V))
3053     if (I->getIntrinsicID() == Intrinsic::experimental_gc_relocate) {
3054       GCRelocateOperands RelocateInst(I);
3055       return isDereferenceableAndAlignedPointer(
3056           RelocateInst.getDerivedPtr(), Align, DL, CtxI, DT, TLI, Visited);
3057     }
3058
3059   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
3060     return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Align, DL,
3061                                               CtxI, DT, TLI, Visited);
3062
3063   // If we don't know, assume the worst.
3064   return false;
3065 }
3066
3067 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
3068                                               const DataLayout &DL,
3069                                               const Instruction *CtxI,
3070                                               const DominatorTree *DT,
3071                                               const TargetLibraryInfo *TLI) {
3072   // When dereferenceability information is provided by a dereferenceable
3073   // attribute, we know exactly how many bytes are dereferenceable. If we can
3074   // determine the exact offset to the attributed variable, we can use that
3075   // information here.
3076   Type *VTy = V->getType();
3077   Type *Ty = VTy->getPointerElementType();
3078
3079   // Require ABI alignment for loads without alignment specification
3080   if (Align == 0)
3081     Align = DL.getABITypeAlignment(Ty);
3082
3083   if (Ty->isSized()) {
3084     APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
3085     const Value *BV = V->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
3086
3087     if (Offset.isNonNegative())
3088       if (isDereferenceableFromAttribute(BV, Offset, Ty, DL, CtxI, DT, TLI) &&
3089           isAligned(BV, Offset, Align, DL))
3090         return true;
3091   }
3092
3093   SmallPtrSet<const Value *, 32> Visited;
3094   return ::isDereferenceableAndAlignedPointer(V, Align, DL, CtxI, DT, TLI,
3095                                               Visited);
3096 }
3097
3098 bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL,
3099                                     const Instruction *CtxI,
3100                                     const DominatorTree *DT,
3101                                     const TargetLibraryInfo *TLI) {
3102   return isDereferenceableAndAlignedPointer(V, 1, DL, CtxI, DT, TLI);
3103 }
3104
3105 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3106                                         const Instruction *CtxI,
3107                                         const DominatorTree *DT,
3108                                         const TargetLibraryInfo *TLI) {
3109   const Operator *Inst = dyn_cast<Operator>(V);
3110   if (!Inst)
3111     return false;
3112
3113   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3114     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3115       if (C->canTrap())
3116         return false;
3117
3118   switch (Inst->getOpcode()) {
3119   default:
3120     return true;
3121   case Instruction::UDiv:
3122   case Instruction::URem: {
3123     // x / y is undefined if y == 0.
3124     const APInt *V;
3125     if (match(Inst->getOperand(1), m_APInt(V)))
3126       return *V != 0;
3127     return false;
3128   }
3129   case Instruction::SDiv:
3130   case Instruction::SRem: {
3131     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
3132     const APInt *Numerator, *Denominator;
3133     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3134       return false;
3135     // We cannot hoist this division if the denominator is 0.
3136     if (*Denominator == 0)
3137       return false;
3138     // It's safe to hoist if the denominator is not 0 or -1.
3139     if (*Denominator != -1)
3140       return true;
3141     // At this point we know that the denominator is -1.  It is safe to hoist as
3142     // long we know that the numerator is not INT_MIN.
3143     if (match(Inst->getOperand(0), m_APInt(Numerator)))
3144       return !Numerator->isMinSignedValue();
3145     // The numerator *might* be MinSignedValue.
3146     return false;
3147   }
3148   case Instruction::Load: {
3149     const LoadInst *LI = cast<LoadInst>(Inst);
3150     if (!LI->isUnordered() ||
3151         // Speculative load may create a race that did not exist in the source.
3152         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
3153       return false;
3154     const DataLayout &DL = LI->getModule()->getDataLayout();
3155     return isDereferenceableAndAlignedPointer(
3156         LI->getPointerOperand(), LI->getAlignment(), DL, CtxI, DT, TLI);
3157   }
3158   case Instruction::Call: {
3159     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3160       switch (II->getIntrinsicID()) {
3161       // These synthetic intrinsics have no side-effects and just mark
3162       // information about their operands.
3163       // FIXME: There are other no-op synthetic instructions that potentially
3164       // should be considered at least *safe* to speculate...
3165       case Intrinsic::dbg_declare:
3166       case Intrinsic::dbg_value:
3167         return true;
3168
3169       case Intrinsic::bswap:
3170       case Intrinsic::ctlz:
3171       case Intrinsic::ctpop:
3172       case Intrinsic::cttz:
3173       case Intrinsic::objectsize:
3174       case Intrinsic::sadd_with_overflow:
3175       case Intrinsic::smul_with_overflow:
3176       case Intrinsic::ssub_with_overflow:
3177       case Intrinsic::uadd_with_overflow:
3178       case Intrinsic::umul_with_overflow:
3179       case Intrinsic::usub_with_overflow:
3180         return true;
3181       // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
3182       // errno like libm sqrt would.
3183       case Intrinsic::sqrt:
3184       case Intrinsic::fma:
3185       case Intrinsic::fmuladd:
3186       case Intrinsic::fabs:
3187       case Intrinsic::minnum:
3188       case Intrinsic::maxnum:
3189         return true;
3190       // TODO: some fp intrinsics are marked as having the same error handling
3191       // as libm. They're safe to speculate when they won't error.
3192       // TODO: are convert_{from,to}_fp16 safe?
3193       // TODO: can we list target-specific intrinsics here?
3194       default: break;
3195       }
3196     }
3197     return false; // The called function could have undefined behavior or
3198                   // side-effects, even if marked readnone nounwind.
3199   }
3200   case Instruction::VAArg:
3201   case Instruction::Alloca:
3202   case Instruction::Invoke:
3203   case Instruction::PHI:
3204   case Instruction::Store:
3205   case Instruction::Ret:
3206   case Instruction::Br:
3207   case Instruction::IndirectBr:
3208   case Instruction::Switch:
3209   case Instruction::Unreachable:
3210   case Instruction::Fence:
3211   case Instruction::AtomicRMW:
3212   case Instruction::AtomicCmpXchg:
3213   case Instruction::LandingPad:
3214   case Instruction::Resume:
3215   case Instruction::CatchPad:
3216   case Instruction::CatchEndPad:
3217   case Instruction::CatchRet:
3218   case Instruction::CleanupPad:
3219   case Instruction::CleanupEndPad:
3220   case Instruction::CleanupRet:
3221   case Instruction::TerminatePad:
3222     return false; // Misc instructions which have effects
3223   }
3224 }
3225
3226 bool llvm::mayBeMemoryDependent(const Instruction &I) {
3227   return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3228 }
3229
3230 /// Return true if we know that the specified value is never null.
3231 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
3232   assert(V->getType()->isPointerTy() && "V must be pointer type");
3233
3234   // Alloca never returns null, malloc might.
3235   if (isa<AllocaInst>(V)) return true;
3236
3237   // A byval, inalloca, or nonnull argument is never null.
3238   if (const Argument *A = dyn_cast<Argument>(V))
3239     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
3240
3241   // A global variable in address space 0 is non null unless extern weak.
3242   // Other address spaces may have null as a valid address for a global,
3243   // so we can't assume anything.
3244   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
3245     return !GV->hasExternalWeakLinkage() &&
3246            GV->getType()->getAddressSpace() == 0;
3247
3248   // A Load tagged w/nonnull metadata is never null. 
3249   if (const LoadInst *LI = dyn_cast<LoadInst>(V))
3250     return LI->getMetadata(LLVMContext::MD_nonnull);
3251
3252   if (auto CS = ImmutableCallSite(V))
3253     if (CS.isReturnNonNull())
3254       return true;
3255
3256   // operator new never returns null.
3257   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
3258     return true;
3259
3260   return false;
3261 }
3262
3263 static bool isKnownNonNullFromDominatingCondition(const Value *V,
3264                                                   const Instruction *CtxI,
3265                                                   const DominatorTree *DT) {
3266   assert(V->getType()->isPointerTy() && "V must be pointer type");
3267
3268   unsigned NumUsesExplored = 0;
3269   for (auto U : V->users()) {
3270     // Avoid massive lists
3271     if (NumUsesExplored >= DomConditionsMaxUses)
3272       break;
3273     NumUsesExplored++;
3274     // Consider only compare instructions uniquely controlling a branch
3275     const ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
3276     if (!Cmp)
3277       continue;
3278
3279     if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
3280       continue;
3281
3282     for (auto *CmpU : Cmp->users()) {
3283       const BranchInst *BI = dyn_cast<BranchInst>(CmpU);
3284       if (!BI)
3285         continue;
3286       
3287       assert(BI->isConditional() && "uses a comparison!");
3288
3289       BasicBlock *NonNullSuccessor = nullptr;
3290       CmpInst::Predicate Pred;
3291
3292       if (match(const_cast<ICmpInst*>(Cmp),
3293                 m_c_ICmp(Pred, m_Specific(V), m_Zero()))) {
3294         if (Pred == ICmpInst::ICMP_EQ)
3295           NonNullSuccessor = BI->getSuccessor(1);
3296         else if (Pred == ICmpInst::ICMP_NE)
3297           NonNullSuccessor = BI->getSuccessor(0);
3298       }
3299
3300       if (NonNullSuccessor) {
3301         BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3302         if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3303           return true;
3304       }
3305     }
3306   }
3307
3308   return false;
3309 }
3310
3311 bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
3312                    const DominatorTree *DT, const TargetLibraryInfo *TLI) {
3313   if (isKnownNonNull(V, TLI))
3314     return true;
3315
3316   return CtxI ? ::isKnownNonNullFromDominatingCondition(V, CtxI, DT) : false;
3317 }
3318
3319 OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
3320                                                    const DataLayout &DL,
3321                                                    AssumptionCache *AC,
3322                                                    const Instruction *CxtI,
3323                                                    const DominatorTree *DT) {
3324   // Multiplying n * m significant bits yields a result of n + m significant
3325   // bits. If the total number of significant bits does not exceed the
3326   // result bit width (minus 1), there is no overflow.
3327   // This means if we have enough leading zero bits in the operands
3328   // we can guarantee that the result does not overflow.
3329   // Ref: "Hacker's Delight" by Henry Warren
3330   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3331   APInt LHSKnownZero(BitWidth, 0);
3332   APInt LHSKnownOne(BitWidth, 0);
3333   APInt RHSKnownZero(BitWidth, 0);
3334   APInt RHSKnownOne(BitWidth, 0);
3335   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3336                    DT);
3337   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3338                    DT);
3339   // Note that underestimating the number of zero bits gives a more
3340   // conservative answer.
3341   unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
3342                       RHSKnownZero.countLeadingOnes();
3343   // First handle the easy case: if we have enough zero bits there's
3344   // definitely no overflow.
3345   if (ZeroBits >= BitWidth)
3346     return OverflowResult::NeverOverflows;
3347
3348   // Get the largest possible values for each operand.
3349   APInt LHSMax = ~LHSKnownZero;
3350   APInt RHSMax = ~RHSKnownZero;
3351
3352   // We know the multiply operation doesn't overflow if the maximum values for
3353   // each operand will not overflow after we multiply them together.
3354   bool MaxOverflow;
3355   LHSMax.umul_ov(RHSMax, MaxOverflow);
3356   if (!MaxOverflow)
3357     return OverflowResult::NeverOverflows;
3358
3359   // We know it always overflows if multiplying the smallest possible values for
3360   // the operands also results in overflow.
3361   bool MinOverflow;
3362   LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
3363   if (MinOverflow)
3364     return OverflowResult::AlwaysOverflows;
3365
3366   return OverflowResult::MayOverflow;
3367 }
3368
3369 OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
3370                                                    const DataLayout &DL,
3371                                                    AssumptionCache *AC,
3372                                                    const Instruction *CxtI,
3373                                                    const DominatorTree *DT) {
3374   bool LHSKnownNonNegative, LHSKnownNegative;
3375   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3376                  AC, CxtI, DT);
3377   if (LHSKnownNonNegative || LHSKnownNegative) {
3378     bool RHSKnownNonNegative, RHSKnownNegative;
3379     ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3380                    AC, CxtI, DT);
3381
3382     if (LHSKnownNegative && RHSKnownNegative) {
3383       // The sign bit is set in both cases: this MUST overflow.
3384       // Create a simple add instruction, and insert it into the struct.
3385       return OverflowResult::AlwaysOverflows;
3386     }
3387
3388     if (LHSKnownNonNegative && RHSKnownNonNegative) {
3389       // The sign bit is clear in both cases: this CANNOT overflow.
3390       // Create a simple add instruction, and insert it into the struct.
3391       return OverflowResult::NeverOverflows;
3392     }
3393   }
3394
3395   return OverflowResult::MayOverflow;
3396 }
3397
3398 static OverflowResult computeOverflowForSignedAdd(
3399     Value *LHS, Value *RHS, AddOperator *Add, const DataLayout &DL,
3400     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) {
3401   if (Add && Add->hasNoSignedWrap()) {
3402     return OverflowResult::NeverOverflows;
3403   }
3404
3405   bool LHSKnownNonNegative, LHSKnownNegative;
3406   bool RHSKnownNonNegative, RHSKnownNegative;
3407   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3408                  AC, CxtI, DT);
3409   ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3410                  AC, CxtI, DT);
3411
3412   if ((LHSKnownNonNegative && RHSKnownNegative) ||
3413       (LHSKnownNegative && RHSKnownNonNegative)) {
3414     // The sign bits are opposite: this CANNOT overflow.
3415     return OverflowResult::NeverOverflows;
3416   }
3417
3418   // The remaining code needs Add to be available. Early returns if not so.
3419   if (!Add)
3420     return OverflowResult::MayOverflow;
3421
3422   // If the sign of Add is the same as at least one of the operands, this add
3423   // CANNOT overflow. This is particularly useful when the sum is
3424   // @llvm.assume'ed non-negative rather than proved so from analyzing its
3425   // operands.
3426   bool LHSOrRHSKnownNonNegative =
3427       (LHSKnownNonNegative || RHSKnownNonNegative);
3428   bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative);
3429   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
3430     bool AddKnownNonNegative, AddKnownNegative;
3431     ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL,
3432                    /*Depth=*/0, AC, CxtI, DT);
3433     if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) ||
3434         (AddKnownNegative && LHSOrRHSKnownNegative)) {
3435       return OverflowResult::NeverOverflows;
3436     }
3437   }
3438
3439   return OverflowResult::MayOverflow;
3440 }
3441
3442 OverflowResult llvm::computeOverflowForSignedAdd(AddOperator *Add,
3443                                                  const DataLayout &DL,
3444                                                  AssumptionCache *AC,
3445                                                  const Instruction *CxtI,
3446                                                  const DominatorTree *DT) {
3447   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
3448                                        Add, DL, AC, CxtI, DT);
3449 }
3450
3451 OverflowResult llvm::computeOverflowForSignedAdd(Value *LHS, Value *RHS,
3452                                                  const DataLayout &DL,
3453                                                  AssumptionCache *AC,
3454                                                  const Instruction *CxtI,
3455                                                  const DominatorTree *DT) {
3456   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
3457 }
3458
3459 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
3460   // FIXME: This conservative implementation can be relaxed. E.g. most
3461   // atomic operations are guaranteed to terminate on most platforms
3462   // and most functions terminate.
3463
3464   return !I->isAtomic() &&       // atomics may never succeed on some platforms
3465          !isa<CallInst>(I) &&    // could throw and might not terminate
3466          !isa<InvokeInst>(I) &&  // might not terminate and could throw to
3467                                  //   non-successor (see bug 24185 for details).
3468          !isa<ResumeInst>(I) &&  // has no successors
3469          !isa<ReturnInst>(I);    // has no successors
3470 }
3471
3472 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3473                                                   const Loop *L) {
3474   // The loop header is guaranteed to be executed for every iteration.
3475   //
3476   // FIXME: Relax this constraint to cover all basic blocks that are
3477   // guaranteed to be executed at every iteration.
3478   if (I->getParent() != L->getHeader()) return false;
3479
3480   for (const Instruction &LI : *L->getHeader()) {
3481     if (&LI == I) return true;
3482     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3483   }
3484   llvm_unreachable("Instruction not contained in its own parent basic block.");
3485 }
3486
3487 bool llvm::propagatesFullPoison(const Instruction *I) {
3488   switch (I->getOpcode()) {
3489     case Instruction::Add:
3490     case Instruction::Sub:
3491     case Instruction::Xor:
3492     case Instruction::Trunc:
3493     case Instruction::BitCast:
3494     case Instruction::AddrSpaceCast:
3495       // These operations all propagate poison unconditionally. Note that poison
3496       // is not any particular value, so xor or subtraction of poison with
3497       // itself still yields poison, not zero.
3498       return true;
3499
3500     case Instruction::AShr:
3501     case Instruction::SExt:
3502       // For these operations, one bit of the input is replicated across
3503       // multiple output bits. A replicated poison bit is still poison.
3504       return true;
3505
3506     case Instruction::Shl: {
3507       // Left shift *by* a poison value is poison. The number of
3508       // positions to shift is unsigned, so no negative values are
3509       // possible there. Left shift by zero places preserves poison. So
3510       // it only remains to consider left shift of poison by a positive
3511       // number of places.
3512       //
3513       // A left shift by a positive number of places leaves the lowest order bit
3514       // non-poisoned. However, if such a shift has a no-wrap flag, then we can
3515       // make the poison operand violate that flag, yielding a fresh full-poison
3516       // value.
3517       auto *OBO = cast<OverflowingBinaryOperator>(I);
3518       return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
3519     }
3520
3521     case Instruction::Mul: {
3522       // A multiplication by zero yields a non-poison zero result, so we need to
3523       // rule out zero as an operand. Conservatively, multiplication by a
3524       // non-zero constant is not multiplication by zero.
3525       //
3526       // Multiplication by a non-zero constant can leave some bits
3527       // non-poisoned. For example, a multiplication by 2 leaves the lowest
3528       // order bit unpoisoned. So we need to consider that.
3529       //
3530       // Multiplication by 1 preserves poison. If the multiplication has a
3531       // no-wrap flag, then we can make the poison operand violate that flag
3532       // when multiplied by any integer other than 0 and 1.
3533       auto *OBO = cast<OverflowingBinaryOperator>(I);
3534       if (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) {
3535         for (Value *V : OBO->operands()) {
3536           if (auto *CI = dyn_cast<ConstantInt>(V)) {
3537             // A ConstantInt cannot yield poison, so we can assume that it is
3538             // the other operand that is poison.
3539             return !CI->isZero();
3540           }
3541         }
3542       }
3543       return false;
3544     }
3545
3546     case Instruction::GetElementPtr:
3547       // A GEP implicitly represents a sequence of additions, subtractions,
3548       // truncations, sign extensions and multiplications. The multiplications
3549       // are by the non-zero sizes of some set of types, so we do not have to be
3550       // concerned with multiplication by zero. If the GEP is in-bounds, then
3551       // these operations are implicitly no-signed-wrap so poison is propagated
3552       // by the arguments above for Add, Sub, Trunc, SExt and Mul.
3553       return cast<GEPOperator>(I)->isInBounds();
3554
3555     default:
3556       return false;
3557   }
3558 }
3559
3560 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3561   switch (I->getOpcode()) {
3562     case Instruction::Store:
3563       return cast<StoreInst>(I)->getPointerOperand();
3564
3565     case Instruction::Load:
3566       return cast<LoadInst>(I)->getPointerOperand();
3567
3568     case Instruction::AtomicCmpXchg:
3569       return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3570
3571     case Instruction::AtomicRMW:
3572       return cast<AtomicRMWInst>(I)->getPointerOperand();
3573
3574     case Instruction::UDiv:
3575     case Instruction::SDiv:
3576     case Instruction::URem:
3577     case Instruction::SRem:
3578       return I->getOperand(1);
3579
3580     default:
3581       return nullptr;
3582   }
3583 }
3584
3585 bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) {
3586   // We currently only look for uses of poison values within the same basic
3587   // block, as that makes it easier to guarantee that the uses will be
3588   // executed given that PoisonI is executed.
3589   //
3590   // FIXME: Expand this to consider uses beyond the same basic block. To do
3591   // this, look out for the distinction between post-dominance and strong
3592   // post-dominance.
3593   const BasicBlock *BB = PoisonI->getParent();
3594
3595   // Set of instructions that we have proved will yield poison if PoisonI
3596   // does.
3597   SmallSet<const Value *, 16> YieldsPoison;
3598   YieldsPoison.insert(PoisonI);
3599
3600   for (const Instruction *I = PoisonI, *E = BB->end(); I != E;
3601        I = I->getNextNode()) {
3602     if (I != PoisonI) {
3603       const Value *NotPoison = getGuaranteedNonFullPoisonOp(I);
3604       if (NotPoison != nullptr && YieldsPoison.count(NotPoison)) return true;
3605       if (!isGuaranteedToTransferExecutionToSuccessor(I)) return false;
3606     }
3607
3608     // Mark poison that propagates from I through uses of I.
3609     if (YieldsPoison.count(I)) {
3610       for (const User *User : I->users()) {
3611         const Instruction *UserI = cast<Instruction>(User);
3612         if (UserI->getParent() == BB && propagatesFullPoison(UserI))
3613           YieldsPoison.insert(User);
3614       }
3615     }
3616   }
3617   return false;
3618 }
3619
3620 static bool isKnownNonNaN(Value *V, FastMathFlags FMF) {
3621   if (FMF.noNaNs())
3622     return true;
3623
3624   if (auto *C = dyn_cast<ConstantFP>(V))
3625     return !C->isNaN();
3626   return false;
3627 }
3628
3629 static bool isKnownNonZero(Value *V) {
3630   if (auto *C = dyn_cast<ConstantFP>(V))
3631     return !C->isZero();
3632   return false;
3633 }
3634
3635 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
3636                                               FastMathFlags FMF,
3637                                               Value *CmpLHS, Value *CmpRHS,
3638                                               Value *TrueVal, Value *FalseVal,
3639                                               Value *&LHS, Value *&RHS) {
3640   LHS = CmpLHS;
3641   RHS = CmpRHS;
3642
3643   // If the predicate is an "or-equal"  (FP) predicate, then signed zeroes may
3644   // return inconsistent results between implementations.
3645   //   (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
3646   //   minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
3647   // Therefore we behave conservatively and only proceed if at least one of the
3648   // operands is known to not be zero, or if we don't care about signed zeroes.
3649   switch (Pred) {
3650   default: break;
3651   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
3652   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
3653     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
3654         !isKnownNonZero(CmpRHS))
3655       return {SPF_UNKNOWN, SPNB_NA, false};
3656   }
3657
3658   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
3659   bool Ordered = false;
3660
3661   // When given one NaN and one non-NaN input:
3662   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
3663   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
3664   //     ordered comparison fails), which could be NaN or non-NaN.
3665   // so here we discover exactly what NaN behavior is required/accepted.
3666   if (CmpInst::isFPPredicate(Pred)) {
3667     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
3668     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
3669
3670     if (LHSSafe && RHSSafe) {
3671       // Both operands are known non-NaN.
3672       NaNBehavior = SPNB_RETURNS_ANY;
3673     } else if (CmpInst::isOrdered(Pred)) {
3674       // An ordered comparison will return false when given a NaN, so it
3675       // returns the RHS.
3676       Ordered = true;
3677       if (LHSSafe)
3678         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
3679         NaNBehavior = SPNB_RETURNS_NAN;
3680       else if (RHSSafe)
3681         NaNBehavior = SPNB_RETURNS_OTHER;
3682       else
3683         // Completely unsafe.
3684         return {SPF_UNKNOWN, SPNB_NA, false};
3685     } else {
3686       Ordered = false;
3687       // An unordered comparison will return true when given a NaN, so it
3688       // returns the LHS.
3689       if (LHSSafe)
3690         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
3691         NaNBehavior = SPNB_RETURNS_OTHER;
3692       else if (RHSSafe)
3693         NaNBehavior = SPNB_RETURNS_NAN;
3694       else
3695         // Completely unsafe.
3696         return {SPF_UNKNOWN, SPNB_NA, false};
3697     }
3698   }
3699
3700   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
3701     std::swap(CmpLHS, CmpRHS);
3702     Pred = CmpInst::getSwappedPredicate(Pred);
3703     if (NaNBehavior == SPNB_RETURNS_NAN)
3704       NaNBehavior = SPNB_RETURNS_OTHER;
3705     else if (NaNBehavior == SPNB_RETURNS_OTHER)
3706       NaNBehavior = SPNB_RETURNS_NAN;
3707     Ordered = !Ordered;
3708   }
3709
3710   // ([if]cmp X, Y) ? X : Y
3711   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
3712     switch (Pred) {
3713     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
3714     case ICmpInst::ICMP_UGT:
3715     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
3716     case ICmpInst::ICMP_SGT:
3717     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
3718     case ICmpInst::ICMP_ULT:
3719     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
3720     case ICmpInst::ICMP_SLT:
3721     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
3722     case FCmpInst::FCMP_UGT:
3723     case FCmpInst::FCMP_UGE:
3724     case FCmpInst::FCMP_OGT:
3725     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
3726     case FCmpInst::FCMP_ULT:
3727     case FCmpInst::FCMP_ULE:
3728     case FCmpInst::FCMP_OLT:
3729     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
3730     }
3731   }
3732
3733   if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
3734     if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
3735         (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
3736
3737       // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
3738       // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
3739       if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
3740         return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
3741       }
3742
3743       // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
3744       // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
3745       if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
3746         return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
3747       }
3748     }
3749     
3750     // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
3751     if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
3752       if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
3753           (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
3754            match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
3755         LHS = TrueVal;
3756         RHS = FalseVal;
3757         return {SPF_SMIN, SPNB_NA, false};
3758       }
3759     }
3760   }
3761
3762   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
3763
3764   return {SPF_UNKNOWN, SPNB_NA, false};
3765 }
3766
3767 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
3768                               Instruction::CastOps *CastOp) {
3769   CastInst *CI = dyn_cast<CastInst>(V1);
3770   Constant *C = dyn_cast<Constant>(V2);
3771   CastInst *CI2 = dyn_cast<CastInst>(V2);
3772   if (!CI)
3773     return nullptr;
3774   *CastOp = CI->getOpcode();
3775
3776   if (CI2) {
3777     // If V1 and V2 are both the same cast from the same type, we can look
3778     // through V1.
3779     if (CI2->getOpcode() == CI->getOpcode() &&
3780         CI2->getSrcTy() == CI->getSrcTy())
3781       return CI2->getOperand(0);
3782     return nullptr;
3783   } else if (!C) {
3784     return nullptr;
3785   }
3786
3787   if (isa<SExtInst>(CI) && CmpI->isSigned()) {
3788     Constant *T = ConstantExpr::getTrunc(C, CI->getSrcTy());
3789     // This is only valid if the truncated value can be sign-extended
3790     // back to the original value.
3791     if (ConstantExpr::getSExt(T, C->getType()) == C)
3792       return T;
3793     return nullptr;
3794   }
3795   if (isa<ZExtInst>(CI) && CmpI->isUnsigned())
3796     return ConstantExpr::getTrunc(C, CI->getSrcTy());
3797
3798   if (isa<TruncInst>(CI))
3799     return ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
3800
3801   if (isa<FPToUIInst>(CI))
3802     return ConstantExpr::getUIToFP(C, CI->getSrcTy(), true);
3803
3804   if (isa<FPToSIInst>(CI))
3805     return ConstantExpr::getSIToFP(C, CI->getSrcTy(), true);
3806
3807   if (isa<UIToFPInst>(CI))
3808     return ConstantExpr::getFPToUI(C, CI->getSrcTy(), true);
3809
3810   if (isa<SIToFPInst>(CI))
3811     return ConstantExpr::getFPToSI(C, CI->getSrcTy(), true);
3812
3813   if (isa<FPTruncInst>(CI))
3814     return ConstantExpr::getFPExtend(C, CI->getSrcTy(), true);
3815
3816   if (isa<FPExtInst>(CI))
3817     return ConstantExpr::getFPTrunc(C, CI->getSrcTy(), true);
3818
3819   return nullptr;
3820 }
3821
3822 SelectPatternResult llvm::matchSelectPattern(Value *V,
3823                                              Value *&LHS, Value *&RHS,
3824                                              Instruction::CastOps *CastOp) {
3825   SelectInst *SI = dyn_cast<SelectInst>(V);
3826   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
3827
3828   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
3829   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
3830
3831   CmpInst::Predicate Pred = CmpI->getPredicate();
3832   Value *CmpLHS = CmpI->getOperand(0);
3833   Value *CmpRHS = CmpI->getOperand(1);
3834   Value *TrueVal = SI->getTrueValue();
3835   Value *FalseVal = SI->getFalseValue();
3836   FastMathFlags FMF;
3837   if (isa<FPMathOperator>(CmpI))
3838     FMF = CmpI->getFastMathFlags();
3839
3840   // Bail out early.
3841   if (CmpI->isEquality())
3842     return {SPF_UNKNOWN, SPNB_NA, false};
3843
3844   // Deal with type mismatches.
3845   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
3846     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
3847       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
3848                                   cast<CastInst>(TrueVal)->getOperand(0), C,
3849                                   LHS, RHS);
3850     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
3851       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
3852                                   C, cast<CastInst>(FalseVal)->getOperand(0),
3853                                   LHS, RHS);
3854   }
3855   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
3856                               LHS, RHS);
3857 }