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