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