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