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