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