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