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