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