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