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