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