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