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