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