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