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