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