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