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