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