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