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