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->getParent() || !II->getFunction() ||
1689             !II->getFunction()->hasFnAttribute(Attribute::VScaleRange))
1690           break;
1691 
1692         auto VScaleRange = II->getFunction()
1693                                ->getFnAttribute(Attribute::VScaleRange)
1694                                .getVScaleRangeArgs();
1695 
1696         if (VScaleRange.second == 0)
1697           break;
1698 
1699         // If vscale min = max then we know the exact value at compile time
1700         // and hence we know the exact bits.
1701         if (VScaleRange.first == VScaleRange.second) {
1702           Known.One = VScaleRange.first;
1703           Known.Zero = VScaleRange.first;
1704           Known.Zero.flipAllBits();
1705           break;
1706         }
1707 
1708         unsigned FirstZeroHighBit = 32 - countLeadingZeros(VScaleRange.second);
1709         if (FirstZeroHighBit < BitWidth)
1710           Known.Zero.setBitsFrom(FirstZeroHighBit);
1711 
1712         break;
1713       }
1714       }
1715     }
1716     break;
1717   case Instruction::ShuffleVector: {
1718     auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
1719     // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
1720     if (!Shuf) {
1721       Known.resetAll();
1722       return;
1723     }
1724     // For undef elements, we don't know anything about the common state of
1725     // the shuffle result.
1726     APInt DemandedLHS, DemandedRHS;
1727     if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
1728       Known.resetAll();
1729       return;
1730     }
1731     Known.One.setAllBits();
1732     Known.Zero.setAllBits();
1733     if (!!DemandedLHS) {
1734       const Value *LHS = Shuf->getOperand(0);
1735       computeKnownBits(LHS, DemandedLHS, Known, Depth + 1, Q);
1736       // If we don't know any bits, early out.
1737       if (Known.isUnknown())
1738         break;
1739     }
1740     if (!!DemandedRHS) {
1741       const Value *RHS = Shuf->getOperand(1);
1742       computeKnownBits(RHS, DemandedRHS, Known2, Depth + 1, Q);
1743       Known = KnownBits::commonBits(Known, Known2);
1744     }
1745     break;
1746   }
1747   case Instruction::InsertElement: {
1748     const Value *Vec = I->getOperand(0);
1749     const Value *Elt = I->getOperand(1);
1750     auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
1751     // Early out if the index is non-constant or out-of-range.
1752     unsigned NumElts = DemandedElts.getBitWidth();
1753     if (!CIdx || CIdx->getValue().uge(NumElts)) {
1754       Known.resetAll();
1755       return;
1756     }
1757     Known.One.setAllBits();
1758     Known.Zero.setAllBits();
1759     unsigned EltIdx = CIdx->getZExtValue();
1760     // Do we demand the inserted element?
1761     if (DemandedElts[EltIdx]) {
1762       computeKnownBits(Elt, Known, Depth + 1, Q);
1763       // If we don't know any bits, early out.
1764       if (Known.isUnknown())
1765         break;
1766     }
1767     // We don't need the base vector element that has been inserted.
1768     APInt DemandedVecElts = DemandedElts;
1769     DemandedVecElts.clearBit(EltIdx);
1770     if (!!DemandedVecElts) {
1771       computeKnownBits(Vec, DemandedVecElts, Known2, Depth + 1, Q);
1772       Known = KnownBits::commonBits(Known, Known2);
1773     }
1774     break;
1775   }
1776   case Instruction::ExtractElement: {
1777     // Look through extract element. If the index is non-constant or
1778     // out-of-range demand all elements, otherwise just the extracted element.
1779     const Value *Vec = I->getOperand(0);
1780     const Value *Idx = I->getOperand(1);
1781     auto *CIdx = dyn_cast<ConstantInt>(Idx);
1782     if (isa<ScalableVectorType>(Vec->getType())) {
1783       // FIXME: there's probably *something* we can do with scalable vectors
1784       Known.resetAll();
1785       break;
1786     }
1787     unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1788     APInt DemandedVecElts = APInt::getAllOnes(NumElts);
1789     if (CIdx && CIdx->getValue().ult(NumElts))
1790       DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
1791     computeKnownBits(Vec, DemandedVecElts, Known, Depth + 1, Q);
1792     break;
1793   }
1794   case Instruction::ExtractValue:
1795     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1796       const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1797       if (EVI->getNumIndices() != 1) break;
1798       if (EVI->getIndices()[0] == 0) {
1799         switch (II->getIntrinsicID()) {
1800         default: break;
1801         case Intrinsic::uadd_with_overflow:
1802         case Intrinsic::sadd_with_overflow:
1803           computeKnownBitsAddSub(true, II->getArgOperand(0),
1804                                  II->getArgOperand(1), false, DemandedElts,
1805                                  Known, Known2, Depth, Q);
1806           break;
1807         case Intrinsic::usub_with_overflow:
1808         case Intrinsic::ssub_with_overflow:
1809           computeKnownBitsAddSub(false, II->getArgOperand(0),
1810                                  II->getArgOperand(1), false, DemandedElts,
1811                                  Known, Known2, Depth, Q);
1812           break;
1813         case Intrinsic::umul_with_overflow:
1814         case Intrinsic::smul_with_overflow:
1815           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1816                               DemandedElts, Known, Known2, Depth, Q);
1817           break;
1818         }
1819       }
1820     }
1821     break;
1822   case Instruction::Freeze:
1823     if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
1824                                   Depth + 1))
1825       computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1826     break;
1827   }
1828 }
1829 
1830 /// Determine which bits of V are known to be either zero or one and return
1831 /// them.
1832 KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
1833                            unsigned Depth, const Query &Q) {
1834   KnownBits Known(getBitWidth(V->getType(), Q.DL));
1835   computeKnownBits(V, DemandedElts, Known, Depth, Q);
1836   return Known;
1837 }
1838 
1839 /// Determine which bits of V are known to be either zero or one and return
1840 /// them.
1841 KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1842   KnownBits Known(getBitWidth(V->getType(), Q.DL));
1843   computeKnownBits(V, Known, Depth, Q);
1844   return Known;
1845 }
1846 
1847 /// Determine which bits of V are known to be either zero or one and return
1848 /// them in the Known bit set.
1849 ///
1850 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
1851 /// we cannot optimize based on the assumption that it is zero without changing
1852 /// it to be an explicit zero.  If we don't change it to zero, other code could
1853 /// optimized based on the contradictory assumption that it is non-zero.
1854 /// Because instcombine aggressively folds operations with undef args anyway,
1855 /// this won't lose us code quality.
1856 ///
1857 /// This function is defined on values with integer type, values with pointer
1858 /// type, and vectors of integers.  In the case
1859 /// where V is a vector, known zero, and known one values are the
1860 /// same width as the vector element, and the bit is set only if it is true
1861 /// for all of the demanded elements in the vector specified by DemandedElts.
1862 void computeKnownBits(const Value *V, const APInt &DemandedElts,
1863                       KnownBits &Known, unsigned Depth, const Query &Q) {
1864   if (!DemandedElts || isa<ScalableVectorType>(V->getType())) {
1865     // No demanded elts or V is a scalable vector, better to assume we don't
1866     // know anything.
1867     Known.resetAll();
1868     return;
1869   }
1870 
1871   assert(V && "No Value?");
1872   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1873 
1874 #ifndef NDEBUG
1875   Type *Ty = V->getType();
1876   unsigned BitWidth = Known.getBitWidth();
1877 
1878   assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
1879          "Not integer or pointer type!");
1880 
1881   if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
1882     assert(
1883         FVTy->getNumElements() == DemandedElts.getBitWidth() &&
1884         "DemandedElt width should equal the fixed vector number of elements");
1885   } else {
1886     assert(DemandedElts == APInt(1, 1) &&
1887            "DemandedElt width should be 1 for scalars");
1888   }
1889 
1890   Type *ScalarTy = Ty->getScalarType();
1891   if (ScalarTy->isPointerTy()) {
1892     assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
1893            "V and Known should have same BitWidth");
1894   } else {
1895     assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
1896            "V and Known should have same BitWidth");
1897   }
1898 #endif
1899 
1900   const APInt *C;
1901   if (match(V, m_APInt(C))) {
1902     // We know all of the bits for a scalar constant or a splat vector constant!
1903     Known = KnownBits::makeConstant(*C);
1904     return;
1905   }
1906   // Null and aggregate-zero are all-zeros.
1907   if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1908     Known.setAllZero();
1909     return;
1910   }
1911   // Handle a constant vector by taking the intersection of the known bits of
1912   // each element.
1913   if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
1914     // We know that CDV must be a vector of integers. Take the intersection of
1915     // each element.
1916     Known.Zero.setAllBits(); Known.One.setAllBits();
1917     for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
1918       if (!DemandedElts[i])
1919         continue;
1920       APInt Elt = CDV->getElementAsAPInt(i);
1921       Known.Zero &= ~Elt;
1922       Known.One &= Elt;
1923     }
1924     return;
1925   }
1926 
1927   if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1928     // We know that CV must be a vector of integers. Take the intersection of
1929     // each element.
1930     Known.Zero.setAllBits(); Known.One.setAllBits();
1931     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1932       if (!DemandedElts[i])
1933         continue;
1934       Constant *Element = CV->getAggregateElement(i);
1935       auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1936       if (!ElementCI) {
1937         Known.resetAll();
1938         return;
1939       }
1940       const APInt &Elt = ElementCI->getValue();
1941       Known.Zero &= ~Elt;
1942       Known.One &= Elt;
1943     }
1944     return;
1945   }
1946 
1947   // Start out not knowing anything.
1948   Known.resetAll();
1949 
1950   // We can't imply anything about undefs.
1951   if (isa<UndefValue>(V))
1952     return;
1953 
1954   // There's no point in looking through other users of ConstantData for
1955   // assumptions.  Confirm that we've handled them all.
1956   assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1957 
1958   // All recursive calls that increase depth must come after this.
1959   if (Depth == MaxAnalysisRecursionDepth)
1960     return;
1961 
1962   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1963   // the bits of its aliasee.
1964   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1965     if (!GA->isInterposable())
1966       computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
1967     return;
1968   }
1969 
1970   if (const Operator *I = dyn_cast<Operator>(V))
1971     computeKnownBitsFromOperator(I, DemandedElts, Known, Depth, Q);
1972 
1973   // Aligned pointers have trailing zeros - refine Known.Zero set
1974   if (isa<PointerType>(V->getType())) {
1975     Align Alignment = V->getPointerAlignment(Q.DL);
1976     Known.Zero.setLowBits(Log2(Alignment));
1977   }
1978 
1979   // computeKnownBitsFromAssume strictly refines Known.
1980   // Therefore, we run them after computeKnownBitsFromOperator.
1981 
1982   // Check whether a nearby assume intrinsic can determine some known bits.
1983   computeKnownBitsFromAssume(V, Known, Depth, Q);
1984 
1985   assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
1986 }
1987 
1988 /// Return true if the given value is known to have exactly one
1989 /// bit set when defined. For vectors return true if every element is known to
1990 /// be a power of two when defined. Supports values with integer or pointer
1991 /// types and vectors of integers.
1992 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
1993                             const Query &Q) {
1994   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1995 
1996   // Attempt to match against constants.
1997   if (OrZero && match(V, m_Power2OrZero()))
1998       return true;
1999   if (match(V, m_Power2()))
2000       return true;
2001 
2002   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
2003   // it is shifted off the end then the result is undefined.
2004   if (match(V, m_Shl(m_One(), m_Value())))
2005     return true;
2006 
2007   // (signmask) >>l X is clearly a power of two if the one is not shifted off
2008   // the bottom.  If it is shifted off the bottom then the result is undefined.
2009   if (match(V, m_LShr(m_SignMask(), m_Value())))
2010     return true;
2011 
2012   // The remaining tests are all recursive, so bail out if we hit the limit.
2013   if (Depth++ == MaxAnalysisRecursionDepth)
2014     return false;
2015 
2016   Value *X = nullptr, *Y = nullptr;
2017   // A shift left or a logical shift right of a power of two is a power of two
2018   // or zero.
2019   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
2020                  match(V, m_LShr(m_Value(X), m_Value()))))
2021     return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
2022 
2023   if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
2024     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
2025 
2026   if (const SelectInst *SI = dyn_cast<SelectInst>(V))
2027     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
2028            isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
2029 
2030   // Peek through min/max.
2031   if (match(V, m_MaxOrMin(m_Value(X), m_Value(Y)))) {
2032     return isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q) &&
2033            isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q);
2034   }
2035 
2036   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
2037     // A power of two and'd with anything is a power of two or zero.
2038     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
2039         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
2040       return true;
2041     // X & (-X) is always a power of two or zero.
2042     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
2043       return true;
2044     return false;
2045   }
2046 
2047   // Adding a power-of-two or zero to the same power-of-two or zero yields
2048   // either the original power-of-two, a larger power-of-two or zero.
2049   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2050     const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
2051     if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2052         Q.IIQ.hasNoSignedWrap(VOBO)) {
2053       if (match(X, m_And(m_Specific(Y), m_Value())) ||
2054           match(X, m_And(m_Value(), m_Specific(Y))))
2055         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
2056           return true;
2057       if (match(Y, m_And(m_Specific(X), m_Value())) ||
2058           match(Y, m_And(m_Value(), m_Specific(X))))
2059         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
2060           return true;
2061 
2062       unsigned BitWidth = V->getType()->getScalarSizeInBits();
2063       KnownBits LHSBits(BitWidth);
2064       computeKnownBits(X, LHSBits, Depth, Q);
2065 
2066       KnownBits RHSBits(BitWidth);
2067       computeKnownBits(Y, RHSBits, Depth, Q);
2068       // If i8 V is a power of two or zero:
2069       //  ZeroBits: 1 1 1 0 1 1 1 1
2070       // ~ZeroBits: 0 0 0 1 0 0 0 0
2071       if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2072         // If OrZero isn't set, we cannot give back a zero result.
2073         // Make sure either the LHS or RHS has a bit set.
2074         if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2075           return true;
2076     }
2077   }
2078 
2079   // An exact divide or right shift can only shift off zero bits, so the result
2080   // is a power of two only if the first operand is a power of two and not
2081   // copying a sign bit (sdiv int_min, 2).
2082   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
2083       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
2084     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
2085                                   Depth, Q);
2086   }
2087 
2088   return false;
2089 }
2090 
2091 /// Test whether a GEP's result is known to be non-null.
2092 ///
2093 /// Uses properties inherent in a GEP to try to determine whether it is known
2094 /// to be non-null.
2095 ///
2096 /// Currently this routine does not support vector GEPs.
2097 static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
2098                               const Query &Q) {
2099   const Function *F = nullptr;
2100   if (const Instruction *I = dyn_cast<Instruction>(GEP))
2101     F = I->getFunction();
2102 
2103   if (!GEP->isInBounds() ||
2104       NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
2105     return false;
2106 
2107   // FIXME: Support vector-GEPs.
2108   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2109 
2110   // If the base pointer is non-null, we cannot walk to a null address with an
2111   // inbounds GEP in address space zero.
2112   if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
2113     return true;
2114 
2115   // Walk the GEP operands and see if any operand introduces a non-zero offset.
2116   // If so, then the GEP cannot produce a null pointer, as doing so would
2117   // inherently violate the inbounds contract within address space zero.
2118   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
2119        GTI != GTE; ++GTI) {
2120     // Struct types are easy -- they must always be indexed by a constant.
2121     if (StructType *STy = GTI.getStructTypeOrNull()) {
2122       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2123       unsigned ElementIdx = OpC->getZExtValue();
2124       const StructLayout *SL = Q.DL.getStructLayout(STy);
2125       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2126       if (ElementOffset > 0)
2127         return true;
2128       continue;
2129     }
2130 
2131     // If we have a zero-sized type, the index doesn't matter. Keep looping.
2132     if (Q.DL.getTypeAllocSize(GTI.getIndexedType()).getKnownMinSize() == 0)
2133       continue;
2134 
2135     // Fast path the constant operand case both for efficiency and so we don't
2136     // increment Depth when just zipping down an all-constant GEP.
2137     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2138       if (!OpC->isZero())
2139         return true;
2140       continue;
2141     }
2142 
2143     // We post-increment Depth here because while isKnownNonZero increments it
2144     // as well, when we pop back up that increment won't persist. We don't want
2145     // to recurse 10k times just because we have 10k GEP operands. We don't
2146     // bail completely out because we want to handle constant GEPs regardless
2147     // of depth.
2148     if (Depth++ >= MaxAnalysisRecursionDepth)
2149       continue;
2150 
2151     if (isKnownNonZero(GTI.getOperand(), Depth, Q))
2152       return true;
2153   }
2154 
2155   return false;
2156 }
2157 
2158 static bool isKnownNonNullFromDominatingCondition(const Value *V,
2159                                                   const Instruction *CtxI,
2160                                                   const DominatorTree *DT) {
2161   if (isa<Constant>(V))
2162     return false;
2163 
2164   if (!CtxI || !DT)
2165     return false;
2166 
2167   unsigned NumUsesExplored = 0;
2168   for (auto *U : V->users()) {
2169     // Avoid massive lists
2170     if (NumUsesExplored >= DomConditionsMaxUses)
2171       break;
2172     NumUsesExplored++;
2173 
2174     // If the value is used as an argument to a call or invoke, then argument
2175     // attributes may provide an answer about null-ness.
2176     if (const auto *CB = dyn_cast<CallBase>(U))
2177       if (auto *CalledFunc = CB->getCalledFunction())
2178         for (const Argument &Arg : CalledFunc->args())
2179           if (CB->getArgOperand(Arg.getArgNo()) == V &&
2180               Arg.hasNonNullAttr(/* AllowUndefOrPoison */ false) &&
2181               DT->dominates(CB, CtxI))
2182             return true;
2183 
2184     // If the value is used as a load/store, then the pointer must be non null.
2185     if (V == getLoadStorePointerOperand(U)) {
2186       const Instruction *I = cast<Instruction>(U);
2187       if (!NullPointerIsDefined(I->getFunction(),
2188                                 V->getType()->getPointerAddressSpace()) &&
2189           DT->dominates(I, CtxI))
2190         return true;
2191     }
2192 
2193     // Consider only compare instructions uniquely controlling a branch
2194     Value *RHS;
2195     CmpInst::Predicate Pred;
2196     if (!match(U, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2197       continue;
2198 
2199     bool NonNullIfTrue;
2200     if (cmpExcludesZero(Pred, RHS))
2201       NonNullIfTrue = true;
2202     else if (cmpExcludesZero(CmpInst::getInversePredicate(Pred), RHS))
2203       NonNullIfTrue = false;
2204     else
2205       continue;
2206 
2207     SmallVector<const User *, 4> WorkList;
2208     SmallPtrSet<const User *, 4> Visited;
2209     for (auto *CmpU : U->users()) {
2210       assert(WorkList.empty() && "Should be!");
2211       if (Visited.insert(CmpU).second)
2212         WorkList.push_back(CmpU);
2213 
2214       while (!WorkList.empty()) {
2215         auto *Curr = WorkList.pop_back_val();
2216 
2217         // If a user is an AND, add all its users to the work list. We only
2218         // propagate "pred != null" condition through AND because it is only
2219         // correct to assume that all conditions of AND are met in true branch.
2220         // TODO: Support similar logic of OR and EQ predicate?
2221         if (NonNullIfTrue)
2222           if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
2223             for (auto *CurrU : Curr->users())
2224               if (Visited.insert(CurrU).second)
2225                 WorkList.push_back(CurrU);
2226             continue;
2227           }
2228 
2229         if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
2230           assert(BI->isConditional() && "uses a comparison!");
2231 
2232           BasicBlock *NonNullSuccessor =
2233               BI->getSuccessor(NonNullIfTrue ? 0 : 1);
2234           BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
2235           if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
2236             return true;
2237         } else if (NonNullIfTrue && isGuard(Curr) &&
2238                    DT->dominates(cast<Instruction>(Curr), CtxI)) {
2239           return true;
2240         }
2241       }
2242     }
2243   }
2244 
2245   return false;
2246 }
2247 
2248 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
2249 /// ensure that the value it's attached to is never Value?  'RangeType' is
2250 /// is the type of the value described by the range.
2251 static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
2252   const unsigned NumRanges = Ranges->getNumOperands() / 2;
2253   assert(NumRanges >= 1);
2254   for (unsigned i = 0; i < NumRanges; ++i) {
2255     ConstantInt *Lower =
2256         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
2257     ConstantInt *Upper =
2258         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
2259     ConstantRange Range(Lower->getValue(), Upper->getValue());
2260     if (Range.contains(Value))
2261       return false;
2262   }
2263   return true;
2264 }
2265 
2266 /// Try to detect a recurrence that monotonically increases/decreases from a
2267 /// non-zero starting value. These are common as induction variables.
2268 static bool isNonZeroRecurrence(const PHINode *PN) {
2269   BinaryOperator *BO = nullptr;
2270   Value *Start = nullptr, *Step = nullptr;
2271   const APInt *StartC, *StepC;
2272   if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
2273       !match(Start, m_APInt(StartC)) || StartC->isNullValue())
2274     return false;
2275 
2276   switch (BO->getOpcode()) {
2277   case Instruction::Add:
2278     // Starting from non-zero and stepping away from zero can never wrap back
2279     // to zero.
2280     return BO->hasNoUnsignedWrap() ||
2281            (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
2282             StartC->isNegative() == StepC->isNegative());
2283   case Instruction::Mul:
2284     return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
2285            match(Step, m_APInt(StepC)) && !StepC->isNullValue();
2286   case Instruction::Shl:
2287     return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
2288   case Instruction::AShr:
2289   case Instruction::LShr:
2290     return BO->isExact();
2291   default:
2292     return false;
2293   }
2294 }
2295 
2296 /// Return true if the given value is known to be non-zero when defined. For
2297 /// vectors, return true if every demanded element is known to be non-zero when
2298 /// defined. For pointers, if the context instruction and dominator tree are
2299 /// specified, perform context-sensitive analysis and return true if the
2300 /// pointer couldn't possibly be null at the specified instruction.
2301 /// Supports values with integer or pointer type and vectors of integers.
2302 bool isKnownNonZero(const Value *V, const APInt &DemandedElts, unsigned Depth,
2303                     const Query &Q) {
2304   // FIXME: We currently have no way to represent the DemandedElts of a scalable
2305   // vector
2306   if (isa<ScalableVectorType>(V->getType()))
2307     return false;
2308 
2309   if (auto *C = dyn_cast<Constant>(V)) {
2310     if (C->isNullValue())
2311       return false;
2312     if (isa<ConstantInt>(C))
2313       // Must be non-zero due to null test above.
2314       return true;
2315 
2316     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2317       // See the comment for IntToPtr/PtrToInt instructions below.
2318       if (CE->getOpcode() == Instruction::IntToPtr ||
2319           CE->getOpcode() == Instruction::PtrToInt)
2320         if (Q.DL.getTypeSizeInBits(CE->getOperand(0)->getType())
2321                 .getFixedSize() <=
2322             Q.DL.getTypeSizeInBits(CE->getType()).getFixedSize())
2323           return isKnownNonZero(CE->getOperand(0), Depth, Q);
2324     }
2325 
2326     // For constant vectors, check that all elements are undefined or known
2327     // non-zero to determine that the whole vector is known non-zero.
2328     if (auto *VecTy = dyn_cast<FixedVectorType>(C->getType())) {
2329       for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2330         if (!DemandedElts[i])
2331           continue;
2332         Constant *Elt = C->getAggregateElement(i);
2333         if (!Elt || Elt->isNullValue())
2334           return false;
2335         if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2336           return false;
2337       }
2338       return true;
2339     }
2340 
2341     // A global variable in address space 0 is non null unless extern weak
2342     // or an absolute symbol reference. Other address spaces may have null as a
2343     // valid address for a global, so we can't assume anything.
2344     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2345       if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2346           GV->getType()->getAddressSpace() == 0)
2347         return true;
2348     } else
2349       return false;
2350   }
2351 
2352   if (auto *I = dyn_cast<Instruction>(V)) {
2353     if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
2354       // If the possible ranges don't contain zero, then the value is
2355       // definitely non-zero.
2356       if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
2357         const APInt ZeroValue(Ty->getBitWidth(), 0);
2358         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2359           return true;
2360       }
2361     }
2362   }
2363 
2364   if (isKnownNonZeroFromAssume(V, Q))
2365     return true;
2366 
2367   // Some of the tests below are recursive, so bail out if we hit the limit.
2368   if (Depth++ >= MaxAnalysisRecursionDepth)
2369     return false;
2370 
2371   // Check for pointer simplifications.
2372 
2373   if (PointerType *PtrTy = dyn_cast<PointerType>(V->getType())) {
2374     // Alloca never returns null, malloc might.
2375     if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2376       return true;
2377 
2378     // A byval, inalloca may not be null in a non-default addres space. A
2379     // nonnull argument is assumed never 0.
2380     if (const Argument *A = dyn_cast<Argument>(V)) {
2381       if (((A->hasPassPointeeByValueCopyAttr() &&
2382             !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
2383            A->hasNonNullAttr()))
2384         return true;
2385     }
2386 
2387     // A Load tagged with nonnull metadata is never null.
2388     if (const LoadInst *LI = dyn_cast<LoadInst>(V))
2389       if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
2390         return true;
2391 
2392     if (const auto *Call = dyn_cast<CallBase>(V)) {
2393       if (Call->isReturnNonNull())
2394         return true;
2395       if (const auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
2396         return isKnownNonZero(RP, Depth, Q);
2397     }
2398   }
2399 
2400   if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2401     return true;
2402 
2403   // Check for recursive pointer simplifications.
2404   if (V->getType()->isPointerTy()) {
2405     // Look through bitcast operations, GEPs, and int2ptr instructions as they
2406     // do not alter the value, or at least not the nullness property of the
2407     // value, e.g., int2ptr is allowed to zero/sign extend the value.
2408     //
2409     // Note that we have to take special care to avoid looking through
2410     // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2411     // as casts that can alter the value, e.g., AddrSpaceCasts.
2412     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
2413       return isGEPKnownNonNull(GEP, Depth, Q);
2414 
2415     if (auto *BCO = dyn_cast<BitCastOperator>(V))
2416       return isKnownNonZero(BCO->getOperand(0), Depth, Q);
2417 
2418     if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2419       if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()).getFixedSize() <=
2420           Q.DL.getTypeSizeInBits(I2P->getDestTy()).getFixedSize())
2421         return isKnownNonZero(I2P->getOperand(0), Depth, Q);
2422   }
2423 
2424   // Similar to int2ptr above, we can look through ptr2int here if the cast
2425   // is a no-op or an extend and not a truncate.
2426   if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2427     if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()).getFixedSize() <=
2428         Q.DL.getTypeSizeInBits(P2I->getDestTy()).getFixedSize())
2429       return isKnownNonZero(P2I->getOperand(0), Depth, Q);
2430 
2431   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
2432 
2433   // X | Y != 0 if X != 0 or Y != 0.
2434   Value *X = nullptr, *Y = nullptr;
2435   if (match(V, m_Or(m_Value(X), m_Value(Y))))
2436     return isKnownNonZero(X, DemandedElts, Depth, Q) ||
2437            isKnownNonZero(Y, DemandedElts, Depth, Q);
2438 
2439   // ext X != 0 if X != 0.
2440   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
2441     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
2442 
2443   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
2444   // if the lowest bit is shifted off the end.
2445   if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
2446     // shl nuw can't remove any non-zero bits.
2447     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2448     if (Q.IIQ.hasNoUnsignedWrap(BO))
2449       return isKnownNonZero(X, Depth, Q);
2450 
2451     KnownBits Known(BitWidth);
2452     computeKnownBits(X, DemandedElts, Known, Depth, Q);
2453     if (Known.One[0])
2454       return true;
2455   }
2456   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
2457   // defined if the sign bit is shifted off the end.
2458   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
2459     // shr exact can only shift out zero bits.
2460     const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
2461     if (BO->isExact())
2462       return isKnownNonZero(X, Depth, Q);
2463 
2464     KnownBits Known = computeKnownBits(X, DemandedElts, Depth, Q);
2465     if (Known.isNegative())
2466       return true;
2467 
2468     // If the shifter operand is a constant, and all of the bits shifted
2469     // out are known to be zero, and X is known non-zero then at least one
2470     // non-zero bit must remain.
2471     if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
2472       auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2473       // Is there a known one in the portion not shifted out?
2474       if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
2475         return true;
2476       // Are all the bits to be shifted out known zero?
2477       if (Known.countMinTrailingZeros() >= ShiftVal)
2478         return isKnownNonZero(X, DemandedElts, Depth, Q);
2479     }
2480   }
2481   // div exact can only produce a zero if the dividend is zero.
2482   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
2483     return isKnownNonZero(X, DemandedElts, Depth, Q);
2484   }
2485   // X + Y.
2486   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2487     KnownBits XKnown = computeKnownBits(X, DemandedElts, Depth, Q);
2488     KnownBits YKnown = computeKnownBits(Y, DemandedElts, Depth, Q);
2489 
2490     // If X and Y are both non-negative (as signed values) then their sum is not
2491     // zero unless both X and Y are zero.
2492     if (XKnown.isNonNegative() && YKnown.isNonNegative())
2493       if (isKnownNonZero(X, DemandedElts, Depth, Q) ||
2494           isKnownNonZero(Y, DemandedElts, Depth, Q))
2495         return true;
2496 
2497     // If X and Y are both negative (as signed values) then their sum is not
2498     // zero unless both X and Y equal INT_MIN.
2499     if (XKnown.isNegative() && YKnown.isNegative()) {
2500       APInt Mask = APInt::getSignedMaxValue(BitWidth);
2501       // The sign bit of X is set.  If some other bit is set then X is not equal
2502       // to INT_MIN.
2503       if (XKnown.One.intersects(Mask))
2504         return true;
2505       // The sign bit of Y is set.  If some other bit is set then Y is not equal
2506       // to INT_MIN.
2507       if (YKnown.One.intersects(Mask))
2508         return true;
2509     }
2510 
2511     // The sum of a non-negative number and a power of two is not zero.
2512     if (XKnown.isNonNegative() &&
2513         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
2514       return true;
2515     if (YKnown.isNonNegative() &&
2516         isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
2517       return true;
2518   }
2519   // X * Y.
2520   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
2521     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2522     // If X and Y are non-zero then so is X * Y as long as the multiplication
2523     // does not overflow.
2524     if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
2525         isKnownNonZero(X, DemandedElts, Depth, Q) &&
2526         isKnownNonZero(Y, DemandedElts, Depth, Q))
2527       return true;
2528   }
2529   // (C ? X : Y) != 0 if X != 0 and Y != 0.
2530   else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
2531     if (isKnownNonZero(SI->getTrueValue(), DemandedElts, Depth, Q) &&
2532         isKnownNonZero(SI->getFalseValue(), DemandedElts, Depth, Q))
2533       return true;
2534   }
2535   // PHI
2536   else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
2537     if (Q.IIQ.UseInstrInfo && isNonZeroRecurrence(PN))
2538       return true;
2539 
2540     // Check if all incoming values are non-zero using recursion.
2541     Query RecQ = Q;
2542     unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2543     return llvm::all_of(PN->operands(), [&](const Use &U) {
2544       if (U.get() == PN)
2545         return true;
2546       RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2547       return isKnownNonZero(U.get(), DemandedElts, NewDepth, RecQ);
2548     });
2549   }
2550   // ExtractElement
2551   else if (const auto *EEI = dyn_cast<ExtractElementInst>(V)) {
2552     const Value *Vec = EEI->getVectorOperand();
2553     const Value *Idx = EEI->getIndexOperand();
2554     auto *CIdx = dyn_cast<ConstantInt>(Idx);
2555     if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
2556       unsigned NumElts = VecTy->getNumElements();
2557       APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2558       if (CIdx && CIdx->getValue().ult(NumElts))
2559         DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2560       return isKnownNonZero(Vec, DemandedVecElts, Depth, Q);
2561     }
2562   }
2563   // Freeze
2564   else if (const FreezeInst *FI = dyn_cast<FreezeInst>(V)) {
2565     auto *Op = FI->getOperand(0);
2566     if (isKnownNonZero(Op, Depth, Q) &&
2567         isGuaranteedNotToBePoison(Op, Q.AC, Q.CxtI, Q.DT, Depth))
2568       return true;
2569   }
2570 
2571   KnownBits Known(BitWidth);
2572   computeKnownBits(V, DemandedElts, Known, Depth, Q);
2573   return Known.One != 0;
2574 }
2575 
2576 bool isKnownNonZero(const Value* V, unsigned Depth, const Query& Q) {
2577   // FIXME: We currently have no way to represent the DemandedElts of a scalable
2578   // vector
2579   if (isa<ScalableVectorType>(V->getType()))
2580     return false;
2581 
2582   auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
2583   APInt DemandedElts =
2584       FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
2585   return isKnownNonZero(V, DemandedElts, Depth, Q);
2586 }
2587 
2588 /// If the pair of operators are the same invertible function, return the
2589 /// the operands of the function corresponding to each input. Otherwise,
2590 /// return None.  An invertible function is one that is 1-to-1 and maps
2591 /// every input value to exactly one output value.  This is equivalent to
2592 /// saying that Op1 and Op2 are equal exactly when the specified pair of
2593 /// operands are equal, (except that Op1 and Op2 may be poison more often.)
2594 static Optional<std::pair<Value*, Value*>>
2595 getInvertibleOperands(const Operator *Op1,
2596                       const Operator *Op2) {
2597   if (Op1->getOpcode() != Op2->getOpcode())
2598     return None;
2599 
2600   auto getOperands = [&](unsigned OpNum) -> auto {
2601     return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
2602   };
2603 
2604   switch (Op1->getOpcode()) {
2605   default:
2606     break;
2607   case Instruction::Add:
2608   case Instruction::Sub:
2609     if (Op1->getOperand(0) == Op2->getOperand(0))
2610       return getOperands(1);
2611     if (Op1->getOperand(1) == Op2->getOperand(1))
2612       return getOperands(0);
2613     break;
2614   case Instruction::Mul: {
2615     // invertible if A * B == (A * B) mod 2^N where A, and B are integers
2616     // and N is the bitwdith.  The nsw case is non-obvious, but proven by
2617     // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
2618     auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2619     auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2620     if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2621         (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2622       break;
2623 
2624     // Assume operand order has been canonicalized
2625     if (Op1->getOperand(1) == Op2->getOperand(1) &&
2626         isa<ConstantInt>(Op1->getOperand(1)) &&
2627         !cast<ConstantInt>(Op1->getOperand(1))->isZero())
2628       return getOperands(0);
2629     break;
2630   }
2631   case Instruction::Shl: {
2632     // Same as multiplies, with the difference that we don't need to check
2633     // for a non-zero multiply. Shifts always multiply by non-zero.
2634     auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2635     auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2636     if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2637         (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2638       break;
2639 
2640     if (Op1->getOperand(1) == Op2->getOperand(1))
2641       return getOperands(0);
2642     break;
2643   }
2644   case Instruction::AShr:
2645   case Instruction::LShr: {
2646     auto *PEO1 = cast<PossiblyExactOperator>(Op1);
2647     auto *PEO2 = cast<PossiblyExactOperator>(Op2);
2648     if (!PEO1->isExact() || !PEO2->isExact())
2649       break;
2650 
2651     if (Op1->getOperand(1) == Op2->getOperand(1))
2652       return getOperands(0);
2653     break;
2654   }
2655   case Instruction::SExt:
2656   case Instruction::ZExt:
2657     if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
2658       return getOperands(0);
2659     break;
2660   case Instruction::PHI: {
2661     const PHINode *PN1 = cast<PHINode>(Op1);
2662     const PHINode *PN2 = cast<PHINode>(Op2);
2663 
2664     // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
2665     // are a single invertible function of the start values? Note that repeated
2666     // application of an invertible function is also invertible
2667     BinaryOperator *BO1 = nullptr;
2668     Value *Start1 = nullptr, *Step1 = nullptr;
2669     BinaryOperator *BO2 = nullptr;
2670     Value *Start2 = nullptr, *Step2 = nullptr;
2671     if (PN1->getParent() != PN2->getParent() ||
2672         !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
2673         !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
2674       break;
2675 
2676     auto Values = getInvertibleOperands(cast<Operator>(BO1),
2677                                         cast<Operator>(BO2));
2678     if (!Values)
2679        break;
2680 
2681     // We have to be careful of mutually defined recurrences here.  Ex:
2682     // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
2683     // * X_i = Y_i = X_(i-1) OP Y_(i-1)
2684     // The invertibility of these is complicated, and not worth reasoning
2685     // about (yet?).
2686     if (Values->first != PN1 || Values->second != PN2)
2687       break;
2688 
2689     return std::make_pair(Start1, Start2);
2690   }
2691   }
2692   return None;
2693 }
2694 
2695 /// Return true if V2 == V1 + X, where X is known non-zero.
2696 static bool isAddOfNonZero(const Value *V1, const Value *V2, unsigned Depth,
2697                            const Query &Q) {
2698   const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2699   if (!BO || BO->getOpcode() != Instruction::Add)
2700     return false;
2701   Value *Op = nullptr;
2702   if (V2 == BO->getOperand(0))
2703     Op = BO->getOperand(1);
2704   else if (V2 == BO->getOperand(1))
2705     Op = BO->getOperand(0);
2706   else
2707     return false;
2708   return isKnownNonZero(Op, Depth + 1, Q);
2709 }
2710 
2711 /// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
2712 /// the multiplication is nuw or nsw.
2713 static bool isNonEqualMul(const Value *V1, const Value *V2, unsigned Depth,
2714                           const Query &Q) {
2715   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2716     const APInt *C;
2717     return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
2718            (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2719            !C->isNullValue() && !C->isOneValue() &&
2720            isKnownNonZero(V1, Depth + 1, Q);
2721   }
2722   return false;
2723 }
2724 
2725 /// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
2726 /// the shift is nuw or nsw.
2727 static bool isNonEqualShl(const Value *V1, const Value *V2, unsigned Depth,
2728                           const Query &Q) {
2729   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2730     const APInt *C;
2731     return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
2732            (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2733            !C->isNullValue() && isKnownNonZero(V1, Depth + 1, Q);
2734   }
2735   return false;
2736 }
2737 
2738 static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
2739                            unsigned Depth, const Query &Q) {
2740   // Check two PHIs are in same block.
2741   if (PN1->getParent() != PN2->getParent())
2742     return false;
2743 
2744   SmallPtrSet<const BasicBlock *, 8> VisitedBBs;
2745   bool UsedFullRecursion = false;
2746   for (const BasicBlock *IncomBB : PN1->blocks()) {
2747     if (!VisitedBBs.insert(IncomBB).second)
2748       continue; // Don't reprocess blocks that we have dealt with already.
2749     const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
2750     const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
2751     const APInt *C1, *C2;
2752     if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
2753       continue;
2754 
2755     // Only one pair of phi operands is allowed for full recursion.
2756     if (UsedFullRecursion)
2757       return false;
2758 
2759     Query RecQ = Q;
2760     RecQ.CxtI = IncomBB->getTerminator();
2761     if (!isKnownNonEqual(IV1, IV2, Depth + 1, RecQ))
2762       return false;
2763     UsedFullRecursion = true;
2764   }
2765   return true;
2766 }
2767 
2768 /// Return true if it is known that V1 != V2.
2769 static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
2770                             const Query &Q) {
2771   if (V1 == V2)
2772     return false;
2773   if (V1->getType() != V2->getType())
2774     // We can't look through casts yet.
2775     return false;
2776 
2777   if (Depth >= MaxAnalysisRecursionDepth)
2778     return false;
2779 
2780   // See if we can recurse through (exactly one of) our operands.  This
2781   // requires our operation be 1-to-1 and map every input value to exactly
2782   // one output value.  Such an operation is invertible.
2783   auto *O1 = dyn_cast<Operator>(V1);
2784   auto *O2 = dyn_cast<Operator>(V2);
2785   if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
2786     if (auto Values = getInvertibleOperands(O1, O2))
2787       return isKnownNonEqual(Values->first, Values->second, Depth + 1, Q);
2788 
2789     if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
2790       const PHINode *PN2 = cast<PHINode>(V2);
2791       // FIXME: This is missing a generalization to handle the case where one is
2792       // a PHI and another one isn't.
2793       if (isNonEqualPHIs(PN1, PN2, Depth, Q))
2794         return true;
2795     };
2796   }
2797 
2798   if (isAddOfNonZero(V1, V2, Depth, Q) || isAddOfNonZero(V2, V1, Depth, Q))
2799     return true;
2800 
2801   if (isNonEqualMul(V1, V2, Depth, Q) || isNonEqualMul(V2, V1, Depth, Q))
2802     return true;
2803 
2804   if (isNonEqualShl(V1, V2, Depth, Q) || isNonEqualShl(V2, V1, Depth, Q))
2805     return true;
2806 
2807   if (V1->getType()->isIntOrIntVectorTy()) {
2808     // Are any known bits in V1 contradictory to known bits in V2? If V1
2809     // has a known zero where V2 has a known one, they must not be equal.
2810     KnownBits Known1 = computeKnownBits(V1, Depth, Q);
2811     KnownBits Known2 = computeKnownBits(V2, Depth, Q);
2812 
2813     if (Known1.Zero.intersects(Known2.One) ||
2814         Known2.Zero.intersects(Known1.One))
2815       return true;
2816   }
2817   return false;
2818 }
2819 
2820 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
2821 /// simplify operations downstream. Mask is known to be zero for bits that V
2822 /// cannot have.
2823 ///
2824 /// This function is defined on values with integer type, values with pointer
2825 /// type, and vectors of integers.  In the case
2826 /// where V is a vector, the mask, known zero, and known one values are the
2827 /// same width as the vector element, and the bit is set only if it is true
2828 /// for all of the elements in the vector.
2829 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
2830                        const Query &Q) {
2831   KnownBits Known(Mask.getBitWidth());
2832   computeKnownBits(V, Known, Depth, Q);
2833   return Mask.isSubsetOf(Known.Zero);
2834 }
2835 
2836 // Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2837 // Returns the input and lower/upper bounds.
2838 static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2839                                 const APInt *&CLow, const APInt *&CHigh) {
2840   assert(isa<Operator>(Select) &&
2841          cast<Operator>(Select)->getOpcode() == Instruction::Select &&
2842          "Input should be a Select!");
2843 
2844   const Value *LHS = nullptr, *RHS = nullptr;
2845   SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2846   if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2847     return false;
2848 
2849   if (!match(RHS, m_APInt(CLow)))
2850     return false;
2851 
2852   const Value *LHS2 = nullptr, *RHS2 = nullptr;
2853   SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2854   if (getInverseMinMaxFlavor(SPF) != SPF2)
2855     return false;
2856 
2857   if (!match(RHS2, m_APInt(CHigh)))
2858     return false;
2859 
2860   if (SPF == SPF_SMIN)
2861     std::swap(CLow, CHigh);
2862 
2863   In = LHS2;
2864   return CLow->sle(*CHigh);
2865 }
2866 
2867 /// For vector constants, loop over the elements and find the constant with the
2868 /// minimum number of sign bits. Return 0 if the value is not a vector constant
2869 /// or if any element was not analyzed; otherwise, return the count for the
2870 /// element with the minimum number of sign bits.
2871 static unsigned computeNumSignBitsVectorConstant(const Value *V,
2872                                                  const APInt &DemandedElts,
2873                                                  unsigned TyBits) {
2874   const auto *CV = dyn_cast<Constant>(V);
2875   if (!CV || !isa<FixedVectorType>(CV->getType()))
2876     return 0;
2877 
2878   unsigned MinSignBits = TyBits;
2879   unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
2880   for (unsigned i = 0; i != NumElts; ++i) {
2881     if (!DemandedElts[i])
2882       continue;
2883     // If we find a non-ConstantInt, bail out.
2884     auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2885     if (!Elt)
2886       return 0;
2887 
2888     MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
2889   }
2890 
2891   return MinSignBits;
2892 }
2893 
2894 static unsigned ComputeNumSignBitsImpl(const Value *V,
2895                                        const APInt &DemandedElts,
2896                                        unsigned Depth, const Query &Q);
2897 
2898 static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
2899                                    unsigned Depth, const Query &Q) {
2900   unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Depth, Q);
2901   assert(Result > 0 && "At least one sign bit needs to be present!");
2902   return Result;
2903 }
2904 
2905 /// Return the number of times the sign bit of the register is replicated into
2906 /// the other bits. We know that at least 1 bit is always equal to the sign bit
2907 /// (itself), but other cases can give us information. For example, immediately
2908 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2909 /// other, so we return 3. For vectors, return the number of sign bits for the
2910 /// vector element with the minimum number of known sign bits of the demanded
2911 /// elements in the vector specified by DemandedElts.
2912 static unsigned ComputeNumSignBitsImpl(const Value *V,
2913                                        const APInt &DemandedElts,
2914                                        unsigned Depth, const Query &Q) {
2915   Type *Ty = V->getType();
2916 
2917   // FIXME: We currently have no way to represent the DemandedElts of a scalable
2918   // vector
2919   if (isa<ScalableVectorType>(Ty))
2920     return 1;
2921 
2922 #ifndef NDEBUG
2923   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2924 
2925   if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2926     assert(
2927         FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2928         "DemandedElt width should equal the fixed vector number of elements");
2929   } else {
2930     assert(DemandedElts == APInt(1, 1) &&
2931            "DemandedElt width should be 1 for scalars");
2932   }
2933 #endif
2934 
2935   // We return the minimum number of sign bits that are guaranteed to be present
2936   // in V, so for undef we have to conservatively return 1.  We don't have the
2937   // same behavior for poison though -- that's a FIXME today.
2938 
2939   Type *ScalarTy = Ty->getScalarType();
2940   unsigned TyBits = ScalarTy->isPointerTy() ?
2941     Q.DL.getPointerTypeSizeInBits(ScalarTy) :
2942     Q.DL.getTypeSizeInBits(ScalarTy);
2943 
2944   unsigned Tmp, Tmp2;
2945   unsigned FirstAnswer = 1;
2946 
2947   // Note that ConstantInt is handled by the general computeKnownBits case
2948   // below.
2949 
2950   if (Depth == MaxAnalysisRecursionDepth)
2951     return 1;
2952 
2953   if (auto *U = dyn_cast<Operator>(V)) {
2954     switch (Operator::getOpcode(V)) {
2955     default: break;
2956     case Instruction::SExt:
2957       Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2958       return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
2959 
2960     case Instruction::SDiv: {
2961       const APInt *Denominator;
2962       // sdiv X, C -> adds log(C) sign bits.
2963       if (match(U->getOperand(1), m_APInt(Denominator))) {
2964 
2965         // Ignore non-positive denominator.
2966         if (!Denominator->isStrictlyPositive())
2967           break;
2968 
2969         // Calculate the incoming numerator bits.
2970         unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2971 
2972         // Add floor(log(C)) bits to the numerator bits.
2973         return std::min(TyBits, NumBits + Denominator->logBase2());
2974       }
2975       break;
2976     }
2977 
2978     case Instruction::SRem: {
2979       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2980 
2981       const APInt *Denominator;
2982       // srem X, C -> we know that the result is within [-C+1,C) when C is a
2983       // positive constant.  This let us put a lower bound on the number of sign
2984       // bits.
2985       if (match(U->getOperand(1), m_APInt(Denominator))) {
2986 
2987         // Ignore non-positive denominator.
2988         if (Denominator->isStrictlyPositive()) {
2989           // Calculate the leading sign bit constraints by examining the
2990           // denominator.  Given that the denominator is positive, there are two
2991           // cases:
2992           //
2993           //  1. The numerator is positive. The result range is [0,C) and
2994           //     [0,C) u< (1 << ceilLogBase2(C)).
2995           //
2996           //  2. The numerator is negative. Then the result range is (-C,0] and
2997           //     integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2998           //
2999           // Thus a lower bound on the number of sign bits is `TyBits -
3000           // ceilLogBase2(C)`.
3001 
3002           unsigned ResBits = TyBits - Denominator->ceilLogBase2();
3003           Tmp = std::max(Tmp, ResBits);
3004         }
3005       }
3006       return Tmp;
3007     }
3008 
3009     case Instruction::AShr: {
3010       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3011       // ashr X, C   -> adds C sign bits.  Vectors too.
3012       const APInt *ShAmt;
3013       if (match(U->getOperand(1), m_APInt(ShAmt))) {
3014         if (ShAmt->uge(TyBits))
3015           break; // Bad shift.
3016         unsigned ShAmtLimited = ShAmt->getZExtValue();
3017         Tmp += ShAmtLimited;
3018         if (Tmp > TyBits) Tmp = TyBits;
3019       }
3020       return Tmp;
3021     }
3022     case Instruction::Shl: {
3023       const APInt *ShAmt;
3024       if (match(U->getOperand(1), m_APInt(ShAmt))) {
3025         // shl destroys sign bits.
3026         Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3027         if (ShAmt->uge(TyBits) ||   // Bad shift.
3028             ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
3029         Tmp2 = ShAmt->getZExtValue();
3030         return Tmp - Tmp2;
3031       }
3032       break;
3033     }
3034     case Instruction::And:
3035     case Instruction::Or:
3036     case Instruction::Xor: // NOT is handled here.
3037       // Logical binary ops preserve the number of sign bits at the worst.
3038       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3039       if (Tmp != 1) {
3040         Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3041         FirstAnswer = std::min(Tmp, Tmp2);
3042         // We computed what we know about the sign bits as our first
3043         // answer. Now proceed to the generic code that uses
3044         // computeKnownBits, and pick whichever answer is better.
3045       }
3046       break;
3047 
3048     case Instruction::Select: {
3049       // If we have a clamp pattern, we know that the number of sign bits will
3050       // be the minimum of the clamp min/max range.
3051       const Value *X;
3052       const APInt *CLow, *CHigh;
3053       if (isSignedMinMaxClamp(U, X, CLow, CHigh))
3054         return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
3055 
3056       Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3057       if (Tmp == 1) break;
3058       Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
3059       return std::min(Tmp, Tmp2);
3060     }
3061 
3062     case Instruction::Add:
3063       // Add can have at most one carry bit.  Thus we know that the output
3064       // is, at worst, one more bit than the inputs.
3065       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3066       if (Tmp == 1) break;
3067 
3068       // Special case decrementing a value (ADD X, -1):
3069       if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
3070         if (CRHS->isAllOnesValue()) {
3071           KnownBits Known(TyBits);
3072           computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
3073 
3074           // If the input is known to be 0 or 1, the output is 0/-1, which is
3075           // all sign bits set.
3076           if ((Known.Zero | 1).isAllOnesValue())
3077             return TyBits;
3078 
3079           // If we are subtracting one from a positive number, there is no carry
3080           // out of the result.
3081           if (Known.isNonNegative())
3082             return Tmp;
3083         }
3084 
3085       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3086       if (Tmp2 == 1) break;
3087       return std::min(Tmp, Tmp2) - 1;
3088 
3089     case Instruction::Sub:
3090       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3091       if (Tmp2 == 1) break;
3092 
3093       // Handle NEG.
3094       if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
3095         if (CLHS->isNullValue()) {
3096           KnownBits Known(TyBits);
3097           computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
3098           // If the input is known to be 0 or 1, the output is 0/-1, which is
3099           // all sign bits set.
3100           if ((Known.Zero | 1).isAllOnesValue())
3101             return TyBits;
3102 
3103           // If the input is known to be positive (the sign bit is known clear),
3104           // the output of the NEG has the same number of sign bits as the
3105           // input.
3106           if (Known.isNonNegative())
3107             return Tmp2;
3108 
3109           // Otherwise, we treat this like a SUB.
3110         }
3111 
3112       // Sub can have at most one carry bit.  Thus we know that the output
3113       // is, at worst, one more bit than the inputs.
3114       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3115       if (Tmp == 1) break;
3116       return std::min(Tmp, Tmp2) - 1;
3117 
3118     case Instruction::Mul: {
3119       // The output of the Mul can be at most twice the valid bits in the
3120       // inputs.
3121       unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3122       if (SignBitsOp0 == 1) break;
3123       unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3124       if (SignBitsOp1 == 1) break;
3125       unsigned OutValidBits =
3126           (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
3127       return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
3128     }
3129 
3130     case Instruction::PHI: {
3131       const PHINode *PN = cast<PHINode>(U);
3132       unsigned NumIncomingValues = PN->getNumIncomingValues();
3133       // Don't analyze large in-degree PHIs.
3134       if (NumIncomingValues > 4) break;
3135       // Unreachable blocks may have zero-operand PHI nodes.
3136       if (NumIncomingValues == 0) break;
3137 
3138       // Take the minimum of all incoming values.  This can't infinitely loop
3139       // because of our depth threshold.
3140       Query RecQ = Q;
3141       Tmp = TyBits;
3142       for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
3143         if (Tmp == 1) return Tmp;
3144         RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
3145         Tmp = std::min(
3146             Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, RecQ));
3147       }
3148       return Tmp;
3149     }
3150 
3151     case Instruction::Trunc:
3152       // FIXME: it's tricky to do anything useful for this, but it is an
3153       // important case for targets like X86.
3154       break;
3155 
3156     case Instruction::ExtractElement:
3157       // Look through extract element. At the moment we keep this simple and
3158       // skip tracking the specific element. But at least we might find
3159       // information valid for all elements of the vector (for example if vector
3160       // is sign extended, shifted, etc).
3161       return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3162 
3163     case Instruction::ShuffleVector: {
3164       // Collect the minimum number of sign bits that are shared by every vector
3165       // element referenced by the shuffle.
3166       auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
3167       if (!Shuf) {
3168         // FIXME: Add support for shufflevector constant expressions.
3169         return 1;
3170       }
3171       APInt DemandedLHS, DemandedRHS;
3172       // For undef elements, we don't know anything about the common state of
3173       // the shuffle result.
3174       if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3175         return 1;
3176       Tmp = std::numeric_limits<unsigned>::max();
3177       if (!!DemandedLHS) {
3178         const Value *LHS = Shuf->getOperand(0);
3179         Tmp = ComputeNumSignBits(LHS, DemandedLHS, Depth + 1, Q);
3180       }
3181       // If we don't know anything, early out and try computeKnownBits
3182       // fall-back.
3183       if (Tmp == 1)
3184         break;
3185       if (!!DemandedRHS) {
3186         const Value *RHS = Shuf->getOperand(1);
3187         Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Depth + 1, Q);
3188         Tmp = std::min(Tmp, Tmp2);
3189       }
3190       // If we don't know anything, early out and try computeKnownBits
3191       // fall-back.
3192       if (Tmp == 1)
3193         break;
3194       assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
3195       return Tmp;
3196     }
3197     case Instruction::Call: {
3198       if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
3199         switch (II->getIntrinsicID()) {
3200         default: break;
3201         case Intrinsic::abs:
3202           Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3203           if (Tmp == 1) break;
3204 
3205           // Absolute value reduces number of sign bits by at most 1.
3206           return Tmp - 1;
3207         }
3208       }
3209     }
3210     }
3211   }
3212 
3213   // Finally, if we can prove that the top bits of the result are 0's or 1's,
3214   // use this information.
3215 
3216   // If we can examine all elements of a vector constant successfully, we're
3217   // done (we can't do any better than that). If not, keep trying.
3218   if (unsigned VecSignBits =
3219           computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
3220     return VecSignBits;
3221 
3222   KnownBits Known(TyBits);
3223   computeKnownBits(V, DemandedElts, Known, Depth, Q);
3224 
3225   // If we know that the sign bit is either zero or one, determine the number of
3226   // identical bits in the top of the input value.
3227   return std::max(FirstAnswer, Known.countMinSignBits());
3228 }
3229 
3230 /// This function computes the integer multiple of Base that equals V.
3231 /// If successful, it returns true and returns the multiple in
3232 /// Multiple. If unsuccessful, it returns false. It looks
3233 /// through SExt instructions only if LookThroughSExt is true.
3234 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
3235                            bool LookThroughSExt, unsigned Depth) {
3236   assert(V && "No Value?");
3237   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3238   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
3239 
3240   Type *T = V->getType();
3241 
3242   ConstantInt *CI = dyn_cast<ConstantInt>(V);
3243 
3244   if (Base == 0)
3245     return false;
3246 
3247   if (Base == 1) {
3248     Multiple = V;
3249     return true;
3250   }
3251 
3252   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
3253   Constant *BaseVal = ConstantInt::get(T, Base);
3254   if (CO && CO == BaseVal) {
3255     // Multiple is 1.
3256     Multiple = ConstantInt::get(T, 1);
3257     return true;
3258   }
3259 
3260   if (CI && CI->getZExtValue() % Base == 0) {
3261     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
3262     return true;
3263   }
3264 
3265   if (Depth == MaxAnalysisRecursionDepth) return false;
3266 
3267   Operator *I = dyn_cast<Operator>(V);
3268   if (!I) return false;
3269 
3270   switch (I->getOpcode()) {
3271   default: break;
3272   case Instruction::SExt:
3273     if (!LookThroughSExt) return false;
3274     // otherwise fall through to ZExt
3275     LLVM_FALLTHROUGH;
3276   case Instruction::ZExt:
3277     return ComputeMultiple(I->getOperand(0), Base, Multiple,
3278                            LookThroughSExt, Depth+1);
3279   case Instruction::Shl:
3280   case Instruction::Mul: {
3281     Value *Op0 = I->getOperand(0);
3282     Value *Op1 = I->getOperand(1);
3283 
3284     if (I->getOpcode() == Instruction::Shl) {
3285       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
3286       if (!Op1CI) return false;
3287       // Turn Op0 << Op1 into Op0 * 2^Op1
3288       APInt Op1Int = Op1CI->getValue();
3289       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
3290       APInt API(Op1Int.getBitWidth(), 0);
3291       API.setBit(BitToSet);
3292       Op1 = ConstantInt::get(V->getContext(), API);
3293     }
3294 
3295     Value *Mul0 = nullptr;
3296     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
3297       if (Constant *Op1C = dyn_cast<Constant>(Op1))
3298         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
3299           if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() <
3300               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3301             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
3302           if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() >
3303               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3304             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
3305 
3306           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
3307           Multiple = ConstantExpr::getMul(MulC, Op1C);
3308           return true;
3309         }
3310 
3311       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
3312         if (Mul0CI->getValue() == 1) {
3313           // V == Base * Op1, so return Op1
3314           Multiple = Op1;
3315           return true;
3316         }
3317     }
3318 
3319     Value *Mul1 = nullptr;
3320     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
3321       if (Constant *Op0C = dyn_cast<Constant>(Op0))
3322         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
3323           if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() <
3324               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3325             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
3326           if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() >
3327               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3328             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
3329 
3330           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
3331           Multiple = ConstantExpr::getMul(MulC, Op0C);
3332           return true;
3333         }
3334 
3335       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
3336         if (Mul1CI->getValue() == 1) {
3337           // V == Base * Op0, so return Op0
3338           Multiple = Op0;
3339           return true;
3340         }
3341     }
3342   }
3343   }
3344 
3345   // We could not determine if V is a multiple of Base.
3346   return false;
3347 }
3348 
3349 Intrinsic::ID llvm::getIntrinsicForCallSite(const CallBase &CB,
3350                                             const TargetLibraryInfo *TLI) {
3351   const Function *F = CB.getCalledFunction();
3352   if (!F)
3353     return Intrinsic::not_intrinsic;
3354 
3355   if (F->isIntrinsic())
3356     return F->getIntrinsicID();
3357 
3358   // We are going to infer semantics of a library function based on mapping it
3359   // to an LLVM intrinsic. Check that the library function is available from
3360   // this callbase and in this environment.
3361   LibFunc Func;
3362   if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) ||
3363       !CB.onlyReadsMemory())
3364     return Intrinsic::not_intrinsic;
3365 
3366   switch (Func) {
3367   default:
3368     break;
3369   case LibFunc_sin:
3370   case LibFunc_sinf:
3371   case LibFunc_sinl:
3372     return Intrinsic::sin;
3373   case LibFunc_cos:
3374   case LibFunc_cosf:
3375   case LibFunc_cosl:
3376     return Intrinsic::cos;
3377   case LibFunc_exp:
3378   case LibFunc_expf:
3379   case LibFunc_expl:
3380     return Intrinsic::exp;
3381   case LibFunc_exp2:
3382   case LibFunc_exp2f:
3383   case LibFunc_exp2l:
3384     return Intrinsic::exp2;
3385   case LibFunc_log:
3386   case LibFunc_logf:
3387   case LibFunc_logl:
3388     return Intrinsic::log;
3389   case LibFunc_log10:
3390   case LibFunc_log10f:
3391   case LibFunc_log10l:
3392     return Intrinsic::log10;
3393   case LibFunc_log2:
3394   case LibFunc_log2f:
3395   case LibFunc_log2l:
3396     return Intrinsic::log2;
3397   case LibFunc_fabs:
3398   case LibFunc_fabsf:
3399   case LibFunc_fabsl:
3400     return Intrinsic::fabs;
3401   case LibFunc_fmin:
3402   case LibFunc_fminf:
3403   case LibFunc_fminl:
3404     return Intrinsic::minnum;
3405   case LibFunc_fmax:
3406   case LibFunc_fmaxf:
3407   case LibFunc_fmaxl:
3408     return Intrinsic::maxnum;
3409   case LibFunc_copysign:
3410   case LibFunc_copysignf:
3411   case LibFunc_copysignl:
3412     return Intrinsic::copysign;
3413   case LibFunc_floor:
3414   case LibFunc_floorf:
3415   case LibFunc_floorl:
3416     return Intrinsic::floor;
3417   case LibFunc_ceil:
3418   case LibFunc_ceilf:
3419   case LibFunc_ceill:
3420     return Intrinsic::ceil;
3421   case LibFunc_trunc:
3422   case LibFunc_truncf:
3423   case LibFunc_truncl:
3424     return Intrinsic::trunc;
3425   case LibFunc_rint:
3426   case LibFunc_rintf:
3427   case LibFunc_rintl:
3428     return Intrinsic::rint;
3429   case LibFunc_nearbyint:
3430   case LibFunc_nearbyintf:
3431   case LibFunc_nearbyintl:
3432     return Intrinsic::nearbyint;
3433   case LibFunc_round:
3434   case LibFunc_roundf:
3435   case LibFunc_roundl:
3436     return Intrinsic::round;
3437   case LibFunc_roundeven:
3438   case LibFunc_roundevenf:
3439   case LibFunc_roundevenl:
3440     return Intrinsic::roundeven;
3441   case LibFunc_pow:
3442   case LibFunc_powf:
3443   case LibFunc_powl:
3444     return Intrinsic::pow;
3445   case LibFunc_sqrt:
3446   case LibFunc_sqrtf:
3447   case LibFunc_sqrtl:
3448     return Intrinsic::sqrt;
3449   }
3450 
3451   return Intrinsic::not_intrinsic;
3452 }
3453 
3454 /// Return true if we can prove that the specified FP value is never equal to
3455 /// -0.0.
3456 /// NOTE: Do not check 'nsz' here because that fast-math-flag does not guarantee
3457 ///       that a value is not -0.0. It only guarantees that -0.0 may be treated
3458 ///       the same as +0.0 in floating-point ops.
3459 ///
3460 /// NOTE: this function will need to be revisited when we support non-default
3461 /// rounding modes!
3462 bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
3463                                 unsigned Depth) {
3464   if (auto *CFP = dyn_cast<ConstantFP>(V))
3465     return !CFP->getValueAPF().isNegZero();
3466 
3467   if (Depth == MaxAnalysisRecursionDepth)
3468     return false;
3469 
3470   auto *Op = dyn_cast<Operator>(V);
3471   if (!Op)
3472     return false;
3473 
3474   // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
3475   if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
3476     return true;
3477 
3478   // sitofp and uitofp turn into +0.0 for zero.
3479   if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
3480     return true;
3481 
3482   if (auto *Call = dyn_cast<CallInst>(Op)) {
3483     Intrinsic::ID IID = getIntrinsicForCallSite(*Call, TLI);
3484     switch (IID) {
3485     default:
3486       break;
3487     // sqrt(-0.0) = -0.0, no other negative results are possible.
3488     case Intrinsic::sqrt:
3489     case Intrinsic::canonicalize:
3490       return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
3491     // fabs(x) != -0.0
3492     case Intrinsic::fabs:
3493       return true;
3494     }
3495   }
3496 
3497   return false;
3498 }
3499 
3500 /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
3501 /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
3502 /// bit despite comparing equal.
3503 static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
3504                                             const TargetLibraryInfo *TLI,
3505                                             bool SignBitOnly,
3506                                             unsigned Depth) {
3507   // TODO: This function does not do the right thing when SignBitOnly is true
3508   // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
3509   // which flips the sign bits of NaNs.  See
3510   // https://llvm.org/bugs/show_bug.cgi?id=31702.
3511 
3512   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3513     return !CFP->getValueAPF().isNegative() ||
3514            (!SignBitOnly && CFP->getValueAPF().isZero());
3515   }
3516 
3517   // Handle vector of constants.
3518   if (auto *CV = dyn_cast<Constant>(V)) {
3519     if (auto *CVFVTy = dyn_cast<FixedVectorType>(CV->getType())) {
3520       unsigned NumElts = CVFVTy->getNumElements();
3521       for (unsigned i = 0; i != NumElts; ++i) {
3522         auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
3523         if (!CFP)
3524           return false;
3525         if (CFP->getValueAPF().isNegative() &&
3526             (SignBitOnly || !CFP->getValueAPF().isZero()))
3527           return false;
3528       }
3529 
3530       // All non-negative ConstantFPs.
3531       return true;
3532     }
3533   }
3534 
3535   if (Depth == MaxAnalysisRecursionDepth)
3536     return false;
3537 
3538   const Operator *I = dyn_cast<Operator>(V);
3539   if (!I)
3540     return false;
3541 
3542   switch (I->getOpcode()) {
3543   default:
3544     break;
3545   // Unsigned integers are always nonnegative.
3546   case Instruction::UIToFP:
3547     return true;
3548   case Instruction::FMul:
3549   case Instruction::FDiv:
3550     // X * X is always non-negative or a NaN.
3551     // X / X is always exactly 1.0 or a NaN.
3552     if (I->getOperand(0) == I->getOperand(1) &&
3553         (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
3554       return true;
3555 
3556     LLVM_FALLTHROUGH;
3557   case Instruction::FAdd:
3558   case Instruction::FRem:
3559     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3560                                            Depth + 1) &&
3561            cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3562                                            Depth + 1);
3563   case Instruction::Select:
3564     return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3565                                            Depth + 1) &&
3566            cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3567                                            Depth + 1);
3568   case Instruction::FPExt:
3569   case Instruction::FPTrunc:
3570     // Widening/narrowing never change sign.
3571     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3572                                            Depth + 1);
3573   case Instruction::ExtractElement:
3574     // Look through extract element. At the moment we keep this simple and skip
3575     // tracking the specific element. But at least we might find information
3576     // valid for all elements of the vector.
3577     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3578                                            Depth + 1);
3579   case Instruction::Call:
3580     const auto *CI = cast<CallInst>(I);
3581     Intrinsic::ID IID = getIntrinsicForCallSite(*CI, TLI);
3582     switch (IID) {
3583     default:
3584       break;
3585     case Intrinsic::maxnum: {
3586       Value *V0 = I->getOperand(0), *V1 = I->getOperand(1);
3587       auto isPositiveNum = [&](Value *V) {
3588         if (SignBitOnly) {
3589           // With SignBitOnly, this is tricky because the result of
3590           // maxnum(+0.0, -0.0) is unspecified. Just check if the operand is
3591           // a constant strictly greater than 0.0.
3592           const APFloat *C;
3593           return match(V, m_APFloat(C)) &&
3594                  *C > APFloat::getZero(C->getSemantics());
3595         }
3596 
3597         // -0.0 compares equal to 0.0, so if this operand is at least -0.0,
3598         // maxnum can't be ordered-less-than-zero.
3599         return isKnownNeverNaN(V, TLI) &&
3600                cannotBeOrderedLessThanZeroImpl(V, TLI, false, Depth + 1);
3601       };
3602 
3603       // TODO: This could be improved. We could also check that neither operand
3604       //       has its sign bit set (and at least 1 is not-NAN?).
3605       return isPositiveNum(V0) || isPositiveNum(V1);
3606     }
3607 
3608     case Intrinsic::maximum:
3609       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3610                                              Depth + 1) ||
3611              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3612                                              Depth + 1);
3613     case Intrinsic::minnum:
3614     case Intrinsic::minimum:
3615       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3616                                              Depth + 1) &&
3617              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3618                                              Depth + 1);
3619     case Intrinsic::exp:
3620     case Intrinsic::exp2:
3621     case Intrinsic::fabs:
3622       return true;
3623 
3624     case Intrinsic::sqrt:
3625       // sqrt(x) is always >= -0 or NaN.  Moreover, sqrt(x) == -0 iff x == -0.
3626       if (!SignBitOnly)
3627         return true;
3628       return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3629                                  CannotBeNegativeZero(CI->getOperand(0), TLI));
3630 
3631     case Intrinsic::powi:
3632       if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
3633         // powi(x,n) is non-negative if n is even.
3634         if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
3635           return true;
3636       }
3637       // TODO: This is not correct.  Given that exp is an integer, here are the
3638       // ways that pow can return a negative value:
3639       //
3640       //   pow(x, exp)    --> negative if exp is odd and x is negative.
3641       //   pow(-0, exp)   --> -inf if exp is negative odd.
3642       //   pow(-0, exp)   --> -0 if exp is positive odd.
3643       //   pow(-inf, exp) --> -0 if exp is negative odd.
3644       //   pow(-inf, exp) --> -inf if exp is positive odd.
3645       //
3646       // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3647       // but we must return false if x == -0.  Unfortunately we do not currently
3648       // have a way of expressing this constraint.  See details in
3649       // https://llvm.org/bugs/show_bug.cgi?id=31702.
3650       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3651                                              Depth + 1);
3652 
3653     case Intrinsic::fma:
3654     case Intrinsic::fmuladd:
3655       // x*x+y is non-negative if y is non-negative.
3656       return I->getOperand(0) == I->getOperand(1) &&
3657              (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3658              cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3659                                              Depth + 1);
3660     }
3661     break;
3662   }
3663   return false;
3664 }
3665 
3666 bool llvm::CannotBeOrderedLessThanZero(const Value *V,
3667                                        const TargetLibraryInfo *TLI) {
3668   return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3669 }
3670 
3671 bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3672   return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3673 }
3674 
3675 bool llvm::isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI,
3676                                 unsigned Depth) {
3677   assert(V->getType()->isFPOrFPVectorTy() && "Querying for Inf on non-FP type");
3678 
3679   // If we're told that infinities won't happen, assume they won't.
3680   if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3681     if (FPMathOp->hasNoInfs())
3682       return true;
3683 
3684   // Handle scalar constants.
3685   if (auto *CFP = dyn_cast<ConstantFP>(V))
3686     return !CFP->isInfinity();
3687 
3688   if (Depth == MaxAnalysisRecursionDepth)
3689     return false;
3690 
3691   if (auto *Inst = dyn_cast<Instruction>(V)) {
3692     switch (Inst->getOpcode()) {
3693     case Instruction::Select: {
3694       return isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1) &&
3695              isKnownNeverInfinity(Inst->getOperand(2), TLI, Depth + 1);
3696     }
3697     case Instruction::SIToFP:
3698     case Instruction::UIToFP: {
3699       // Get width of largest magnitude integer (remove a bit if signed).
3700       // This still works for a signed minimum value because the largest FP
3701       // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
3702       int IntSize = Inst->getOperand(0)->getType()->getScalarSizeInBits();
3703       if (Inst->getOpcode() == Instruction::SIToFP)
3704         --IntSize;
3705 
3706       // If the exponent of the largest finite FP value can hold the largest
3707       // integer, the result of the cast must be finite.
3708       Type *FPTy = Inst->getType()->getScalarType();
3709       return ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize;
3710     }
3711     default:
3712       break;
3713     }
3714   }
3715 
3716   // try to handle fixed width vector constants
3717   auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3718   if (VFVTy && isa<Constant>(V)) {
3719     // For vectors, verify that each element is not infinity.
3720     unsigned NumElts = VFVTy->getNumElements();
3721     for (unsigned i = 0; i != NumElts; ++i) {
3722       Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3723       if (!Elt)
3724         return false;
3725       if (isa<UndefValue>(Elt))
3726         continue;
3727       auto *CElt = dyn_cast<ConstantFP>(Elt);
3728       if (!CElt || CElt->isInfinity())
3729         return false;
3730     }
3731     // All elements were confirmed non-infinity or undefined.
3732     return true;
3733   }
3734 
3735   // was not able to prove that V never contains infinity
3736   return false;
3737 }
3738 
3739 bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3740                            unsigned Depth) {
3741   assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3742 
3743   // If we're told that NaNs won't happen, assume they won't.
3744   if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3745     if (FPMathOp->hasNoNaNs())
3746       return true;
3747 
3748   // Handle scalar constants.
3749   if (auto *CFP = dyn_cast<ConstantFP>(V))
3750     return !CFP->isNaN();
3751 
3752   if (Depth == MaxAnalysisRecursionDepth)
3753     return false;
3754 
3755   if (auto *Inst = dyn_cast<Instruction>(V)) {
3756     switch (Inst->getOpcode()) {
3757     case Instruction::FAdd:
3758     case Instruction::FSub:
3759       // Adding positive and negative infinity produces NaN.
3760       return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3761              isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3762              (isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) ||
3763               isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1));
3764 
3765     case Instruction::FMul:
3766       // Zero multiplied with infinity produces NaN.
3767       // FIXME: If neither side can be zero fmul never produces NaN.
3768       return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3769              isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) &&
3770              isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3771              isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1);
3772 
3773     case Instruction::FDiv:
3774     case Instruction::FRem:
3775       // FIXME: Only 0/0, Inf/Inf, Inf REM x and x REM 0 produce NaN.
3776       return false;
3777 
3778     case Instruction::Select: {
3779       return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3780              isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3781     }
3782     case Instruction::SIToFP:
3783     case Instruction::UIToFP:
3784       return true;
3785     case Instruction::FPTrunc:
3786     case Instruction::FPExt:
3787       return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3788     default:
3789       break;
3790     }
3791   }
3792 
3793   if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3794     switch (II->getIntrinsicID()) {
3795     case Intrinsic::canonicalize:
3796     case Intrinsic::fabs:
3797     case Intrinsic::copysign:
3798     case Intrinsic::exp:
3799     case Intrinsic::exp2:
3800     case Intrinsic::floor:
3801     case Intrinsic::ceil:
3802     case Intrinsic::trunc:
3803     case Intrinsic::rint:
3804     case Intrinsic::nearbyint:
3805     case Intrinsic::round:
3806     case Intrinsic::roundeven:
3807       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3808     case Intrinsic::sqrt:
3809       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3810              CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
3811     case Intrinsic::minnum:
3812     case Intrinsic::maxnum:
3813       // If either operand is not NaN, the result is not NaN.
3814       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
3815              isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
3816     default:
3817       return false;
3818     }
3819   }
3820 
3821   // Try to handle fixed width vector constants
3822   auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3823   if (VFVTy && isa<Constant>(V)) {
3824     // For vectors, verify that each element is not NaN.
3825     unsigned NumElts = VFVTy->getNumElements();
3826     for (unsigned i = 0; i != NumElts; ++i) {
3827       Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3828       if (!Elt)
3829         return false;
3830       if (isa<UndefValue>(Elt))
3831         continue;
3832       auto *CElt = dyn_cast<ConstantFP>(Elt);
3833       if (!CElt || CElt->isNaN())
3834         return false;
3835     }
3836     // All elements were confirmed not-NaN or undefined.
3837     return true;
3838   }
3839 
3840   // Was not able to prove that V never contains NaN
3841   return false;
3842 }
3843 
3844 Value *llvm::isBytewiseValue(Value *V, const DataLayout &DL) {
3845 
3846   // All byte-wide stores are splatable, even of arbitrary variables.
3847   if (V->getType()->isIntegerTy(8))
3848     return V;
3849 
3850   LLVMContext &Ctx = V->getContext();
3851 
3852   // Undef don't care.
3853   auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3854   if (isa<UndefValue>(V))
3855     return UndefInt8;
3856 
3857   // Return Undef for zero-sized type.
3858   if (!DL.getTypeStoreSize(V->getType()).isNonZero())
3859     return UndefInt8;
3860 
3861   Constant *C = dyn_cast<Constant>(V);
3862   if (!C) {
3863     // Conceptually, we could handle things like:
3864     //   %a = zext i8 %X to i16
3865     //   %b = shl i16 %a, 8
3866     //   %c = or i16 %a, %b
3867     // but until there is an example that actually needs this, it doesn't seem
3868     // worth worrying about.
3869     return nullptr;
3870   }
3871 
3872   // Handle 'null' ConstantArrayZero etc.
3873   if (C->isNullValue())
3874     return Constant::getNullValue(Type::getInt8Ty(Ctx));
3875 
3876   // Constant floating-point values can be handled as integer values if the
3877   // corresponding integer value is "byteable".  An important case is 0.0.
3878   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3879     Type *Ty = nullptr;
3880     if (CFP->getType()->isHalfTy())
3881       Ty = Type::getInt16Ty(Ctx);
3882     else if (CFP->getType()->isFloatTy())
3883       Ty = Type::getInt32Ty(Ctx);
3884     else if (CFP->getType()->isDoubleTy())
3885       Ty = Type::getInt64Ty(Ctx);
3886     // Don't handle long double formats, which have strange constraints.
3887     return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL)
3888               : nullptr;
3889   }
3890 
3891   // We can handle constant integers that are multiple of 8 bits.
3892   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
3893     if (CI->getBitWidth() % 8 == 0) {
3894       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
3895       if (!CI->getValue().isSplat(8))
3896         return nullptr;
3897       return ConstantInt::get(Ctx, CI->getValue().trunc(8));
3898     }
3899   }
3900 
3901   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
3902     if (CE->getOpcode() == Instruction::IntToPtr) {
3903       if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
3904         unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
3905         return isBytewiseValue(
3906             ConstantExpr::getIntegerCast(CE->getOperand(0),
3907                                          Type::getIntNTy(Ctx, BitWidth), false),
3908             DL);
3909       }
3910     }
3911   }
3912 
3913   auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3914     if (LHS == RHS)
3915       return LHS;
3916     if (!LHS || !RHS)
3917       return nullptr;
3918     if (LHS == UndefInt8)
3919       return RHS;
3920     if (RHS == UndefInt8)
3921       return LHS;
3922     return nullptr;
3923   };
3924 
3925   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3926     Value *Val = UndefInt8;
3927     for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
3928       if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
3929         return nullptr;
3930     return Val;
3931   }
3932 
3933   if (isa<ConstantAggregate>(C)) {
3934     Value *Val = UndefInt8;
3935     for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
3936       if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL))))
3937         return nullptr;
3938     return Val;
3939   }
3940 
3941   // Don't try to handle the handful of other constants.
3942   return nullptr;
3943 }
3944 
3945 // This is the recursive version of BuildSubAggregate. It takes a few different
3946 // arguments. Idxs is the index within the nested struct From that we are
3947 // looking at now (which is of type IndexedType). IdxSkip is the number of
3948 // indices from Idxs that should be left out when inserting into the resulting
3949 // struct. To is the result struct built so far, new insertvalue instructions
3950 // build on that.
3951 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
3952                                 SmallVectorImpl<unsigned> &Idxs,
3953                                 unsigned IdxSkip,
3954                                 Instruction *InsertBefore) {
3955   StructType *STy = dyn_cast<StructType>(IndexedType);
3956   if (STy) {
3957     // Save the original To argument so we can modify it
3958     Value *OrigTo = To;
3959     // General case, the type indexed by Idxs is a struct
3960     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3961       // Process each struct element recursively
3962       Idxs.push_back(i);
3963       Value *PrevTo = To;
3964       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
3965                              InsertBefore);
3966       Idxs.pop_back();
3967       if (!To) {
3968         // Couldn't find any inserted value for this index? Cleanup
3969         while (PrevTo != OrigTo) {
3970           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3971           PrevTo = Del->getAggregateOperand();
3972           Del->eraseFromParent();
3973         }
3974         // Stop processing elements
3975         break;
3976       }
3977     }
3978     // If we successfully found a value for each of our subaggregates
3979     if (To)
3980       return To;
3981   }
3982   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3983   // the struct's elements had a value that was inserted directly. In the latter
3984   // case, perhaps we can't determine each of the subelements individually, but
3985   // we might be able to find the complete struct somewhere.
3986 
3987   // Find the value that is at that particular spot
3988   Value *V = FindInsertedValue(From, Idxs);
3989 
3990   if (!V)
3991     return nullptr;
3992 
3993   // Insert the value in the new (sub) aggregate
3994   return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3995                                  "tmp", InsertBefore);
3996 }
3997 
3998 // This helper takes a nested struct and extracts a part of it (which is again a
3999 // struct) into a new value. For example, given the struct:
4000 // { a, { b, { c, d }, e } }
4001 // and the indices "1, 1" this returns
4002 // { c, d }.
4003 //
4004 // It does this by inserting an insertvalue for each element in the resulting
4005 // struct, as opposed to just inserting a single struct. This will only work if
4006 // each of the elements of the substruct are known (ie, inserted into From by an
4007 // insertvalue instruction somewhere).
4008 //
4009 // All inserted insertvalue instructions are inserted before InsertBefore
4010 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
4011                                 Instruction *InsertBefore) {
4012   assert(InsertBefore && "Must have someplace to insert!");
4013   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
4014                                                              idx_range);
4015   Value *To = UndefValue::get(IndexedType);
4016   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
4017   unsigned IdxSkip = Idxs.size();
4018 
4019   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
4020 }
4021 
4022 /// Given an aggregate and a sequence of indices, see if the scalar value
4023 /// indexed is already around as a register, for example if it was inserted
4024 /// directly into the aggregate.
4025 ///
4026 /// If InsertBefore is not null, this function will duplicate (modified)
4027 /// insertvalues when a part of a nested struct is extracted.
4028 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
4029                                Instruction *InsertBefore) {
4030   // Nothing to index? Just return V then (this is useful at the end of our
4031   // recursion).
4032   if (idx_range.empty())
4033     return V;
4034   // We have indices, so V should have an indexable type.
4035   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
4036          "Not looking at a struct or array?");
4037   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
4038          "Invalid indices for type?");
4039 
4040   if (Constant *C = dyn_cast<Constant>(V)) {
4041     C = C->getAggregateElement(idx_range[0]);
4042     if (!C) return nullptr;
4043     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
4044   }
4045 
4046   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
4047     // Loop the indices for the insertvalue instruction in parallel with the
4048     // requested indices
4049     const unsigned *req_idx = idx_range.begin();
4050     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
4051          i != e; ++i, ++req_idx) {
4052       if (req_idx == idx_range.end()) {
4053         // We can't handle this without inserting insertvalues
4054         if (!InsertBefore)
4055           return nullptr;
4056 
4057         // The requested index identifies a part of a nested aggregate. Handle
4058         // this specially. For example,
4059         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
4060         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
4061         // %C = extractvalue {i32, { i32, i32 } } %B, 1
4062         // This can be changed into
4063         // %A = insertvalue {i32, i32 } undef, i32 10, 0
4064         // %C = insertvalue {i32, i32 } %A, i32 11, 1
4065         // which allows the unused 0,0 element from the nested struct to be
4066         // removed.
4067         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
4068                                  InsertBefore);
4069       }
4070 
4071       // This insert value inserts something else than what we are looking for.
4072       // See if the (aggregate) value inserted into has the value we are
4073       // looking for, then.
4074       if (*req_idx != *i)
4075         return FindInsertedValue(I->getAggregateOperand(), idx_range,
4076                                  InsertBefore);
4077     }
4078     // If we end up here, the indices of the insertvalue match with those
4079     // requested (though possibly only partially). Now we recursively look at
4080     // the inserted value, passing any remaining indices.
4081     return FindInsertedValue(I->getInsertedValueOperand(),
4082                              makeArrayRef(req_idx, idx_range.end()),
4083                              InsertBefore);
4084   }
4085 
4086   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
4087     // If we're extracting a value from an aggregate that was extracted from
4088     // something else, we can extract from that something else directly instead.
4089     // However, we will need to chain I's indices with the requested indices.
4090 
4091     // Calculate the number of indices required
4092     unsigned size = I->getNumIndices() + idx_range.size();
4093     // Allocate some space to put the new indices in
4094     SmallVector<unsigned, 5> Idxs;
4095     Idxs.reserve(size);
4096     // Add indices from the extract value instruction
4097     Idxs.append(I->idx_begin(), I->idx_end());
4098 
4099     // Add requested indices
4100     Idxs.append(idx_range.begin(), idx_range.end());
4101 
4102     assert(Idxs.size() == size
4103            && "Number of indices added not correct?");
4104 
4105     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
4106   }
4107   // Otherwise, we don't know (such as, extracting from a function return value
4108   // or load instruction)
4109   return nullptr;
4110 }
4111 
4112 bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
4113                                        unsigned CharSize) {
4114   // Make sure the GEP has exactly three arguments.
4115   if (GEP->getNumOperands() != 3)
4116     return false;
4117 
4118   // Make sure the index-ee is a pointer to array of \p CharSize integers.
4119   // CharSize.
4120   ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
4121   if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
4122     return false;
4123 
4124   // Check to make sure that the first operand of the GEP is an integer and
4125   // has value 0 so that we are sure we're indexing into the initializer.
4126   const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
4127   if (!FirstIdx || !FirstIdx->isZero())
4128     return false;
4129 
4130   return true;
4131 }
4132 
4133 bool llvm::getConstantDataArrayInfo(const Value *V,
4134                                     ConstantDataArraySlice &Slice,
4135                                     unsigned ElementSize, uint64_t Offset) {
4136   assert(V);
4137 
4138   // Look through bitcast instructions and geps.
4139   V = V->stripPointerCasts();
4140 
4141   // If the value is a GEP instruction or constant expression, treat it as an
4142   // offset.
4143   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
4144     // The GEP operator should be based on a pointer to string constant, and is
4145     // indexing into the string constant.
4146     if (!isGEPBasedOnPointerToString(GEP, ElementSize))
4147       return false;
4148 
4149     // If the second index isn't a ConstantInt, then this is a variable index
4150     // into the array.  If this occurs, we can't say anything meaningful about
4151     // the string.
4152     uint64_t StartIdx = 0;
4153     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
4154       StartIdx = CI->getZExtValue();
4155     else
4156       return false;
4157     return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
4158                                     StartIdx + Offset);
4159   }
4160 
4161   // The GEP instruction, constant or instruction, must reference a global
4162   // variable that is a constant and is initialized. The referenced constant
4163   // initializer is the array that we'll use for optimization.
4164   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
4165   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
4166     return false;
4167 
4168   const ConstantDataArray *Array;
4169   ArrayType *ArrayTy;
4170   if (GV->getInitializer()->isNullValue()) {
4171     Type *GVTy = GV->getValueType();
4172     if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
4173       // A zeroinitializer for the array; there is no ConstantDataArray.
4174       Array = nullptr;
4175     } else {
4176       const DataLayout &DL = GV->getParent()->getDataLayout();
4177       uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedSize();
4178       uint64_t Length = SizeInBytes / (ElementSize / 8);
4179       if (Length <= Offset)
4180         return false;
4181 
4182       Slice.Array = nullptr;
4183       Slice.Offset = 0;
4184       Slice.Length = Length - Offset;
4185       return true;
4186     }
4187   } else {
4188     // This must be a ConstantDataArray.
4189     Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
4190     if (!Array)
4191       return false;
4192     ArrayTy = Array->getType();
4193   }
4194   if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
4195     return false;
4196 
4197   uint64_t NumElts = ArrayTy->getArrayNumElements();
4198   if (Offset > NumElts)
4199     return false;
4200 
4201   Slice.Array = Array;
4202   Slice.Offset = Offset;
4203   Slice.Length = NumElts - Offset;
4204   return true;
4205 }
4206 
4207 /// This function computes the length of a null-terminated C string pointed to
4208 /// by V. If successful, it returns true and returns the string in Str.
4209 /// If unsuccessful, it returns false.
4210 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
4211                                  uint64_t Offset, bool TrimAtNul) {
4212   ConstantDataArraySlice Slice;
4213   if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
4214     return false;
4215 
4216   if (Slice.Array == nullptr) {
4217     if (TrimAtNul) {
4218       Str = StringRef();
4219       return true;
4220     }
4221     if (Slice.Length == 1) {
4222       Str = StringRef("", 1);
4223       return true;
4224     }
4225     // We cannot instantiate a StringRef as we do not have an appropriate string
4226     // of 0s at hand.
4227     return false;
4228   }
4229 
4230   // Start out with the entire array in the StringRef.
4231   Str = Slice.Array->getAsString();
4232   // Skip over 'offset' bytes.
4233   Str = Str.substr(Slice.Offset);
4234 
4235   if (TrimAtNul) {
4236     // Trim off the \0 and anything after it.  If the array is not nul
4237     // terminated, we just return the whole end of string.  The client may know
4238     // some other way that the string is length-bound.
4239     Str = Str.substr(0, Str.find('\0'));
4240   }
4241   return true;
4242 }
4243 
4244 // These next two are very similar to the above, but also look through PHI
4245 // nodes.
4246 // TODO: See if we can integrate these two together.
4247 
4248 /// If we can compute the length of the string pointed to by
4249 /// the specified pointer, return 'len+1'.  If we can't, return 0.
4250 static uint64_t GetStringLengthH(const Value *V,
4251                                  SmallPtrSetImpl<const PHINode*> &PHIs,
4252                                  unsigned CharSize) {
4253   // Look through noop bitcast instructions.
4254   V = V->stripPointerCasts();
4255 
4256   // If this is a PHI node, there are two cases: either we have already seen it
4257   // or we haven't.
4258   if (const PHINode *PN = dyn_cast<PHINode>(V)) {
4259     if (!PHIs.insert(PN).second)
4260       return ~0ULL;  // already in the set.
4261 
4262     // If it was new, see if all the input strings are the same length.
4263     uint64_t LenSoFar = ~0ULL;
4264     for (Value *IncValue : PN->incoming_values()) {
4265       uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
4266       if (Len == 0) return 0; // Unknown length -> unknown.
4267 
4268       if (Len == ~0ULL) continue;
4269 
4270       if (Len != LenSoFar && LenSoFar != ~0ULL)
4271         return 0;    // Disagree -> unknown.
4272       LenSoFar = Len;
4273     }
4274 
4275     // Success, all agree.
4276     return LenSoFar;
4277   }
4278 
4279   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
4280   if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
4281     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
4282     if (Len1 == 0) return 0;
4283     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
4284     if (Len2 == 0) return 0;
4285     if (Len1 == ~0ULL) return Len2;
4286     if (Len2 == ~0ULL) return Len1;
4287     if (Len1 != Len2) return 0;
4288     return Len1;
4289   }
4290 
4291   // Otherwise, see if we can read the string.
4292   ConstantDataArraySlice Slice;
4293   if (!getConstantDataArrayInfo(V, Slice, CharSize))
4294     return 0;
4295 
4296   if (Slice.Array == nullptr)
4297     return 1;
4298 
4299   // Search for nul characters
4300   unsigned NullIndex = 0;
4301   for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
4302     if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
4303       break;
4304   }
4305 
4306   return NullIndex + 1;
4307 }
4308 
4309 /// If we can compute the length of the string pointed to by
4310 /// the specified pointer, return 'len+1'.  If we can't, return 0.
4311 uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
4312   if (!V->getType()->isPointerTy())
4313     return 0;
4314 
4315   SmallPtrSet<const PHINode*, 32> PHIs;
4316   uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
4317   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
4318   // an empty string as a length.
4319   return Len == ~0ULL ? 1 : Len;
4320 }
4321 
4322 const Value *
4323 llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call,
4324                                            bool MustPreserveNullness) {
4325   assert(Call &&
4326          "getArgumentAliasingToReturnedPointer only works on nonnull calls");
4327   if (const Value *RV = Call->getReturnedArgOperand())
4328     return RV;
4329   // This can be used only as a aliasing property.
4330   if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
4331           Call, MustPreserveNullness))
4332     return Call->getArgOperand(0);
4333   return nullptr;
4334 }
4335 
4336 bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
4337     const CallBase *Call, bool MustPreserveNullness) {
4338   switch (Call->getIntrinsicID()) {
4339   case Intrinsic::launder_invariant_group:
4340   case Intrinsic::strip_invariant_group:
4341   case Intrinsic::aarch64_irg:
4342   case Intrinsic::aarch64_tagp:
4343     return true;
4344   case Intrinsic::ptrmask:
4345     return !MustPreserveNullness;
4346   default:
4347     return false;
4348   }
4349 }
4350 
4351 /// \p PN defines a loop-variant pointer to an object.  Check if the
4352 /// previous iteration of the loop was referring to the same object as \p PN.
4353 static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
4354                                          const LoopInfo *LI) {
4355   // Find the loop-defined value.
4356   Loop *L = LI->getLoopFor(PN->getParent());
4357   if (PN->getNumIncomingValues() != 2)
4358     return true;
4359 
4360   // Find the value from previous iteration.
4361   auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
4362   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
4363     PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
4364   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
4365     return true;
4366 
4367   // If a new pointer is loaded in the loop, the pointer references a different
4368   // object in every iteration.  E.g.:
4369   //    for (i)
4370   //       int *p = a[i];
4371   //       ...
4372   if (auto *Load = dyn_cast<LoadInst>(PrevValue))
4373     if (!L->isLoopInvariant(Load->getPointerOperand()))
4374       return false;
4375   return true;
4376 }
4377 
4378 const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
4379   if (!V->getType()->isPointerTy())
4380     return V;
4381   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
4382     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
4383       V = GEP->getPointerOperand();
4384     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
4385                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
4386       V = cast<Operator>(V)->getOperand(0);
4387       if (!V->getType()->isPointerTy())
4388         return V;
4389     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
4390       if (GA->isInterposable())
4391         return V;
4392       V = GA->getAliasee();
4393     } else {
4394       if (auto *PHI = dyn_cast<PHINode>(V)) {
4395         // Look through single-arg phi nodes created by LCSSA.
4396         if (PHI->getNumIncomingValues() == 1) {
4397           V = PHI->getIncomingValue(0);
4398           continue;
4399         }
4400       } else if (auto *Call = dyn_cast<CallBase>(V)) {
4401         // CaptureTracking can know about special capturing properties of some
4402         // intrinsics like launder.invariant.group, that can't be expressed with
4403         // the attributes, but have properties like returning aliasing pointer.
4404         // Because some analysis may assume that nocaptured pointer is not
4405         // returned from some special intrinsic (because function would have to
4406         // be marked with returns attribute), it is crucial to use this function
4407         // because it should be in sync with CaptureTracking. Not using it may
4408         // cause weird miscompilations where 2 aliasing pointers are assumed to
4409         // noalias.
4410         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
4411           V = RP;
4412           continue;
4413         }
4414       }
4415 
4416       return V;
4417     }
4418     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
4419   }
4420   return V;
4421 }
4422 
4423 void llvm::getUnderlyingObjects(const Value *V,
4424                                 SmallVectorImpl<const Value *> &Objects,
4425                                 LoopInfo *LI, unsigned MaxLookup) {
4426   SmallPtrSet<const Value *, 4> Visited;
4427   SmallVector<const Value *, 4> Worklist;
4428   Worklist.push_back(V);
4429   do {
4430     const Value *P = Worklist.pop_back_val();
4431     P = getUnderlyingObject(P, MaxLookup);
4432 
4433     if (!Visited.insert(P).second)
4434       continue;
4435 
4436     if (auto *SI = dyn_cast<SelectInst>(P)) {
4437       Worklist.push_back(SI->getTrueValue());
4438       Worklist.push_back(SI->getFalseValue());
4439       continue;
4440     }
4441 
4442     if (auto *PN = dyn_cast<PHINode>(P)) {
4443       // If this PHI changes the underlying object in every iteration of the
4444       // loop, don't look through it.  Consider:
4445       //   int **A;
4446       //   for (i) {
4447       //     Prev = Curr;     // Prev = PHI (Prev_0, Curr)
4448       //     Curr = A[i];
4449       //     *Prev, *Curr;
4450       //
4451       // Prev is tracking Curr one iteration behind so they refer to different
4452       // underlying objects.
4453       if (!LI || !LI->isLoopHeader(PN->getParent()) ||
4454           isSameUnderlyingObjectInLoop(PN, LI))
4455         append_range(Worklist, PN->incoming_values());
4456       continue;
4457     }
4458 
4459     Objects.push_back(P);
4460   } while (!Worklist.empty());
4461 }
4462 
4463 /// This is the function that does the work of looking through basic
4464 /// ptrtoint+arithmetic+inttoptr sequences.
4465 static const Value *getUnderlyingObjectFromInt(const Value *V) {
4466   do {
4467     if (const Operator *U = dyn_cast<Operator>(V)) {
4468       // If we find a ptrtoint, we can transfer control back to the
4469       // regular getUnderlyingObjectFromInt.
4470       if (U->getOpcode() == Instruction::PtrToInt)
4471         return U->getOperand(0);
4472       // If we find an add of a constant, a multiplied value, or a phi, it's
4473       // likely that the other operand will lead us to the base
4474       // object. We don't have to worry about the case where the
4475       // object address is somehow being computed by the multiply,
4476       // because our callers only care when the result is an
4477       // identifiable object.
4478       if (U->getOpcode() != Instruction::Add ||
4479           (!isa<ConstantInt>(U->getOperand(1)) &&
4480            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
4481            !isa<PHINode>(U->getOperand(1))))
4482         return V;
4483       V = U->getOperand(0);
4484     } else {
4485       return V;
4486     }
4487     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
4488   } while (true);
4489 }
4490 
4491 /// This is a wrapper around getUnderlyingObjects and adds support for basic
4492 /// ptrtoint+arithmetic+inttoptr sequences.
4493 /// It returns false if unidentified object is found in getUnderlyingObjects.
4494 bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
4495                                           SmallVectorImpl<Value *> &Objects) {
4496   SmallPtrSet<const Value *, 16> Visited;
4497   SmallVector<const Value *, 4> Working(1, V);
4498   do {
4499     V = Working.pop_back_val();
4500 
4501     SmallVector<const Value *, 4> Objs;
4502     getUnderlyingObjects(V, Objs);
4503 
4504     for (const Value *V : Objs) {
4505       if (!Visited.insert(V).second)
4506         continue;
4507       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
4508         const Value *O =
4509           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
4510         if (O->getType()->isPointerTy()) {
4511           Working.push_back(O);
4512           continue;
4513         }
4514       }
4515       // If getUnderlyingObjects fails to find an identifiable object,
4516       // getUnderlyingObjectsForCodeGen also fails for safety.
4517       if (!isIdentifiedObject(V)) {
4518         Objects.clear();
4519         return false;
4520       }
4521       Objects.push_back(const_cast<Value *>(V));
4522     }
4523   } while (!Working.empty());
4524   return true;
4525 }
4526 
4527 AllocaInst *llvm::findAllocaForValue(Value *V, bool OffsetZero) {
4528   AllocaInst *Result = nullptr;
4529   SmallPtrSet<Value *, 4> Visited;
4530   SmallVector<Value *, 4> Worklist;
4531 
4532   auto AddWork = [&](Value *V) {
4533     if (Visited.insert(V).second)
4534       Worklist.push_back(V);
4535   };
4536 
4537   AddWork(V);
4538   do {
4539     V = Worklist.pop_back_val();
4540     assert(Visited.count(V));
4541 
4542     if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
4543       if (Result && Result != AI)
4544         return nullptr;
4545       Result = AI;
4546     } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
4547       AddWork(CI->getOperand(0));
4548     } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
4549       for (Value *IncValue : PN->incoming_values())
4550         AddWork(IncValue);
4551     } else if (auto *SI = dyn_cast<SelectInst>(V)) {
4552       AddWork(SI->getTrueValue());
4553       AddWork(SI->getFalseValue());
4554     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
4555       if (OffsetZero && !GEP->hasAllZeroIndices())
4556         return nullptr;
4557       AddWork(GEP->getPointerOperand());
4558     } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
4559       Value *Returned = CB->getReturnedArgOperand();
4560       if (Returned)
4561         AddWork(Returned);
4562       else
4563         return nullptr;
4564     } else {
4565       return nullptr;
4566     }
4567   } while (!Worklist.empty());
4568 
4569   return Result;
4570 }
4571 
4572 static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4573     const Value *V, bool AllowLifetime, bool AllowDroppable) {
4574   for (const User *U : V->users()) {
4575     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
4576     if (!II)
4577       return false;
4578 
4579     if (AllowLifetime && II->isLifetimeStartOrEnd())
4580       continue;
4581 
4582     if (AllowDroppable && II->isDroppable())
4583       continue;
4584 
4585     return false;
4586   }
4587   return true;
4588 }
4589 
4590 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
4591   return onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4592       V, /* AllowLifetime */ true, /* AllowDroppable */ false);
4593 }
4594 bool llvm::onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V) {
4595   return onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4596       V, /* AllowLifetime */ true, /* AllowDroppable */ true);
4597 }
4598 
4599 bool llvm::mustSuppressSpeculation(const LoadInst &LI) {
4600   if (!LI.isUnordered())
4601     return true;
4602   const Function &F = *LI.getFunction();
4603   // Speculative load may create a race that did not exist in the source.
4604   return F.hasFnAttribute(Attribute::SanitizeThread) ||
4605     // Speculative load may load data from dirty regions.
4606     F.hasFnAttribute(Attribute::SanitizeAddress) ||
4607     F.hasFnAttribute(Attribute::SanitizeHWAddress);
4608 }
4609 
4610 
4611 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
4612                                         const Instruction *CtxI,
4613                                         const DominatorTree *DT,
4614                                         const TargetLibraryInfo *TLI) {
4615   const Operator *Inst = dyn_cast<Operator>(V);
4616   if (!Inst)
4617     return false;
4618 
4619   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
4620     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
4621       if (C->canTrap())
4622         return false;
4623 
4624   switch (Inst->getOpcode()) {
4625   default:
4626     return true;
4627   case Instruction::UDiv:
4628   case Instruction::URem: {
4629     // x / y is undefined if y == 0.
4630     const APInt *V;
4631     if (match(Inst->getOperand(1), m_APInt(V)))
4632       return *V != 0;
4633     return false;
4634   }
4635   case Instruction::SDiv:
4636   case Instruction::SRem: {
4637     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
4638     const APInt *Numerator, *Denominator;
4639     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
4640       return false;
4641     // We cannot hoist this division if the denominator is 0.
4642     if (*Denominator == 0)
4643       return false;
4644     // It's safe to hoist if the denominator is not 0 or -1.
4645     if (!Denominator->isAllOnesValue())
4646       return true;
4647     // At this point we know that the denominator is -1.  It is safe to hoist as
4648     // long we know that the numerator is not INT_MIN.
4649     if (match(Inst->getOperand(0), m_APInt(Numerator)))
4650       return !Numerator->isMinSignedValue();
4651     // The numerator *might* be MinSignedValue.
4652     return false;
4653   }
4654   case Instruction::Load: {
4655     const LoadInst *LI = cast<LoadInst>(Inst);
4656     if (mustSuppressSpeculation(*LI))
4657       return false;
4658     const DataLayout &DL = LI->getModule()->getDataLayout();
4659     return isDereferenceableAndAlignedPointer(
4660         LI->getPointerOperand(), LI->getType(), MaybeAlign(LI->getAlignment()),
4661         DL, CtxI, DT, TLI);
4662   }
4663   case Instruction::Call: {
4664     auto *CI = cast<const CallInst>(Inst);
4665     const Function *Callee = CI->getCalledFunction();
4666 
4667     // The called function could have undefined behavior or side-effects, even
4668     // if marked readnone nounwind.
4669     return Callee && Callee->isSpeculatable();
4670   }
4671   case Instruction::VAArg:
4672   case Instruction::Alloca:
4673   case Instruction::Invoke:
4674   case Instruction::CallBr:
4675   case Instruction::PHI:
4676   case Instruction::Store:
4677   case Instruction::Ret:
4678   case Instruction::Br:
4679   case Instruction::IndirectBr:
4680   case Instruction::Switch:
4681   case Instruction::Unreachable:
4682   case Instruction::Fence:
4683   case Instruction::AtomicRMW:
4684   case Instruction::AtomicCmpXchg:
4685   case Instruction::LandingPad:
4686   case Instruction::Resume:
4687   case Instruction::CatchSwitch:
4688   case Instruction::CatchPad:
4689   case Instruction::CatchRet:
4690   case Instruction::CleanupPad:
4691   case Instruction::CleanupRet:
4692     return false; // Misc instructions which have effects
4693   }
4694 }
4695 
4696 bool llvm::mayBeMemoryDependent(const Instruction &I) {
4697   return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
4698 }
4699 
4700 /// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
4701 static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
4702   switch (OR) {
4703     case ConstantRange::OverflowResult::MayOverflow:
4704       return OverflowResult::MayOverflow;
4705     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
4706       return OverflowResult::AlwaysOverflowsLow;
4707     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
4708       return OverflowResult::AlwaysOverflowsHigh;
4709     case ConstantRange::OverflowResult::NeverOverflows:
4710       return OverflowResult::NeverOverflows;
4711   }
4712   llvm_unreachable("Unknown OverflowResult");
4713 }
4714 
4715 /// Combine constant ranges from computeConstantRange() and computeKnownBits().
4716 static ConstantRange computeConstantRangeIncludingKnownBits(
4717     const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
4718     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4719     OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
4720   KnownBits Known = computeKnownBits(
4721       V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
4722   ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
4723   ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
4724   ConstantRange::PreferredRangeType RangeType =
4725       ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
4726   return CR1.intersectWith(CR2, RangeType);
4727 }
4728 
4729 OverflowResult llvm::computeOverflowForUnsignedMul(
4730     const Value *LHS, const Value *RHS, const DataLayout &DL,
4731     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4732     bool UseInstrInfo) {
4733   KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4734                                         nullptr, UseInstrInfo);
4735   KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4736                                         nullptr, UseInstrInfo);
4737   ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
4738   ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
4739   return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
4740 }
4741 
4742 OverflowResult
4743 llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4744                                   const DataLayout &DL, AssumptionCache *AC,
4745                                   const Instruction *CxtI,
4746                                   const DominatorTree *DT, bool UseInstrInfo) {
4747   // Multiplying n * m significant bits yields a result of n + m significant
4748   // bits. If the total number of significant bits does not exceed the
4749   // result bit width (minus 1), there is no overflow.
4750   // This means if we have enough leading sign bits in the operands
4751   // we can guarantee that the result does not overflow.
4752   // Ref: "Hacker's Delight" by Henry Warren
4753   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4754 
4755   // Note that underestimating the number of sign bits gives a more
4756   // conservative answer.
4757   unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4758                       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4759 
4760   // First handle the easy case: if we have enough sign bits there's
4761   // definitely no overflow.
4762   if (SignBits > BitWidth + 1)
4763     return OverflowResult::NeverOverflows;
4764 
4765   // There are two ambiguous cases where there can be no overflow:
4766   //   SignBits == BitWidth + 1    and
4767   //   SignBits == BitWidth
4768   // The second case is difficult to check, therefore we only handle the
4769   // first case.
4770   if (SignBits == BitWidth + 1) {
4771     // It overflows only when both arguments are negative and the true
4772     // product is exactly the minimum negative number.
4773     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4774     // For simplicity we just check if at least one side is not negative.
4775     KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4776                                           nullptr, UseInstrInfo);
4777     KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4778                                           nullptr, UseInstrInfo);
4779     if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4780       return OverflowResult::NeverOverflows;
4781   }
4782   return OverflowResult::MayOverflow;
4783 }
4784 
4785 OverflowResult llvm::computeOverflowForUnsignedAdd(
4786     const Value *LHS, const Value *RHS, const DataLayout &DL,
4787     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4788     bool UseInstrInfo) {
4789   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4790       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4791       nullptr, UseInstrInfo);
4792   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4793       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4794       nullptr, UseInstrInfo);
4795   return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
4796 }
4797 
4798 static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4799                                                   const Value *RHS,
4800                                                   const AddOperator *Add,
4801                                                   const DataLayout &DL,
4802                                                   AssumptionCache *AC,
4803                                                   const Instruction *CxtI,
4804                                                   const DominatorTree *DT) {
4805   if (Add && Add->hasNoSignedWrap()) {
4806     return OverflowResult::NeverOverflows;
4807   }
4808 
4809   // If LHS and RHS each have at least two sign bits, the addition will look
4810   // like
4811   //
4812   // XX..... +
4813   // YY.....
4814   //
4815   // If the carry into the most significant position is 0, X and Y can't both
4816   // be 1 and therefore the carry out of the addition is also 0.
4817   //
4818   // If the carry into the most significant position is 1, X and Y can't both
4819   // be 0 and therefore the carry out of the addition is also 1.
4820   //
4821   // Since the carry into the most significant position is always equal to
4822   // the carry out of the addition, there is no signed overflow.
4823   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4824       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4825     return OverflowResult::NeverOverflows;
4826 
4827   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4828       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4829   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4830       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4831   OverflowResult OR =
4832       mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4833   if (OR != OverflowResult::MayOverflow)
4834     return OR;
4835 
4836   // The remaining code needs Add to be available. Early returns if not so.
4837   if (!Add)
4838     return OverflowResult::MayOverflow;
4839 
4840   // If the sign of Add is the same as at least one of the operands, this add
4841   // CANNOT overflow. If this can be determined from the known bits of the
4842   // operands the above signedAddMayOverflow() check will have already done so.
4843   // The only other way to improve on the known bits is from an assumption, so
4844   // call computeKnownBitsFromAssume() directly.
4845   bool LHSOrRHSKnownNonNegative =
4846       (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
4847   bool LHSOrRHSKnownNegative =
4848       (LHSRange.isAllNegative() || RHSRange.isAllNegative());
4849   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
4850     KnownBits AddKnown(LHSRange.getBitWidth());
4851     computeKnownBitsFromAssume(
4852         Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
4853     if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
4854         (AddKnown.isNegative() && LHSOrRHSKnownNegative))
4855       return OverflowResult::NeverOverflows;
4856   }
4857 
4858   return OverflowResult::MayOverflow;
4859 }
4860 
4861 OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4862                                                    const Value *RHS,
4863                                                    const DataLayout &DL,
4864                                                    AssumptionCache *AC,
4865                                                    const Instruction *CxtI,
4866                                                    const DominatorTree *DT) {
4867   // Checking for conditions implied by dominating conditions may be expensive.
4868   // Limit it to usub_with_overflow calls for now.
4869   if (match(CxtI,
4870             m_Intrinsic<Intrinsic::usub_with_overflow>(m_Value(), m_Value())))
4871     if (auto C =
4872             isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, CxtI, DL)) {
4873       if (*C)
4874         return OverflowResult::NeverOverflows;
4875       return OverflowResult::AlwaysOverflowsLow;
4876     }
4877   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4878       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4879   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4880       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4881   return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
4882 }
4883 
4884 OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4885                                                  const Value *RHS,
4886                                                  const DataLayout &DL,
4887                                                  AssumptionCache *AC,
4888                                                  const Instruction *CxtI,
4889                                                  const DominatorTree *DT) {
4890   // If LHS and RHS each have at least two sign bits, the subtraction
4891   // cannot overflow.
4892   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4893       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4894     return OverflowResult::NeverOverflows;
4895 
4896   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4897       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4898   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4899       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4900   return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
4901 }
4902 
4903 bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
4904                                      const DominatorTree &DT) {
4905   SmallVector<const BranchInst *, 2> GuardingBranches;
4906   SmallVector<const ExtractValueInst *, 2> Results;
4907 
4908   for (const User *U : WO->users()) {
4909     if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
4910       assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4911 
4912       if (EVI->getIndices()[0] == 0)
4913         Results.push_back(EVI);
4914       else {
4915         assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4916 
4917         for (const auto *U : EVI->users())
4918           if (const auto *B = dyn_cast<BranchInst>(U)) {
4919             assert(B->isConditional() && "How else is it using an i1?");
4920             GuardingBranches.push_back(B);
4921           }
4922       }
4923     } else {
4924       // We are using the aggregate directly in a way we don't want to analyze
4925       // here (storing it to a global, say).
4926       return false;
4927     }
4928   }
4929 
4930   auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
4931     BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4932     if (!NoWrapEdge.isSingleEdge())
4933       return false;
4934 
4935     // Check if all users of the add are provably no-wrap.
4936     for (const auto *Result : Results) {
4937       // If the extractvalue itself is not executed on overflow, the we don't
4938       // need to check each use separately, since domination is transitive.
4939       if (DT.dominates(NoWrapEdge, Result->getParent()))
4940         continue;
4941 
4942       for (auto &RU : Result->uses())
4943         if (!DT.dominates(NoWrapEdge, RU))
4944           return false;
4945     }
4946 
4947     return true;
4948   };
4949 
4950   return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
4951 }
4952 
4953 static bool canCreateUndefOrPoison(const Operator *Op, bool PoisonOnly) {
4954   // See whether I has flags that may create poison
4955   if (const auto *OvOp = dyn_cast<OverflowingBinaryOperator>(Op)) {
4956     if (OvOp->hasNoSignedWrap() || OvOp->hasNoUnsignedWrap())
4957       return true;
4958   }
4959   if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(Op))
4960     if (ExactOp->isExact())
4961       return true;
4962   if (const auto *FP = dyn_cast<FPMathOperator>(Op)) {
4963     auto FMF = FP->getFastMathFlags();
4964     if (FMF.noNaNs() || FMF.noInfs())
4965       return true;
4966   }
4967 
4968   unsigned Opcode = Op->getOpcode();
4969 
4970   // Check whether opcode is a poison/undef-generating operation
4971   switch (Opcode) {
4972   case Instruction::Shl:
4973   case Instruction::AShr:
4974   case Instruction::LShr: {
4975     // Shifts return poison if shiftwidth is larger than the bitwidth.
4976     if (auto *C = dyn_cast<Constant>(Op->getOperand(1))) {
4977       SmallVector<Constant *, 4> ShiftAmounts;
4978       if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
4979         unsigned NumElts = FVTy->getNumElements();
4980         for (unsigned i = 0; i < NumElts; ++i)
4981           ShiftAmounts.push_back(C->getAggregateElement(i));
4982       } else if (isa<ScalableVectorType>(C->getType()))
4983         return true; // Can't tell, just return true to be safe
4984       else
4985         ShiftAmounts.push_back(C);
4986 
4987       bool Safe = llvm::all_of(ShiftAmounts, [](Constant *C) {
4988         auto *CI = dyn_cast_or_null<ConstantInt>(C);
4989         return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
4990       });
4991       return !Safe;
4992     }
4993     return true;
4994   }
4995   case Instruction::FPToSI:
4996   case Instruction::FPToUI:
4997     // fptosi/ui yields poison if the resulting value does not fit in the
4998     // destination type.
4999     return true;
5000   case Instruction::Call:
5001     if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
5002       switch (II->getIntrinsicID()) {
5003       // TODO: Add more intrinsics.
5004       case Intrinsic::ctpop:
5005       case Intrinsic::sadd_with_overflow:
5006       case Intrinsic::ssub_with_overflow:
5007       case Intrinsic::smul_with_overflow:
5008       case Intrinsic::uadd_with_overflow:
5009       case Intrinsic::usub_with_overflow:
5010       case Intrinsic::umul_with_overflow:
5011         return false;
5012       }
5013     }
5014     LLVM_FALLTHROUGH;
5015   case Instruction::CallBr:
5016   case Instruction::Invoke: {
5017     const auto *CB = cast<CallBase>(Op);
5018     return !CB->hasRetAttr(Attribute::NoUndef);
5019   }
5020   case Instruction::InsertElement:
5021   case Instruction::ExtractElement: {
5022     // If index exceeds the length of the vector, it returns poison
5023     auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
5024     unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
5025     auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
5026     if (!Idx || Idx->getValue().uge(VTy->getElementCount().getKnownMinValue()))
5027       return true;
5028     return false;
5029   }
5030   case Instruction::ShuffleVector: {
5031     // shufflevector may return undef.
5032     if (PoisonOnly)
5033       return false;
5034     ArrayRef<int> Mask = isa<ConstantExpr>(Op)
5035                              ? cast<ConstantExpr>(Op)->getShuffleMask()
5036                              : cast<ShuffleVectorInst>(Op)->getShuffleMask();
5037     return is_contained(Mask, UndefMaskElem);
5038   }
5039   case Instruction::FNeg:
5040   case Instruction::PHI:
5041   case Instruction::Select:
5042   case Instruction::URem:
5043   case Instruction::SRem:
5044   case Instruction::ExtractValue:
5045   case Instruction::InsertValue:
5046   case Instruction::Freeze:
5047   case Instruction::ICmp:
5048   case Instruction::FCmp:
5049     return false;
5050   case Instruction::GetElementPtr: {
5051     const auto *GEP = cast<GEPOperator>(Op);
5052     return GEP->isInBounds();
5053   }
5054   default: {
5055     const auto *CE = dyn_cast<ConstantExpr>(Op);
5056     if (isa<CastInst>(Op) || (CE && CE->isCast()))
5057       return false;
5058     else if (Instruction::isBinaryOp(Opcode))
5059       return false;
5060     // Be conservative and return true.
5061     return true;
5062   }
5063   }
5064 }
5065 
5066 bool llvm::canCreateUndefOrPoison(const Operator *Op) {
5067   return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/false);
5068 }
5069 
5070 bool llvm::canCreatePoison(const Operator *Op) {
5071   return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/true);
5072 }
5073 
5074 static bool directlyImpliesPoison(const Value *ValAssumedPoison,
5075                                   const Value *V, unsigned Depth) {
5076   if (ValAssumedPoison == V)
5077     return true;
5078 
5079   const unsigned MaxDepth = 2;
5080   if (Depth >= MaxDepth)
5081     return false;
5082 
5083   if (const auto *I = dyn_cast<Instruction>(V)) {
5084     if (propagatesPoison(cast<Operator>(I)))
5085       return any_of(I->operands(), [=](const Value *Op) {
5086         return directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
5087       });
5088 
5089     // 'select ValAssumedPoison, _, _' is poison.
5090     if (const auto *SI = dyn_cast<SelectInst>(I))
5091       return directlyImpliesPoison(ValAssumedPoison, SI->getCondition(),
5092                                    Depth + 1);
5093     // V  = extractvalue V0, idx
5094     // V2 = extractvalue V0, idx2
5095     // V0's elements are all poison or not. (e.g., add_with_overflow)
5096     const WithOverflowInst *II;
5097     if (match(I, m_ExtractValue(m_WithOverflowInst(II))) &&
5098         (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
5099          llvm::is_contained(II->args(), ValAssumedPoison)))
5100       return true;
5101   }
5102   return false;
5103 }
5104 
5105 static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
5106                           unsigned Depth) {
5107   if (isGuaranteedNotToBeUndefOrPoison(ValAssumedPoison))
5108     return true;
5109 
5110   if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
5111     return true;
5112 
5113   const unsigned MaxDepth = 2;
5114   if (Depth >= MaxDepth)
5115     return false;
5116 
5117   const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
5118   if (I && !canCreatePoison(cast<Operator>(I))) {
5119     return all_of(I->operands(), [=](const Value *Op) {
5120       return impliesPoison(Op, V, Depth + 1);
5121     });
5122   }
5123   return false;
5124 }
5125 
5126 bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
5127   return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
5128 }
5129 
5130 static bool programUndefinedIfUndefOrPoison(const Value *V,
5131                                             bool PoisonOnly);
5132 
5133 static bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
5134                                              AssumptionCache *AC,
5135                                              const Instruction *CtxI,
5136                                              const DominatorTree *DT,
5137                                              unsigned Depth, bool PoisonOnly) {
5138   if (Depth >= MaxAnalysisRecursionDepth)
5139     return false;
5140 
5141   if (isa<MetadataAsValue>(V))
5142     return false;
5143 
5144   if (const auto *A = dyn_cast<Argument>(V)) {
5145     if (A->hasAttribute(Attribute::NoUndef))
5146       return true;
5147   }
5148 
5149   if (auto *C = dyn_cast<Constant>(V)) {
5150     if (isa<UndefValue>(C))
5151       return PoisonOnly && !isa<PoisonValue>(C);
5152 
5153     if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(V) ||
5154         isa<ConstantPointerNull>(C) || isa<Function>(C))
5155       return true;
5156 
5157     if (C->getType()->isVectorTy() && !isa<ConstantExpr>(C))
5158       return (PoisonOnly ? !C->containsPoisonElement()
5159                          : !C->containsUndefOrPoisonElement()) &&
5160              !C->containsConstantExpression();
5161   }
5162 
5163   // Strip cast operations from a pointer value.
5164   // Note that stripPointerCastsSameRepresentation can strip off getelementptr
5165   // inbounds with zero offset. To guarantee that the result isn't poison, the
5166   // stripped pointer is checked as it has to be pointing into an allocated
5167   // object or be null `null` to ensure `inbounds` getelement pointers with a
5168   // zero offset could not produce poison.
5169   // It can strip off addrspacecast that do not change bit representation as
5170   // well. We believe that such addrspacecast is equivalent to no-op.
5171   auto *StrippedV = V->stripPointerCastsSameRepresentation();
5172   if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
5173       isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
5174     return true;
5175 
5176   auto OpCheck = [&](const Value *V) {
5177     return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1,
5178                                             PoisonOnly);
5179   };
5180 
5181   if (auto *Opr = dyn_cast<Operator>(V)) {
5182     // If the value is a freeze instruction, then it can never
5183     // be undef or poison.
5184     if (isa<FreezeInst>(V))
5185       return true;
5186 
5187     if (const auto *CB = dyn_cast<CallBase>(V)) {
5188       if (CB->hasRetAttr(Attribute::NoUndef))
5189         return true;
5190     }
5191 
5192     if (const auto *PN = dyn_cast<PHINode>(V)) {
5193       unsigned Num = PN->getNumIncomingValues();
5194       bool IsWellDefined = true;
5195       for (unsigned i = 0; i < Num; ++i) {
5196         auto *TI = PN->getIncomingBlock(i)->getTerminator();
5197         if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
5198                                               DT, Depth + 1, PoisonOnly)) {
5199           IsWellDefined = false;
5200           break;
5201         }
5202       }
5203       if (IsWellDefined)
5204         return true;
5205     } else if (!canCreateUndefOrPoison(Opr) && all_of(Opr->operands(), OpCheck))
5206       return true;
5207   }
5208 
5209   if (auto *I = dyn_cast<LoadInst>(V))
5210     if (I->getMetadata(LLVMContext::MD_noundef))
5211       return true;
5212 
5213   if (programUndefinedIfUndefOrPoison(V, PoisonOnly))
5214     return true;
5215 
5216   // CxtI may be null or a cloned instruction.
5217   if (!CtxI || !CtxI->getParent() || !DT)
5218     return false;
5219 
5220   auto *DNode = DT->getNode(CtxI->getParent());
5221   if (!DNode)
5222     // Unreachable block
5223     return false;
5224 
5225   // If V is used as a branch condition before reaching CtxI, V cannot be
5226   // undef or poison.
5227   //   br V, BB1, BB2
5228   // BB1:
5229   //   CtxI ; V cannot be undef or poison here
5230   auto *Dominator = DNode->getIDom();
5231   while (Dominator) {
5232     auto *TI = Dominator->getBlock()->getTerminator();
5233 
5234     Value *Cond = nullptr;
5235     if (auto BI = dyn_cast<BranchInst>(TI)) {
5236       if (BI->isConditional())
5237         Cond = BI->getCondition();
5238     } else if (auto SI = dyn_cast<SwitchInst>(TI)) {
5239       Cond = SI->getCondition();
5240     }
5241 
5242     if (Cond) {
5243       if (Cond == V)
5244         return true;
5245       else if (PoisonOnly && isa<Operator>(Cond)) {
5246         // For poison, we can analyze further
5247         auto *Opr = cast<Operator>(Cond);
5248         if (propagatesPoison(Opr) && is_contained(Opr->operand_values(), V))
5249           return true;
5250       }
5251     }
5252 
5253     Dominator = Dominator->getIDom();
5254   }
5255 
5256   SmallVector<Attribute::AttrKind, 2> AttrKinds{Attribute::NoUndef};
5257   if (getKnowledgeValidInContext(V, AttrKinds, CtxI, DT, AC))
5258     return true;
5259 
5260   return false;
5261 }
5262 
5263 bool llvm::isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC,
5264                                             const Instruction *CtxI,
5265                                             const DominatorTree *DT,
5266                                             unsigned Depth) {
5267   return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, false);
5268 }
5269 
5270 bool llvm::isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC,
5271                                      const Instruction *CtxI,
5272                                      const DominatorTree *DT, unsigned Depth) {
5273   return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, true);
5274 }
5275 
5276 OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
5277                                                  const DataLayout &DL,
5278                                                  AssumptionCache *AC,
5279                                                  const Instruction *CxtI,
5280                                                  const DominatorTree *DT) {
5281   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
5282                                        Add, DL, AC, CxtI, DT);
5283 }
5284 
5285 OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
5286                                                  const Value *RHS,
5287                                                  const DataLayout &DL,
5288                                                  AssumptionCache *AC,
5289                                                  const Instruction *CxtI,
5290                                                  const DominatorTree *DT) {
5291   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
5292 }
5293 
5294 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
5295   // Note: An atomic operation isn't guaranteed to return in a reasonable amount
5296   // of time because it's possible for another thread to interfere with it for an
5297   // arbitrary length of time, but programs aren't allowed to rely on that.
5298 
5299   // If there is no successor, then execution can't transfer to it.
5300   if (isa<ReturnInst>(I))
5301     return false;
5302   if (isa<UnreachableInst>(I))
5303     return false;
5304 
5305   // Note: Do not add new checks here; instead, change Instruction::mayThrow or
5306   // Instruction::willReturn.
5307   //
5308   // FIXME: Move this check into Instruction::willReturn.
5309   if (isa<CatchPadInst>(I)) {
5310     switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
5311     default:
5312       // A catchpad may invoke exception object constructors and such, which
5313       // in some languages can be arbitrary code, so be conservative by default.
5314       return false;
5315     case EHPersonality::CoreCLR:
5316       // For CoreCLR, it just involves a type test.
5317       return true;
5318     }
5319   }
5320 
5321   // An instruction that returns without throwing must transfer control flow
5322   // to a successor.
5323   return !I->mayThrow() && I->willReturn();
5324 }
5325 
5326 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
5327   // TODO: This is slightly conservative for invoke instruction since exiting
5328   // via an exception *is* normal control for them.
5329   for (const Instruction &I : *BB)
5330     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5331       return false;
5332   return true;
5333 }
5334 
5335 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
5336                                                   const Loop *L) {
5337   // The loop header is guaranteed to be executed for every iteration.
5338   //
5339   // FIXME: Relax this constraint to cover all basic blocks that are
5340   // guaranteed to be executed at every iteration.
5341   if (I->getParent() != L->getHeader()) return false;
5342 
5343   for (const Instruction &LI : *L->getHeader()) {
5344     if (&LI == I) return true;
5345     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
5346   }
5347   llvm_unreachable("Instruction not contained in its own parent basic block.");
5348 }
5349 
5350 bool llvm::propagatesPoison(const Operator *I) {
5351   switch (I->getOpcode()) {
5352   case Instruction::Freeze:
5353   case Instruction::Select:
5354   case Instruction::PHI:
5355   case Instruction::Invoke:
5356     return false;
5357   case Instruction::Call:
5358     if (auto *II = dyn_cast<IntrinsicInst>(I)) {
5359       switch (II->getIntrinsicID()) {
5360       // TODO: Add more intrinsics.
5361       case Intrinsic::sadd_with_overflow:
5362       case Intrinsic::ssub_with_overflow:
5363       case Intrinsic::smul_with_overflow:
5364       case Intrinsic::uadd_with_overflow:
5365       case Intrinsic::usub_with_overflow:
5366       case Intrinsic::umul_with_overflow:
5367         // If an input is a vector containing a poison element, the
5368         // two output vectors (calculated results, overflow bits)'
5369         // corresponding lanes are poison.
5370         return true;
5371       case Intrinsic::ctpop:
5372         return true;
5373       }
5374     }
5375     return false;
5376   case Instruction::ICmp:
5377   case Instruction::FCmp:
5378   case Instruction::GetElementPtr:
5379     return true;
5380   default:
5381     if (isa<BinaryOperator>(I) || isa<UnaryOperator>(I) || isa<CastInst>(I))
5382       return true;
5383 
5384     // Be conservative and return false.
5385     return false;
5386   }
5387 }
5388 
5389 void llvm::getGuaranteedWellDefinedOps(
5390     const Instruction *I, SmallPtrSetImpl<const Value *> &Operands) {
5391   switch (I->getOpcode()) {
5392     case Instruction::Store:
5393       Operands.insert(cast<StoreInst>(I)->getPointerOperand());
5394       break;
5395 
5396     case Instruction::Load:
5397       Operands.insert(cast<LoadInst>(I)->getPointerOperand());
5398       break;
5399 
5400     // Since dereferenceable attribute imply noundef, atomic operations
5401     // also implicitly have noundef pointers too
5402     case Instruction::AtomicCmpXchg:
5403       Operands.insert(cast<AtomicCmpXchgInst>(I)->getPointerOperand());
5404       break;
5405 
5406     case Instruction::AtomicRMW:
5407       Operands.insert(cast<AtomicRMWInst>(I)->getPointerOperand());
5408       break;
5409 
5410     case Instruction::Call:
5411     case Instruction::Invoke: {
5412       const CallBase *CB = cast<CallBase>(I);
5413       if (CB->isIndirectCall())
5414         Operands.insert(CB->getCalledOperand());
5415       for (unsigned i = 0; i < CB->arg_size(); ++i) {
5416         if (CB->paramHasAttr(i, Attribute::NoUndef) ||
5417             CB->paramHasAttr(i, Attribute::Dereferenceable))
5418           Operands.insert(CB->getArgOperand(i));
5419       }
5420       break;
5421     }
5422 
5423     default:
5424       break;
5425   }
5426 }
5427 
5428 void llvm::getGuaranteedNonPoisonOps(const Instruction *I,
5429                                      SmallPtrSetImpl<const Value *> &Operands) {
5430   getGuaranteedWellDefinedOps(I, Operands);
5431   switch (I->getOpcode()) {
5432   // Divisors of these operations are allowed to be partially undef.
5433   case Instruction::UDiv:
5434   case Instruction::SDiv:
5435   case Instruction::URem:
5436   case Instruction::SRem:
5437     Operands.insert(I->getOperand(1));
5438     break;
5439 
5440   default:
5441     break;
5442   }
5443 }
5444 
5445 bool llvm::mustTriggerUB(const Instruction *I,
5446                          const SmallSet<const Value *, 16>& KnownPoison) {
5447   SmallPtrSet<const Value *, 4> NonPoisonOps;
5448   getGuaranteedNonPoisonOps(I, NonPoisonOps);
5449 
5450   for (const auto *V : NonPoisonOps)
5451     if (KnownPoison.count(V))
5452       return true;
5453 
5454   return false;
5455 }
5456 
5457 static bool programUndefinedIfUndefOrPoison(const Value *V,
5458                                             bool PoisonOnly) {
5459   // We currently only look for uses of values within the same basic
5460   // block, as that makes it easier to guarantee that the uses will be
5461   // executed given that Inst is executed.
5462   //
5463   // FIXME: Expand this to consider uses beyond the same basic block. To do
5464   // this, look out for the distinction between post-dominance and strong
5465   // post-dominance.
5466   const BasicBlock *BB = nullptr;
5467   BasicBlock::const_iterator Begin;
5468   if (const auto *Inst = dyn_cast<Instruction>(V)) {
5469     BB = Inst->getParent();
5470     Begin = Inst->getIterator();
5471     Begin++;
5472   } else if (const auto *Arg = dyn_cast<Argument>(V)) {
5473     BB = &Arg->getParent()->getEntryBlock();
5474     Begin = BB->begin();
5475   } else {
5476     return false;
5477   }
5478 
5479   // Limit number of instructions we look at, to avoid scanning through large
5480   // blocks. The current limit is chosen arbitrarily.
5481   unsigned ScanLimit = 32;
5482   BasicBlock::const_iterator End = BB->end();
5483 
5484   if (!PoisonOnly) {
5485     // Since undef does not propagate eagerly, be conservative & just check
5486     // whether a value is directly passed to an instruction that must take
5487     // well-defined operands.
5488 
5489     for (auto &I : make_range(Begin, End)) {
5490       if (isa<DbgInfoIntrinsic>(I))
5491         continue;
5492       if (--ScanLimit == 0)
5493         break;
5494 
5495       SmallPtrSet<const Value *, 4> WellDefinedOps;
5496       getGuaranteedWellDefinedOps(&I, WellDefinedOps);
5497       if (WellDefinedOps.contains(V))
5498         return true;
5499 
5500       if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5501         break;
5502     }
5503     return false;
5504   }
5505 
5506   // Set of instructions that we have proved will yield poison if Inst
5507   // does.
5508   SmallSet<const Value *, 16> YieldsPoison;
5509   SmallSet<const BasicBlock *, 4> Visited;
5510 
5511   YieldsPoison.insert(V);
5512   auto Propagate = [&](const User *User) {
5513     if (propagatesPoison(cast<Operator>(User)))
5514       YieldsPoison.insert(User);
5515   };
5516   for_each(V->users(), Propagate);
5517   Visited.insert(BB);
5518 
5519   while (true) {
5520     for (auto &I : make_range(Begin, End)) {
5521       if (isa<DbgInfoIntrinsic>(I))
5522         continue;
5523       if (--ScanLimit == 0)
5524         return false;
5525       if (mustTriggerUB(&I, YieldsPoison))
5526         return true;
5527       if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5528         return false;
5529 
5530       // Mark poison that propagates from I through uses of I.
5531       if (YieldsPoison.count(&I))
5532         for_each(I.users(), Propagate);
5533     }
5534 
5535     BB = BB->getSingleSuccessor();
5536     if (!BB || !Visited.insert(BB).second)
5537       break;
5538 
5539     Begin = BB->getFirstNonPHI()->getIterator();
5540     End = BB->end();
5541   }
5542   return false;
5543 }
5544 
5545 bool llvm::programUndefinedIfUndefOrPoison(const Instruction *Inst) {
5546   return ::programUndefinedIfUndefOrPoison(Inst, false);
5547 }
5548 
5549 bool llvm::programUndefinedIfPoison(const Instruction *Inst) {
5550   return ::programUndefinedIfUndefOrPoison(Inst, true);
5551 }
5552 
5553 static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
5554   if (FMF.noNaNs())
5555     return true;
5556 
5557   if (auto *C = dyn_cast<ConstantFP>(V))
5558     return !C->isNaN();
5559 
5560   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
5561     if (!C->getElementType()->isFloatingPointTy())
5562       return false;
5563     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
5564       if (C->getElementAsAPFloat(I).isNaN())
5565         return false;
5566     }
5567     return true;
5568   }
5569 
5570   if (isa<ConstantAggregateZero>(V))
5571     return true;
5572 
5573   return false;
5574 }
5575 
5576 static bool isKnownNonZero(const Value *V) {
5577   if (auto *C = dyn_cast<ConstantFP>(V))
5578     return !C->isZero();
5579 
5580   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
5581     if (!C->getElementType()->isFloatingPointTy())
5582       return false;
5583     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
5584       if (C->getElementAsAPFloat(I).isZero())
5585         return false;
5586     }
5587     return true;
5588   }
5589 
5590   return false;
5591 }
5592 
5593 /// Match clamp pattern for float types without care about NaNs or signed zeros.
5594 /// Given non-min/max outer cmp/select from the clamp pattern this
5595 /// function recognizes if it can be substitued by a "canonical" min/max
5596 /// pattern.
5597 static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
5598                                                Value *CmpLHS, Value *CmpRHS,
5599                                                Value *TrueVal, Value *FalseVal,
5600                                                Value *&LHS, Value *&RHS) {
5601   // Try to match
5602   //   X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
5603   //   X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
5604   // and return description of the outer Max/Min.
5605 
5606   // First, check if select has inverse order:
5607   if (CmpRHS == FalseVal) {
5608     std::swap(TrueVal, FalseVal);
5609     Pred = CmpInst::getInversePredicate(Pred);
5610   }
5611 
5612   // Assume success now. If there's no match, callers should not use these anyway.
5613   LHS = TrueVal;
5614   RHS = FalseVal;
5615 
5616   const APFloat *FC1;
5617   if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
5618     return {SPF_UNKNOWN, SPNB_NA, false};
5619 
5620   const APFloat *FC2;
5621   switch (Pred) {
5622   case CmpInst::FCMP_OLT:
5623   case CmpInst::FCMP_OLE:
5624   case CmpInst::FCMP_ULT:
5625   case CmpInst::FCMP_ULE:
5626     if (match(FalseVal,
5627               m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
5628                           m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
5629         *FC1 < *FC2)
5630       return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
5631     break;
5632   case CmpInst::FCMP_OGT:
5633   case CmpInst::FCMP_OGE:
5634   case CmpInst::FCMP_UGT:
5635   case CmpInst::FCMP_UGE:
5636     if (match(FalseVal,
5637               m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
5638                           m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
5639         *FC1 > *FC2)
5640       return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
5641     break;
5642   default:
5643     break;
5644   }
5645 
5646   return {SPF_UNKNOWN, SPNB_NA, false};
5647 }
5648 
5649 /// Recognize variations of:
5650 ///   CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
5651 static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
5652                                       Value *CmpLHS, Value *CmpRHS,
5653                                       Value *TrueVal, Value *FalseVal) {
5654   // Swap the select operands and predicate to match the patterns below.
5655   if (CmpRHS != TrueVal) {
5656     Pred = ICmpInst::getSwappedPredicate(Pred);
5657     std::swap(TrueVal, FalseVal);
5658   }
5659   const APInt *C1;
5660   if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
5661     const APInt *C2;
5662     // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
5663     if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
5664         C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
5665       return {SPF_SMAX, SPNB_NA, false};
5666 
5667     // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
5668     if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
5669         C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
5670       return {SPF_SMIN, SPNB_NA, false};
5671 
5672     // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
5673     if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
5674         C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
5675       return {SPF_UMAX, SPNB_NA, false};
5676 
5677     // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
5678     if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
5679         C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
5680       return {SPF_UMIN, SPNB_NA, false};
5681   }
5682   return {SPF_UNKNOWN, SPNB_NA, false};
5683 }
5684 
5685 /// Recognize variations of:
5686 ///   a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
5687 static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
5688                                                Value *CmpLHS, Value *CmpRHS,
5689                                                Value *TVal, Value *FVal,
5690                                                unsigned Depth) {
5691   // TODO: Allow FP min/max with nnan/nsz.
5692   assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
5693 
5694   Value *A = nullptr, *B = nullptr;
5695   SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
5696   if (!SelectPatternResult::isMinOrMax(L.Flavor))
5697     return {SPF_UNKNOWN, SPNB_NA, false};
5698 
5699   Value *C = nullptr, *D = nullptr;
5700   SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
5701   if (L.Flavor != R.Flavor)
5702     return {SPF_UNKNOWN, SPNB_NA, false};
5703 
5704   // We have something like: x Pred y ? min(a, b) : min(c, d).
5705   // Try to match the compare to the min/max operations of the select operands.
5706   // First, make sure we have the right compare predicate.
5707   switch (L.Flavor) {
5708   case SPF_SMIN:
5709     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
5710       Pred = ICmpInst::getSwappedPredicate(Pred);
5711       std::swap(CmpLHS, CmpRHS);
5712     }
5713     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5714       break;
5715     return {SPF_UNKNOWN, SPNB_NA, false};
5716   case SPF_SMAX:
5717     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
5718       Pred = ICmpInst::getSwappedPredicate(Pred);
5719       std::swap(CmpLHS, CmpRHS);
5720     }
5721     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5722       break;
5723     return {SPF_UNKNOWN, SPNB_NA, false};
5724   case SPF_UMIN:
5725     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
5726       Pred = ICmpInst::getSwappedPredicate(Pred);
5727       std::swap(CmpLHS, CmpRHS);
5728     }
5729     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
5730       break;
5731     return {SPF_UNKNOWN, SPNB_NA, false};
5732   case SPF_UMAX:
5733     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
5734       Pred = ICmpInst::getSwappedPredicate(Pred);
5735       std::swap(CmpLHS, CmpRHS);
5736     }
5737     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
5738       break;
5739     return {SPF_UNKNOWN, SPNB_NA, false};
5740   default:
5741     return {SPF_UNKNOWN, SPNB_NA, false};
5742   }
5743 
5744   // If there is a common operand in the already matched min/max and the other
5745   // min/max operands match the compare operands (either directly or inverted),
5746   // then this is min/max of the same flavor.
5747 
5748   // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
5749   // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
5750   if (D == B) {
5751     if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
5752                                          match(A, m_Not(m_Specific(CmpRHS)))))
5753       return {L.Flavor, SPNB_NA, false};
5754   }
5755   // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
5756   // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
5757   if (C == B) {
5758     if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
5759                                          match(A, m_Not(m_Specific(CmpRHS)))))
5760       return {L.Flavor, SPNB_NA, false};
5761   }
5762   // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
5763   // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
5764   if (D == A) {
5765     if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
5766                                          match(B, m_Not(m_Specific(CmpRHS)))))
5767       return {L.Flavor, SPNB_NA, false};
5768   }
5769   // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
5770   // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
5771   if (C == A) {
5772     if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
5773                                          match(B, m_Not(m_Specific(CmpRHS)))))
5774       return {L.Flavor, SPNB_NA, false};
5775   }
5776 
5777   return {SPF_UNKNOWN, SPNB_NA, false};
5778 }
5779 
5780 /// If the input value is the result of a 'not' op, constant integer, or vector
5781 /// splat of a constant integer, return the bitwise-not source value.
5782 /// TODO: This could be extended to handle non-splat vector integer constants.
5783 static Value *getNotValue(Value *V) {
5784   Value *NotV;
5785   if (match(V, m_Not(m_Value(NotV))))
5786     return NotV;
5787 
5788   const APInt *C;
5789   if (match(V, m_APInt(C)))
5790     return ConstantInt::get(V->getType(), ~(*C));
5791 
5792   return nullptr;
5793 }
5794 
5795 /// Match non-obvious integer minimum and maximum sequences.
5796 static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
5797                                        Value *CmpLHS, Value *CmpRHS,
5798                                        Value *TrueVal, Value *FalseVal,
5799                                        Value *&LHS, Value *&RHS,
5800                                        unsigned Depth) {
5801   // Assume success. If there's no match, callers should not use these anyway.
5802   LHS = TrueVal;
5803   RHS = FalseVal;
5804 
5805   SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
5806   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
5807     return SPR;
5808 
5809   SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
5810   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
5811     return SPR;
5812 
5813   // Look through 'not' ops to find disguised min/max.
5814   // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
5815   // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
5816   if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
5817     switch (Pred) {
5818     case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
5819     case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
5820     case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
5821     case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
5822     default: break;
5823     }
5824   }
5825 
5826   // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
5827   // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
5828   if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
5829     switch (Pred) {
5830     case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
5831     case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
5832     case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
5833     case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
5834     default: break;
5835     }
5836   }
5837 
5838   if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
5839     return {SPF_UNKNOWN, SPNB_NA, false};
5840 
5841   // Z = X -nsw Y
5842   // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
5843   // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
5844   if (match(TrueVal, m_Zero()) &&
5845       match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
5846     return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
5847 
5848   // Z = X -nsw Y
5849   // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
5850   // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
5851   if (match(FalseVal, m_Zero()) &&
5852       match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
5853     return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
5854 
5855   const APInt *C1;
5856   if (!match(CmpRHS, m_APInt(C1)))
5857     return {SPF_UNKNOWN, SPNB_NA, false};
5858 
5859   // An unsigned min/max can be written with a signed compare.
5860   const APInt *C2;
5861   if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
5862       (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
5863     // Is the sign bit set?
5864     // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
5865     // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
5866     if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
5867         C2->isMaxSignedValue())
5868       return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
5869 
5870     // Is the sign bit clear?
5871     // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
5872     // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
5873     if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
5874         C2->isMinSignedValue())
5875       return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
5876   }
5877 
5878   return {SPF_UNKNOWN, SPNB_NA, false};
5879 }
5880 
5881 bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
5882   assert(X && Y && "Invalid operand");
5883 
5884   // X = sub (0, Y) || X = sub nsw (0, Y)
5885   if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
5886       (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
5887     return true;
5888 
5889   // Y = sub (0, X) || Y = sub nsw (0, X)
5890   if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
5891       (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
5892     return true;
5893 
5894   // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
5895   Value *A, *B;
5896   return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
5897                         match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
5898          (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
5899                        match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
5900 }
5901 
5902 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
5903                                               FastMathFlags FMF,
5904                                               Value *CmpLHS, Value *CmpRHS,
5905                                               Value *TrueVal, Value *FalseVal,
5906                                               Value *&LHS, Value *&RHS,
5907                                               unsigned Depth) {
5908   if (CmpInst::isFPPredicate(Pred)) {
5909     // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
5910     // 0.0 operand, set the compare's 0.0 operands to that same value for the
5911     // purpose of identifying min/max. Disregard vector constants with undefined
5912     // elements because those can not be back-propagated for analysis.
5913     Value *OutputZeroVal = nullptr;
5914     if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
5915         !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
5916       OutputZeroVal = TrueVal;
5917     else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
5918              !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
5919       OutputZeroVal = FalseVal;
5920 
5921     if (OutputZeroVal) {
5922       if (match(CmpLHS, m_AnyZeroFP()))
5923         CmpLHS = OutputZeroVal;
5924       if (match(CmpRHS, m_AnyZeroFP()))
5925         CmpRHS = OutputZeroVal;
5926     }
5927   }
5928 
5929   LHS = CmpLHS;
5930   RHS = CmpRHS;
5931 
5932   // Signed zero may return inconsistent results between implementations.
5933   //  (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
5934   //  minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
5935   // Therefore, we behave conservatively and only proceed if at least one of the
5936   // operands is known to not be zero or if we don't care about signed zero.
5937   switch (Pred) {
5938   default: break;
5939   // FIXME: Include OGT/OLT/UGT/ULT.
5940   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
5941   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
5942     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
5943         !isKnownNonZero(CmpRHS))
5944       return {SPF_UNKNOWN, SPNB_NA, false};
5945   }
5946 
5947   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
5948   bool Ordered = false;
5949 
5950   // When given one NaN and one non-NaN input:
5951   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
5952   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
5953   //     ordered comparison fails), which could be NaN or non-NaN.
5954   // so here we discover exactly what NaN behavior is required/accepted.
5955   if (CmpInst::isFPPredicate(Pred)) {
5956     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
5957     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
5958 
5959     if (LHSSafe && RHSSafe) {
5960       // Both operands are known non-NaN.
5961       NaNBehavior = SPNB_RETURNS_ANY;
5962     } else if (CmpInst::isOrdered(Pred)) {
5963       // An ordered comparison will return false when given a NaN, so it
5964       // returns the RHS.
5965       Ordered = true;
5966       if (LHSSafe)
5967         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
5968         NaNBehavior = SPNB_RETURNS_NAN;
5969       else if (RHSSafe)
5970         NaNBehavior = SPNB_RETURNS_OTHER;
5971       else
5972         // Completely unsafe.
5973         return {SPF_UNKNOWN, SPNB_NA, false};
5974     } else {
5975       Ordered = false;
5976       // An unordered comparison will return true when given a NaN, so it
5977       // returns the LHS.
5978       if (LHSSafe)
5979         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
5980         NaNBehavior = SPNB_RETURNS_OTHER;
5981       else if (RHSSafe)
5982         NaNBehavior = SPNB_RETURNS_NAN;
5983       else
5984         // Completely unsafe.
5985         return {SPF_UNKNOWN, SPNB_NA, false};
5986     }
5987   }
5988 
5989   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
5990     std::swap(CmpLHS, CmpRHS);
5991     Pred = CmpInst::getSwappedPredicate(Pred);
5992     if (NaNBehavior == SPNB_RETURNS_NAN)
5993       NaNBehavior = SPNB_RETURNS_OTHER;
5994     else if (NaNBehavior == SPNB_RETURNS_OTHER)
5995       NaNBehavior = SPNB_RETURNS_NAN;
5996     Ordered = !Ordered;
5997   }
5998 
5999   // ([if]cmp X, Y) ? X : Y
6000   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
6001     switch (Pred) {
6002     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
6003     case ICmpInst::ICMP_UGT:
6004     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
6005     case ICmpInst::ICMP_SGT:
6006     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
6007     case ICmpInst::ICMP_ULT:
6008     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
6009     case ICmpInst::ICMP_SLT:
6010     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
6011     case FCmpInst::FCMP_UGT:
6012     case FCmpInst::FCMP_UGE:
6013     case FCmpInst::FCMP_OGT:
6014     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
6015     case FCmpInst::FCMP_ULT:
6016     case FCmpInst::FCMP_ULE:
6017     case FCmpInst::FCMP_OLT:
6018     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
6019     }
6020   }
6021 
6022   if (isKnownNegation(TrueVal, FalseVal)) {
6023     // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
6024     // match against either LHS or sext(LHS).
6025     auto MaybeSExtCmpLHS =
6026         m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
6027     auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
6028     auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
6029     if (match(TrueVal, MaybeSExtCmpLHS)) {
6030       // Set the return values. If the compare uses the negated value (-X >s 0),
6031       // swap the return values because the negated value is always 'RHS'.
6032       LHS = TrueVal;
6033       RHS = FalseVal;
6034       if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
6035         std::swap(LHS, RHS);
6036 
6037       // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
6038       // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
6039       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
6040         return {SPF_ABS, SPNB_NA, false};
6041 
6042       // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
6043       if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
6044         return {SPF_ABS, SPNB_NA, false};
6045 
6046       // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
6047       // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
6048       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
6049         return {SPF_NABS, SPNB_NA, false};
6050     }
6051     else if (match(FalseVal, MaybeSExtCmpLHS)) {
6052       // Set the return values. If the compare uses the negated value (-X >s 0),
6053       // swap the return values because the negated value is always 'RHS'.
6054       LHS = FalseVal;
6055       RHS = TrueVal;
6056       if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
6057         std::swap(LHS, RHS);
6058 
6059       // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
6060       // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
6061       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
6062         return {SPF_NABS, SPNB_NA, false};
6063 
6064       // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
6065       // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
6066       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
6067         return {SPF_ABS, SPNB_NA, false};
6068     }
6069   }
6070 
6071   if (CmpInst::isIntPredicate(Pred))
6072     return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
6073 
6074   // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
6075   // may return either -0.0 or 0.0, so fcmp/select pair has stricter
6076   // semantics than minNum. Be conservative in such case.
6077   if (NaNBehavior != SPNB_RETURNS_ANY ||
6078       (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
6079        !isKnownNonZero(CmpRHS)))
6080     return {SPF_UNKNOWN, SPNB_NA, false};
6081 
6082   return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
6083 }
6084 
6085 /// Helps to match a select pattern in case of a type mismatch.
6086 ///
6087 /// The function processes the case when type of true and false values of a
6088 /// select instruction differs from type of the cmp instruction operands because
6089 /// of a cast instruction. The function checks if it is legal to move the cast
6090 /// operation after "select". If yes, it returns the new second value of
6091 /// "select" (with the assumption that cast is moved):
6092 /// 1. As operand of cast instruction when both values of "select" are same cast
6093 /// instructions.
6094 /// 2. As restored constant (by applying reverse cast operation) when the first
6095 /// value of the "select" is a cast operation and the second value is a
6096 /// constant.
6097 /// NOTE: We return only the new second value because the first value could be
6098 /// accessed as operand of cast instruction.
6099 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
6100                               Instruction::CastOps *CastOp) {
6101   auto *Cast1 = dyn_cast<CastInst>(V1);
6102   if (!Cast1)
6103     return nullptr;
6104 
6105   *CastOp = Cast1->getOpcode();
6106   Type *SrcTy = Cast1->getSrcTy();
6107   if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
6108     // If V1 and V2 are both the same cast from the same type, look through V1.
6109     if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
6110       return Cast2->getOperand(0);
6111     return nullptr;
6112   }
6113 
6114   auto *C = dyn_cast<Constant>(V2);
6115   if (!C)
6116     return nullptr;
6117 
6118   Constant *CastedTo = nullptr;
6119   switch (*CastOp) {
6120   case Instruction::ZExt:
6121     if (CmpI->isUnsigned())
6122       CastedTo = ConstantExpr::getTrunc(C, SrcTy);
6123     break;
6124   case Instruction::SExt:
6125     if (CmpI->isSigned())
6126       CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
6127     break;
6128   case Instruction::Trunc:
6129     Constant *CmpConst;
6130     if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
6131         CmpConst->getType() == SrcTy) {
6132       // Here we have the following case:
6133       //
6134       //   %cond = cmp iN %x, CmpConst
6135       //   %tr = trunc iN %x to iK
6136       //   %narrowsel = select i1 %cond, iK %t, iK C
6137       //
6138       // We can always move trunc after select operation:
6139       //
6140       //   %cond = cmp iN %x, CmpConst
6141       //   %widesel = select i1 %cond, iN %x, iN CmpConst
6142       //   %tr = trunc iN %widesel to iK
6143       //
6144       // Note that C could be extended in any way because we don't care about
6145       // upper bits after truncation. It can't be abs pattern, because it would
6146       // look like:
6147       //
6148       //   select i1 %cond, x, -x.
6149       //
6150       // So only min/max pattern could be matched. Such match requires widened C
6151       // == CmpConst. That is why set widened C = CmpConst, condition trunc
6152       // CmpConst == C is checked below.
6153       CastedTo = CmpConst;
6154     } else {
6155       CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
6156     }
6157     break;
6158   case Instruction::FPTrunc:
6159     CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
6160     break;
6161   case Instruction::FPExt:
6162     CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
6163     break;
6164   case Instruction::FPToUI:
6165     CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
6166     break;
6167   case Instruction::FPToSI:
6168     CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
6169     break;
6170   case Instruction::UIToFP:
6171     CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
6172     break;
6173   case Instruction::SIToFP:
6174     CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
6175     break;
6176   default:
6177     break;
6178   }
6179 
6180   if (!CastedTo)
6181     return nullptr;
6182 
6183   // Make sure the cast doesn't lose any information.
6184   Constant *CastedBack =
6185       ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
6186   if (CastedBack != C)
6187     return nullptr;
6188 
6189   return CastedTo;
6190 }
6191 
6192 SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
6193                                              Instruction::CastOps *CastOp,
6194                                              unsigned Depth) {
6195   if (Depth >= MaxAnalysisRecursionDepth)
6196     return {SPF_UNKNOWN, SPNB_NA, false};
6197 
6198   SelectInst *SI = dyn_cast<SelectInst>(V);
6199   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
6200 
6201   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
6202   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
6203 
6204   Value *TrueVal = SI->getTrueValue();
6205   Value *FalseVal = SI->getFalseValue();
6206 
6207   return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
6208                                             CastOp, Depth);
6209 }
6210 
6211 SelectPatternResult llvm::matchDecomposedSelectPattern(
6212     CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
6213     Instruction::CastOps *CastOp, unsigned Depth) {
6214   CmpInst::Predicate Pred = CmpI->getPredicate();
6215   Value *CmpLHS = CmpI->getOperand(0);
6216   Value *CmpRHS = CmpI->getOperand(1);
6217   FastMathFlags FMF;
6218   if (isa<FPMathOperator>(CmpI))
6219     FMF = CmpI->getFastMathFlags();
6220 
6221   // Bail out early.
6222   if (CmpI->isEquality())
6223     return {SPF_UNKNOWN, SPNB_NA, false};
6224 
6225   // Deal with type mismatches.
6226   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
6227     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
6228       // If this is a potential fmin/fmax with a cast to integer, then ignore
6229       // -0.0 because there is no corresponding integer value.
6230       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
6231         FMF.setNoSignedZeros();
6232       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
6233                                   cast<CastInst>(TrueVal)->getOperand(0), C,
6234                                   LHS, RHS, Depth);
6235     }
6236     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
6237       // If this is a potential fmin/fmax with a cast to integer, then ignore
6238       // -0.0 because there is no corresponding integer value.
6239       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
6240         FMF.setNoSignedZeros();
6241       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
6242                                   C, cast<CastInst>(FalseVal)->getOperand(0),
6243                                   LHS, RHS, Depth);
6244     }
6245   }
6246   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
6247                               LHS, RHS, Depth);
6248 }
6249 
6250 CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
6251   if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
6252   if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
6253   if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
6254   if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
6255   if (SPF == SPF_FMINNUM)
6256     return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
6257   if (SPF == SPF_FMAXNUM)
6258     return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
6259   llvm_unreachable("unhandled!");
6260 }
6261 
6262 SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
6263   if (SPF == SPF_SMIN) return SPF_SMAX;
6264   if (SPF == SPF_UMIN) return SPF_UMAX;
6265   if (SPF == SPF_SMAX) return SPF_SMIN;
6266   if (SPF == SPF_UMAX) return SPF_UMIN;
6267   llvm_unreachable("unhandled!");
6268 }
6269 
6270 Intrinsic::ID llvm::getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID) {
6271   switch (MinMaxID) {
6272   case Intrinsic::smax: return Intrinsic::smin;
6273   case Intrinsic::smin: return Intrinsic::smax;
6274   case Intrinsic::umax: return Intrinsic::umin;
6275   case Intrinsic::umin: return Intrinsic::umax;
6276   default: llvm_unreachable("Unexpected intrinsic");
6277   }
6278 }
6279 
6280 CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
6281   return getMinMaxPred(getInverseMinMaxFlavor(SPF));
6282 }
6283 
6284 APInt llvm::getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth) {
6285   switch (SPF) {
6286   case SPF_SMAX: return APInt::getSignedMaxValue(BitWidth);
6287   case SPF_SMIN: return APInt::getSignedMinValue(BitWidth);
6288   case SPF_UMAX: return APInt::getMaxValue(BitWidth);
6289   case SPF_UMIN: return APInt::getMinValue(BitWidth);
6290   default: llvm_unreachable("Unexpected flavor");
6291   }
6292 }
6293 
6294 std::pair<Intrinsic::ID, bool>
6295 llvm::canConvertToMinOrMaxIntrinsic(ArrayRef<Value *> VL) {
6296   // Check if VL contains select instructions that can be folded into a min/max
6297   // vector intrinsic and return the intrinsic if it is possible.
6298   // TODO: Support floating point min/max.
6299   bool AllCmpSingleUse = true;
6300   SelectPatternResult SelectPattern;
6301   SelectPattern.Flavor = SPF_UNKNOWN;
6302   if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
6303         Value *LHS, *RHS;
6304         auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
6305         if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor) ||
6306             CurrentPattern.Flavor == SPF_FMINNUM ||
6307             CurrentPattern.Flavor == SPF_FMAXNUM ||
6308             !I->getType()->isIntOrIntVectorTy())
6309           return false;
6310         if (SelectPattern.Flavor != SPF_UNKNOWN &&
6311             SelectPattern.Flavor != CurrentPattern.Flavor)
6312           return false;
6313         SelectPattern = CurrentPattern;
6314         AllCmpSingleUse &=
6315             match(I, m_Select(m_OneUse(m_Value()), m_Value(), m_Value()));
6316         return true;
6317       })) {
6318     switch (SelectPattern.Flavor) {
6319     case SPF_SMIN:
6320       return {Intrinsic::smin, AllCmpSingleUse};
6321     case SPF_UMIN:
6322       return {Intrinsic::umin, AllCmpSingleUse};
6323     case SPF_SMAX:
6324       return {Intrinsic::smax, AllCmpSingleUse};
6325     case SPF_UMAX:
6326       return {Intrinsic::umax, AllCmpSingleUse};
6327     default:
6328       llvm_unreachable("unexpected select pattern flavor");
6329     }
6330   }
6331   return {Intrinsic::not_intrinsic, false};
6332 }
6333 
6334 bool llvm::matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO,
6335                                  Value *&Start, Value *&Step) {
6336   // Handle the case of a simple two-predecessor recurrence PHI.
6337   // There's a lot more that could theoretically be done here, but
6338   // this is sufficient to catch some interesting cases.
6339   if (P->getNumIncomingValues() != 2)
6340     return false;
6341 
6342   for (unsigned i = 0; i != 2; ++i) {
6343     Value *L = P->getIncomingValue(i);
6344     Value *R = P->getIncomingValue(!i);
6345     Operator *LU = dyn_cast<Operator>(L);
6346     if (!LU)
6347       continue;
6348     unsigned Opcode = LU->getOpcode();
6349 
6350     switch (Opcode) {
6351     default:
6352       continue;
6353     // TODO: Expand list -- xor, div, gep, uaddo, etc..
6354     case Instruction::LShr:
6355     case Instruction::AShr:
6356     case Instruction::Shl:
6357     case Instruction::Add:
6358     case Instruction::Sub:
6359     case Instruction::And:
6360     case Instruction::Or:
6361     case Instruction::Mul: {
6362       Value *LL = LU->getOperand(0);
6363       Value *LR = LU->getOperand(1);
6364       // Find a recurrence.
6365       if (LL == P)
6366         L = LR;
6367       else if (LR == P)
6368         L = LL;
6369       else
6370         continue; // Check for recurrence with L and R flipped.
6371 
6372       break; // Match!
6373     }
6374     };
6375 
6376     // We have matched a recurrence of the form:
6377     //   %iv = [R, %entry], [%iv.next, %backedge]
6378     //   %iv.next = binop %iv, L
6379     // OR
6380     //   %iv = [R, %entry], [%iv.next, %backedge]
6381     //   %iv.next = binop L, %iv
6382     BO = cast<BinaryOperator>(LU);
6383     Start = R;
6384     Step = L;
6385     return true;
6386   }
6387   return false;
6388 }
6389 
6390 bool llvm::matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P,
6391                                  Value *&Start, Value *&Step) {
6392   BinaryOperator *BO = nullptr;
6393   P = dyn_cast<PHINode>(I->getOperand(0));
6394   if (!P)
6395     P = dyn_cast<PHINode>(I->getOperand(1));
6396   return P && matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
6397 }
6398 
6399 /// Return true if "icmp Pred LHS RHS" is always true.
6400 static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
6401                             const Value *RHS, const DataLayout &DL,
6402                             unsigned Depth) {
6403   assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
6404   if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
6405     return true;
6406 
6407   switch (Pred) {
6408   default:
6409     return false;
6410 
6411   case CmpInst::ICMP_SLE: {
6412     const APInt *C;
6413 
6414     // LHS s<= LHS +_{nsw} C   if C >= 0
6415     if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
6416       return !C->isNegative();
6417     return false;
6418   }
6419 
6420   case CmpInst::ICMP_ULE: {
6421     const APInt *C;
6422 
6423     // LHS u<= LHS +_{nuw} C   for any C
6424     if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
6425       return true;
6426 
6427     // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
6428     auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
6429                                        const Value *&X,
6430                                        const APInt *&CA, const APInt *&CB) {
6431       if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
6432           match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
6433         return true;
6434 
6435       // If X & C == 0 then (X | C) == X +_{nuw} C
6436       if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
6437           match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
6438         KnownBits Known(CA->getBitWidth());
6439         computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
6440                          /*CxtI*/ nullptr, /*DT*/ nullptr);
6441         if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
6442           return true;
6443       }
6444 
6445       return false;
6446     };
6447 
6448     const Value *X;
6449     const APInt *CLHS, *CRHS;
6450     if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
6451       return CLHS->ule(*CRHS);
6452 
6453     return false;
6454   }
6455   }
6456 }
6457 
6458 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
6459 /// ALHS ARHS" is true.  Otherwise, return None.
6460 static Optional<bool>
6461 isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
6462                       const Value *ARHS, const Value *BLHS, const Value *BRHS,
6463                       const DataLayout &DL, unsigned Depth) {
6464   switch (Pred) {
6465   default:
6466     return None;
6467 
6468   case CmpInst::ICMP_SLT:
6469   case CmpInst::ICMP_SLE:
6470     if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
6471         isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
6472       return true;
6473     return None;
6474 
6475   case CmpInst::ICMP_ULT:
6476   case CmpInst::ICMP_ULE:
6477     if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
6478         isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
6479       return true;
6480     return None;
6481   }
6482 }
6483 
6484 /// Return true if the operands of the two compares match.  IsSwappedOps is true
6485 /// when the operands match, but are swapped.
6486 static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
6487                           const Value *BLHS, const Value *BRHS,
6488                           bool &IsSwappedOps) {
6489 
6490   bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
6491   IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
6492   return IsMatchingOps || IsSwappedOps;
6493 }
6494 
6495 /// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
6496 /// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
6497 /// Otherwise, return None if we can't infer anything.
6498 static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
6499                                                     CmpInst::Predicate BPred,
6500                                                     bool AreSwappedOps) {
6501   // Canonicalize the predicate as if the operands were not commuted.
6502   if (AreSwappedOps)
6503     BPred = ICmpInst::getSwappedPredicate(BPred);
6504 
6505   if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
6506     return true;
6507   if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
6508     return false;
6509 
6510   return None;
6511 }
6512 
6513 /// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
6514 /// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
6515 /// Otherwise, return None if we can't infer anything.
6516 static Optional<bool>
6517 isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
6518                                  const ConstantInt *C1,
6519                                  CmpInst::Predicate BPred,
6520                                  const ConstantInt *C2) {
6521   ConstantRange DomCR =
6522       ConstantRange::makeExactICmpRegion(APred, C1->getValue());
6523   ConstantRange CR = ConstantRange::makeExactICmpRegion(BPred, C2->getValue());
6524   ConstantRange Intersection = DomCR.intersectWith(CR);
6525   ConstantRange Difference = DomCR.difference(CR);
6526   if (Intersection.isEmptySet())
6527     return false;
6528   if (Difference.isEmptySet())
6529     return true;
6530   return None;
6531 }
6532 
6533 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
6534 /// false.  Otherwise, return None if we can't infer anything.
6535 static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
6536                                          CmpInst::Predicate BPred,
6537                                          const Value *BLHS, const Value *BRHS,
6538                                          const DataLayout &DL, bool LHSIsTrue,
6539                                          unsigned Depth) {
6540   Value *ALHS = LHS->getOperand(0);
6541   Value *ARHS = LHS->getOperand(1);
6542 
6543   // The rest of the logic assumes the LHS condition is true.  If that's not the
6544   // case, invert the predicate to make it so.
6545   CmpInst::Predicate APred =
6546       LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
6547 
6548   // Can we infer anything when the two compares have matching operands?
6549   bool AreSwappedOps;
6550   if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
6551     if (Optional<bool> Implication = isImpliedCondMatchingOperands(
6552             APred, BPred, AreSwappedOps))
6553       return Implication;
6554     // No amount of additional analysis will infer the second condition, so
6555     // early exit.
6556     return None;
6557   }
6558 
6559   // Can we infer anything when the LHS operands match and the RHS operands are
6560   // constants (not necessarily matching)?
6561   if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
6562     if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
6563             APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
6564       return Implication;
6565     // No amount of additional analysis will infer the second condition, so
6566     // early exit.
6567     return None;
6568   }
6569 
6570   if (APred == BPred)
6571     return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
6572   return None;
6573 }
6574 
6575 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
6576 /// false.  Otherwise, return None if we can't infer anything.  We expect the
6577 /// RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select' instruction.
6578 static Optional<bool>
6579 isImpliedCondAndOr(const Instruction *LHS, CmpInst::Predicate RHSPred,
6580                    const Value *RHSOp0, const Value *RHSOp1,
6581                    const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
6582   // The LHS must be an 'or', 'and', or a 'select' instruction.
6583   assert((LHS->getOpcode() == Instruction::And ||
6584           LHS->getOpcode() == Instruction::Or ||
6585           LHS->getOpcode() == Instruction::Select) &&
6586          "Expected LHS to be 'and', 'or', or 'select'.");
6587 
6588   assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
6589 
6590   // If the result of an 'or' is false, then we know both legs of the 'or' are
6591   // false.  Similarly, if the result of an 'and' is true, then we know both
6592   // legs of the 'and' are true.
6593   const Value *ALHS, *ARHS;
6594   if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
6595       (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
6596     // FIXME: Make this non-recursion.
6597     if (Optional<bool> Implication = isImpliedCondition(
6598             ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
6599       return Implication;
6600     if (Optional<bool> Implication = isImpliedCondition(
6601             ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
6602       return Implication;
6603     return None;
6604   }
6605   return None;
6606 }
6607 
6608 Optional<bool>
6609 llvm::isImpliedCondition(const Value *LHS, CmpInst::Predicate RHSPred,
6610                          const Value *RHSOp0, const Value *RHSOp1,
6611                          const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
6612   // Bail out when we hit the limit.
6613   if (Depth == MaxAnalysisRecursionDepth)
6614     return None;
6615 
6616   // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
6617   // example.
6618   if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
6619     return None;
6620 
6621   Type *OpTy = LHS->getType();
6622   assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
6623 
6624   // FIXME: Extending the code below to handle vectors.
6625   if (OpTy->isVectorTy())
6626     return None;
6627 
6628   assert(OpTy->isIntegerTy(1) && "implied by above");
6629 
6630   // Both LHS and RHS are icmps.
6631   const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
6632   if (LHSCmp)
6633     return isImpliedCondICmps(LHSCmp, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
6634                               Depth);
6635 
6636   /// The LHS should be an 'or', 'and', or a 'select' instruction.  We expect
6637   /// the RHS to be an icmp.
6638   /// FIXME: Add support for and/or/select on the RHS.
6639   if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
6640     if ((LHSI->getOpcode() == Instruction::And ||
6641          LHSI->getOpcode() == Instruction::Or ||
6642          LHSI->getOpcode() == Instruction::Select))
6643       return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
6644                                 Depth);
6645   }
6646   return None;
6647 }
6648 
6649 Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
6650                                         const DataLayout &DL, bool LHSIsTrue,
6651                                         unsigned Depth) {
6652   // LHS ==> RHS by definition
6653   if (LHS == RHS)
6654     return LHSIsTrue;
6655 
6656   const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
6657   if (RHSCmp)
6658     return isImpliedCondition(LHS, RHSCmp->getPredicate(),
6659                               RHSCmp->getOperand(0), RHSCmp->getOperand(1), DL,
6660                               LHSIsTrue, Depth);
6661   return None;
6662 }
6663 
6664 // Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
6665 // condition dominating ContextI or nullptr, if no condition is found.
6666 static std::pair<Value *, bool>
6667 getDomPredecessorCondition(const Instruction *ContextI) {
6668   if (!ContextI || !ContextI->getParent())
6669     return {nullptr, false};
6670 
6671   // TODO: This is a poor/cheap way to determine dominance. Should we use a
6672   // dominator tree (eg, from a SimplifyQuery) instead?
6673   const BasicBlock *ContextBB = ContextI->getParent();
6674   const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
6675   if (!PredBB)
6676     return {nullptr, false};
6677 
6678   // We need a conditional branch in the predecessor.
6679   Value *PredCond;
6680   BasicBlock *TrueBB, *FalseBB;
6681   if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
6682     return {nullptr, false};
6683 
6684   // The branch should get simplified. Don't bother simplifying this condition.
6685   if (TrueBB == FalseBB)
6686     return {nullptr, false};
6687 
6688   assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
6689          "Predecessor block does not point to successor?");
6690 
6691   // Is this condition implied by the predecessor condition?
6692   return {PredCond, TrueBB == ContextBB};
6693 }
6694 
6695 Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
6696                                              const Instruction *ContextI,
6697                                              const DataLayout &DL) {
6698   assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
6699   auto PredCond = getDomPredecessorCondition(ContextI);
6700   if (PredCond.first)
6701     return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
6702   return None;
6703 }
6704 
6705 Optional<bool> llvm::isImpliedByDomCondition(CmpInst::Predicate Pred,
6706                                              const Value *LHS, const Value *RHS,
6707                                              const Instruction *ContextI,
6708                                              const DataLayout &DL) {
6709   auto PredCond = getDomPredecessorCondition(ContextI);
6710   if (PredCond.first)
6711     return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
6712                               PredCond.second);
6713   return None;
6714 }
6715 
6716 static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
6717                               APInt &Upper, const InstrInfoQuery &IIQ) {
6718   unsigned Width = Lower.getBitWidth();
6719   const APInt *C;
6720   switch (BO.getOpcode()) {
6721   case Instruction::Add:
6722     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
6723       // FIXME: If we have both nuw and nsw, we should reduce the range further.
6724       if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
6725         // 'add nuw x, C' produces [C, UINT_MAX].
6726         Lower = *C;
6727       } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
6728         if (C->isNegative()) {
6729           // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
6730           Lower = APInt::getSignedMinValue(Width);
6731           Upper = APInt::getSignedMaxValue(Width) + *C + 1;
6732         } else {
6733           // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
6734           Lower = APInt::getSignedMinValue(Width) + *C;
6735           Upper = APInt::getSignedMaxValue(Width) + 1;
6736         }
6737       }
6738     }
6739     break;
6740 
6741   case Instruction::And:
6742     if (match(BO.getOperand(1), m_APInt(C)))
6743       // 'and x, C' produces [0, C].
6744       Upper = *C + 1;
6745     break;
6746 
6747   case Instruction::Or:
6748     if (match(BO.getOperand(1), m_APInt(C)))
6749       // 'or x, C' produces [C, UINT_MAX].
6750       Lower = *C;
6751     break;
6752 
6753   case Instruction::AShr:
6754     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
6755       // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
6756       Lower = APInt::getSignedMinValue(Width).ashr(*C);
6757       Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
6758     } else if (match(BO.getOperand(0), m_APInt(C))) {
6759       unsigned ShiftAmount = Width - 1;
6760       if (!C->isNullValue() && IIQ.isExact(&BO))
6761         ShiftAmount = C->countTrailingZeros();
6762       if (C->isNegative()) {
6763         // 'ashr C, x' produces [C, C >> (Width-1)]
6764         Lower = *C;
6765         Upper = C->ashr(ShiftAmount) + 1;
6766       } else {
6767         // 'ashr C, x' produces [C >> (Width-1), C]
6768         Lower = C->ashr(ShiftAmount);
6769         Upper = *C + 1;
6770       }
6771     }
6772     break;
6773 
6774   case Instruction::LShr:
6775     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
6776       // 'lshr x, C' produces [0, UINT_MAX >> C].
6777       Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
6778     } else if (match(BO.getOperand(0), m_APInt(C))) {
6779       // 'lshr C, x' produces [C >> (Width-1), C].
6780       unsigned ShiftAmount = Width - 1;
6781       if (!C->isNullValue() && IIQ.isExact(&BO))
6782         ShiftAmount = C->countTrailingZeros();
6783       Lower = C->lshr(ShiftAmount);
6784       Upper = *C + 1;
6785     }
6786     break;
6787 
6788   case Instruction::Shl:
6789     if (match(BO.getOperand(0), m_APInt(C))) {
6790       if (IIQ.hasNoUnsignedWrap(&BO)) {
6791         // 'shl nuw C, x' produces [C, C << CLZ(C)]
6792         Lower = *C;
6793         Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
6794       } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
6795         if (C->isNegative()) {
6796           // 'shl nsw C, x' produces [C << CLO(C)-1, C]
6797           unsigned ShiftAmount = C->countLeadingOnes() - 1;
6798           Lower = C->shl(ShiftAmount);
6799           Upper = *C + 1;
6800         } else {
6801           // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
6802           unsigned ShiftAmount = C->countLeadingZeros() - 1;
6803           Lower = *C;
6804           Upper = C->shl(ShiftAmount) + 1;
6805         }
6806       }
6807     }
6808     break;
6809 
6810   case Instruction::SDiv:
6811     if (match(BO.getOperand(1), m_APInt(C))) {
6812       APInt IntMin = APInt::getSignedMinValue(Width);
6813       APInt IntMax = APInt::getSignedMaxValue(Width);
6814       if (C->isAllOnesValue()) {
6815         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
6816         //    where C != -1 and C != 0 and C != 1
6817         Lower = IntMin + 1;
6818         Upper = IntMax + 1;
6819       } else if (C->countLeadingZeros() < Width - 1) {
6820         // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
6821         //    where C != -1 and C != 0 and C != 1
6822         Lower = IntMin.sdiv(*C);
6823         Upper = IntMax.sdiv(*C);
6824         if (Lower.sgt(Upper))
6825           std::swap(Lower, Upper);
6826         Upper = Upper + 1;
6827         assert(Upper != Lower && "Upper part of range has wrapped!");
6828       }
6829     } else if (match(BO.getOperand(0), m_APInt(C))) {
6830       if (C->isMinSignedValue()) {
6831         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
6832         Lower = *C;
6833         Upper = Lower.lshr(1) + 1;
6834       } else {
6835         // 'sdiv C, x' produces [-|C|, |C|].
6836         Upper = C->abs() + 1;
6837         Lower = (-Upper) + 1;
6838       }
6839     }
6840     break;
6841 
6842   case Instruction::UDiv:
6843     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
6844       // 'udiv x, C' produces [0, UINT_MAX / C].
6845       Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
6846     } else if (match(BO.getOperand(0), m_APInt(C))) {
6847       // 'udiv C, x' produces [0, C].
6848       Upper = *C + 1;
6849     }
6850     break;
6851 
6852   case Instruction::SRem:
6853     if (match(BO.getOperand(1), m_APInt(C))) {
6854       // 'srem x, C' produces (-|C|, |C|).
6855       Upper = C->abs();
6856       Lower = (-Upper) + 1;
6857     }
6858     break;
6859 
6860   case Instruction::URem:
6861     if (match(BO.getOperand(1), m_APInt(C)))
6862       // 'urem x, C' produces [0, C).
6863       Upper = *C;
6864     break;
6865 
6866   default:
6867     break;
6868   }
6869 }
6870 
6871 static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
6872                                   APInt &Upper) {
6873   unsigned Width = Lower.getBitWidth();
6874   const APInt *C;
6875   switch (II.getIntrinsicID()) {
6876   case Intrinsic::ctpop:
6877   case Intrinsic::ctlz:
6878   case Intrinsic::cttz:
6879     // Maximum of set/clear bits is the bit width.
6880     assert(Lower == 0 && "Expected lower bound to be zero");
6881     Upper = Width + 1;
6882     break;
6883   case Intrinsic::uadd_sat:
6884     // uadd.sat(x, C) produces [C, UINT_MAX].
6885     if (match(II.getOperand(0), m_APInt(C)) ||
6886         match(II.getOperand(1), m_APInt(C)))
6887       Lower = *C;
6888     break;
6889   case Intrinsic::sadd_sat:
6890     if (match(II.getOperand(0), m_APInt(C)) ||
6891         match(II.getOperand(1), m_APInt(C))) {
6892       if (C->isNegative()) {
6893         // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
6894         Lower = APInt::getSignedMinValue(Width);
6895         Upper = APInt::getSignedMaxValue(Width) + *C + 1;
6896       } else {
6897         // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
6898         Lower = APInt::getSignedMinValue(Width) + *C;
6899         Upper = APInt::getSignedMaxValue(Width) + 1;
6900       }
6901     }
6902     break;
6903   case Intrinsic::usub_sat:
6904     // usub.sat(C, x) produces [0, C].
6905     if (match(II.getOperand(0), m_APInt(C)))
6906       Upper = *C + 1;
6907     // usub.sat(x, C) produces [0, UINT_MAX - C].
6908     else if (match(II.getOperand(1), m_APInt(C)))
6909       Upper = APInt::getMaxValue(Width) - *C + 1;
6910     break;
6911   case Intrinsic::ssub_sat:
6912     if (match(II.getOperand(0), m_APInt(C))) {
6913       if (C->isNegative()) {
6914         // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
6915         Lower = APInt::getSignedMinValue(Width);
6916         Upper = *C - APInt::getSignedMinValue(Width) + 1;
6917       } else {
6918         // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
6919         Lower = *C - APInt::getSignedMaxValue(Width);
6920         Upper = APInt::getSignedMaxValue(Width) + 1;
6921       }
6922     } else if (match(II.getOperand(1), m_APInt(C))) {
6923       if (C->isNegative()) {
6924         // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
6925         Lower = APInt::getSignedMinValue(Width) - *C;
6926         Upper = APInt::getSignedMaxValue(Width) + 1;
6927       } else {
6928         // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
6929         Lower = APInt::getSignedMinValue(Width);
6930         Upper = APInt::getSignedMaxValue(Width) - *C + 1;
6931       }
6932     }
6933     break;
6934   case Intrinsic::umin:
6935   case Intrinsic::umax:
6936   case Intrinsic::smin:
6937   case Intrinsic::smax:
6938     if (!match(II.getOperand(0), m_APInt(C)) &&
6939         !match(II.getOperand(1), m_APInt(C)))
6940       break;
6941 
6942     switch (II.getIntrinsicID()) {
6943     case Intrinsic::umin:
6944       Upper = *C + 1;
6945       break;
6946     case Intrinsic::umax:
6947       Lower = *C;
6948       break;
6949     case Intrinsic::smin:
6950       Lower = APInt::getSignedMinValue(Width);
6951       Upper = *C + 1;
6952       break;
6953     case Intrinsic::smax:
6954       Lower = *C;
6955       Upper = APInt::getSignedMaxValue(Width) + 1;
6956       break;
6957     default:
6958       llvm_unreachable("Must be min/max intrinsic");
6959     }
6960     break;
6961   case Intrinsic::abs:
6962     // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
6963     // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
6964     if (match(II.getOperand(1), m_One()))
6965       Upper = APInt::getSignedMaxValue(Width) + 1;
6966     else
6967       Upper = APInt::getSignedMinValue(Width) + 1;
6968     break;
6969   default:
6970     break;
6971   }
6972 }
6973 
6974 static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
6975                                       APInt &Upper, const InstrInfoQuery &IIQ) {
6976   const Value *LHS = nullptr, *RHS = nullptr;
6977   SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
6978   if (R.Flavor == SPF_UNKNOWN)
6979     return;
6980 
6981   unsigned BitWidth = SI.getType()->getScalarSizeInBits();
6982 
6983   if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
6984     // If the negation part of the abs (in RHS) has the NSW flag,
6985     // then the result of abs(X) is [0..SIGNED_MAX],
6986     // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
6987     Lower = APInt::getZero(BitWidth);
6988     if (match(RHS, m_Neg(m_Specific(LHS))) &&
6989         IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
6990       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
6991     else
6992       Upper = APInt::getSignedMinValue(BitWidth) + 1;
6993     return;
6994   }
6995 
6996   if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
6997     // The result of -abs(X) is <= 0.
6998     Lower = APInt::getSignedMinValue(BitWidth);
6999     Upper = APInt(BitWidth, 1);
7000     return;
7001   }
7002 
7003   const APInt *C;
7004   if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
7005     return;
7006 
7007   switch (R.Flavor) {
7008     case SPF_UMIN:
7009       Upper = *C + 1;
7010       break;
7011     case SPF_UMAX:
7012       Lower = *C;
7013       break;
7014     case SPF_SMIN:
7015       Lower = APInt::getSignedMinValue(BitWidth);
7016       Upper = *C + 1;
7017       break;
7018     case SPF_SMAX:
7019       Lower = *C;
7020       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
7021       break;
7022     default:
7023       break;
7024   }
7025 }
7026 
7027 ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo,
7028                                          AssumptionCache *AC,
7029                                          const Instruction *CtxI,
7030                                          const DominatorTree *DT,
7031                                          unsigned Depth) {
7032   assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
7033 
7034   if (Depth == MaxAnalysisRecursionDepth)
7035     return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
7036 
7037   const APInt *C;
7038   if (match(V, m_APInt(C)))
7039     return ConstantRange(*C);
7040 
7041   InstrInfoQuery IIQ(UseInstrInfo);
7042   unsigned BitWidth = V->getType()->getScalarSizeInBits();
7043   APInt Lower = APInt(BitWidth, 0);
7044   APInt Upper = APInt(BitWidth, 0);
7045   if (auto *BO = dyn_cast<BinaryOperator>(V))
7046     setLimitsForBinOp(*BO, Lower, Upper, IIQ);
7047   else if (auto *II = dyn_cast<IntrinsicInst>(V))
7048     setLimitsForIntrinsic(*II, Lower, Upper);
7049   else if (auto *SI = dyn_cast<SelectInst>(V))
7050     setLimitsForSelectPattern(*SI, Lower, Upper, IIQ);
7051 
7052   ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper);
7053 
7054   if (auto *I = dyn_cast<Instruction>(V))
7055     if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
7056       CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
7057 
7058   if (CtxI && AC) {
7059     // Try to restrict the range based on information from assumptions.
7060     for (auto &AssumeVH : AC->assumptionsFor(V)) {
7061       if (!AssumeVH)
7062         continue;
7063       CallInst *I = cast<CallInst>(AssumeVH);
7064       assert(I->getParent()->getParent() == CtxI->getParent()->getParent() &&
7065              "Got assumption for the wrong function!");
7066       assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
7067              "must be an assume intrinsic");
7068 
7069       if (!isValidAssumeForContext(I, CtxI, DT))
7070         continue;
7071       Value *Arg = I->getArgOperand(0);
7072       ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
7073       // Currently we just use information from comparisons.
7074       if (!Cmp || Cmp->getOperand(0) != V)
7075         continue;
7076       ConstantRange RHS = computeConstantRange(Cmp->getOperand(1), UseInstrInfo,
7077                                                AC, I, DT, Depth + 1);
7078       CR = CR.intersectWith(
7079           ConstantRange::makeAllowedICmpRegion(Cmp->getPredicate(), RHS));
7080     }
7081   }
7082 
7083   return CR;
7084 }
7085 
7086 static Optional<int64_t>
7087 getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) {
7088   // Skip over the first indices.
7089   gep_type_iterator GTI = gep_type_begin(GEP);
7090   for (unsigned i = 1; i != Idx; ++i, ++GTI)
7091     /*skip along*/;
7092 
7093   // Compute the offset implied by the rest of the indices.
7094   int64_t Offset = 0;
7095   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
7096     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
7097     if (!OpC)
7098       return None;
7099     if (OpC->isZero())
7100       continue; // No offset.
7101 
7102     // Handle struct indices, which add their field offset to the pointer.
7103     if (StructType *STy = GTI.getStructTypeOrNull()) {
7104       Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
7105       continue;
7106     }
7107 
7108     // Otherwise, we have a sequential type like an array or fixed-length
7109     // vector. Multiply the index by the ElementSize.
7110     TypeSize Size = DL.getTypeAllocSize(GTI.getIndexedType());
7111     if (Size.isScalable())
7112       return None;
7113     Offset += Size.getFixedSize() * OpC->getSExtValue();
7114   }
7115 
7116   return Offset;
7117 }
7118 
7119 Optional<int64_t> llvm::isPointerOffset(const Value *Ptr1, const Value *Ptr2,
7120                                         const DataLayout &DL) {
7121   Ptr1 = Ptr1->stripPointerCasts();
7122   Ptr2 = Ptr2->stripPointerCasts();
7123 
7124   // Handle the trivial case first.
7125   if (Ptr1 == Ptr2) {
7126     return 0;
7127   }
7128 
7129   const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
7130   const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
7131 
7132   // If one pointer is a GEP see if the GEP is a constant offset from the base,
7133   // as in "P" and "gep P, 1".
7134   // Also do this iteratively to handle the the following case:
7135   //   Ptr_t1 = GEP Ptr1, c1
7136   //   Ptr_t2 = GEP Ptr_t1, c2
7137   //   Ptr2 = GEP Ptr_t2, c3
7138   // where we will return c1+c2+c3.
7139   // TODO: Handle the case when both Ptr1 and Ptr2 are GEPs of some common base
7140   // -- replace getOffsetFromBase with getOffsetAndBase, check that the bases
7141   // are the same, and return the difference between offsets.
7142   auto getOffsetFromBase = [&DL](const GEPOperator *GEP,
7143                                  const Value *Ptr) -> Optional<int64_t> {
7144     const GEPOperator *GEP_T = GEP;
7145     int64_t OffsetVal = 0;
7146     bool HasSameBase = false;
7147     while (GEP_T) {
7148       auto Offset = getOffsetFromIndex(GEP_T, 1, DL);
7149       if (!Offset)
7150         return None;
7151       OffsetVal += *Offset;
7152       auto Op0 = GEP_T->getOperand(0)->stripPointerCasts();
7153       if (Op0 == Ptr) {
7154         HasSameBase = true;
7155         break;
7156       }
7157       GEP_T = dyn_cast<GEPOperator>(Op0);
7158     }
7159     if (!HasSameBase)
7160       return None;
7161     return OffsetVal;
7162   };
7163 
7164   if (GEP1) {
7165     auto Offset = getOffsetFromBase(GEP1, Ptr2);
7166     if (Offset)
7167       return -*Offset;
7168   }
7169   if (GEP2) {
7170     auto Offset = getOffsetFromBase(GEP2, Ptr1);
7171     if (Offset)
7172       return Offset;
7173   }
7174 
7175   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
7176   // base.  After that base, they may have some number of common (and
7177   // potentially variable) indices.  After that they handle some constant
7178   // offset, which determines their offset from each other.  At this point, we
7179   // handle no other case.
7180   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
7181     return None;
7182 
7183   // Skip any common indices and track the GEP types.
7184   unsigned Idx = 1;
7185   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
7186     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
7187       break;
7188 
7189   auto Offset1 = getOffsetFromIndex(GEP1, Idx, DL);
7190   auto Offset2 = getOffsetFromIndex(GEP2, Idx, DL);
7191   if (!Offset1 || !Offset2)
7192     return None;
7193   return *Offset2 - *Offset1;
7194 }
7195