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