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