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