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