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