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