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