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