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