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