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