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