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