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