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