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