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