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