106f32e7eSjoerg //===- ValueTracking.cpp - Walk computations to compute properties --------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file contains routines that help analyze properties that chains of
1006f32e7eSjoerg // computations have.
1106f32e7eSjoerg //
1206f32e7eSjoerg //===----------------------------------------------------------------------===//
1306f32e7eSjoerg 
1406f32e7eSjoerg #include "llvm/Analysis/ValueTracking.h"
1506f32e7eSjoerg #include "llvm/ADT/APFloat.h"
1606f32e7eSjoerg #include "llvm/ADT/APInt.h"
1706f32e7eSjoerg #include "llvm/ADT/ArrayRef.h"
1806f32e7eSjoerg #include "llvm/ADT/None.h"
1906f32e7eSjoerg #include "llvm/ADT/Optional.h"
2006f32e7eSjoerg #include "llvm/ADT/STLExtras.h"
2106f32e7eSjoerg #include "llvm/ADT/SmallPtrSet.h"
2206f32e7eSjoerg #include "llvm/ADT/SmallSet.h"
2306f32e7eSjoerg #include "llvm/ADT/SmallVector.h"
2406f32e7eSjoerg #include "llvm/ADT/StringRef.h"
2506f32e7eSjoerg #include "llvm/ADT/iterator_range.h"
2606f32e7eSjoerg #include "llvm/Analysis/AliasAnalysis.h"
27*da58b97aSjoerg #include "llvm/Analysis/AssumeBundleQueries.h"
2806f32e7eSjoerg #include "llvm/Analysis/AssumptionCache.h"
2906f32e7eSjoerg #include "llvm/Analysis/GuardUtils.h"
3006f32e7eSjoerg #include "llvm/Analysis/InstructionSimplify.h"
3106f32e7eSjoerg #include "llvm/Analysis/Loads.h"
3206f32e7eSjoerg #include "llvm/Analysis/LoopInfo.h"
3306f32e7eSjoerg #include "llvm/Analysis/OptimizationRemarkEmitter.h"
3406f32e7eSjoerg #include "llvm/Analysis/TargetLibraryInfo.h"
3506f32e7eSjoerg #include "llvm/IR/Argument.h"
3606f32e7eSjoerg #include "llvm/IR/Attributes.h"
3706f32e7eSjoerg #include "llvm/IR/BasicBlock.h"
3806f32e7eSjoerg #include "llvm/IR/Constant.h"
3906f32e7eSjoerg #include "llvm/IR/ConstantRange.h"
4006f32e7eSjoerg #include "llvm/IR/Constants.h"
4106f32e7eSjoerg #include "llvm/IR/DerivedTypes.h"
4206f32e7eSjoerg #include "llvm/IR/DiagnosticInfo.h"
4306f32e7eSjoerg #include "llvm/IR/Dominators.h"
4406f32e7eSjoerg #include "llvm/IR/Function.h"
4506f32e7eSjoerg #include "llvm/IR/GetElementPtrTypeIterator.h"
4606f32e7eSjoerg #include "llvm/IR/GlobalAlias.h"
4706f32e7eSjoerg #include "llvm/IR/GlobalValue.h"
4806f32e7eSjoerg #include "llvm/IR/GlobalVariable.h"
4906f32e7eSjoerg #include "llvm/IR/InstrTypes.h"
5006f32e7eSjoerg #include "llvm/IR/Instruction.h"
5106f32e7eSjoerg #include "llvm/IR/Instructions.h"
5206f32e7eSjoerg #include "llvm/IR/IntrinsicInst.h"
5306f32e7eSjoerg #include "llvm/IR/Intrinsics.h"
54*da58b97aSjoerg #include "llvm/IR/IntrinsicsAArch64.h"
55*da58b97aSjoerg #include "llvm/IR/IntrinsicsRISCV.h"
56*da58b97aSjoerg #include "llvm/IR/IntrinsicsX86.h"
5706f32e7eSjoerg #include "llvm/IR/LLVMContext.h"
5806f32e7eSjoerg #include "llvm/IR/Metadata.h"
5906f32e7eSjoerg #include "llvm/IR/Module.h"
6006f32e7eSjoerg #include "llvm/IR/Operator.h"
6106f32e7eSjoerg #include "llvm/IR/PatternMatch.h"
6206f32e7eSjoerg #include "llvm/IR/Type.h"
6306f32e7eSjoerg #include "llvm/IR/User.h"
6406f32e7eSjoerg #include "llvm/IR/Value.h"
6506f32e7eSjoerg #include "llvm/Support/Casting.h"
6606f32e7eSjoerg #include "llvm/Support/CommandLine.h"
6706f32e7eSjoerg #include "llvm/Support/Compiler.h"
6806f32e7eSjoerg #include "llvm/Support/ErrorHandling.h"
6906f32e7eSjoerg #include "llvm/Support/KnownBits.h"
7006f32e7eSjoerg #include "llvm/Support/MathExtras.h"
7106f32e7eSjoerg #include <algorithm>
7206f32e7eSjoerg #include <array>
7306f32e7eSjoerg #include <cassert>
7406f32e7eSjoerg #include <cstdint>
7506f32e7eSjoerg #include <iterator>
7606f32e7eSjoerg #include <utility>
7706f32e7eSjoerg 
7806f32e7eSjoerg using namespace llvm;
7906f32e7eSjoerg using namespace llvm::PatternMatch;
8006f32e7eSjoerg 
8106f32e7eSjoerg // Controls the number of uses of the value searched for possible
8206f32e7eSjoerg // dominating comparisons.
8306f32e7eSjoerg static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
8406f32e7eSjoerg                                               cl::Hidden, cl::init(20));
8506f32e7eSjoerg 
8606f32e7eSjoerg /// Returns the bitwidth of the given scalar or pointer type. For vector types,
8706f32e7eSjoerg /// returns the element type's bitwidth.
getBitWidth(Type * Ty,const DataLayout & DL)8806f32e7eSjoerg static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
8906f32e7eSjoerg   if (unsigned BitWidth = Ty->getScalarSizeInBits())
9006f32e7eSjoerg     return BitWidth;
9106f32e7eSjoerg 
92*da58b97aSjoerg   return DL.getPointerTypeSizeInBits(Ty);
9306f32e7eSjoerg }
9406f32e7eSjoerg 
9506f32e7eSjoerg namespace {
9606f32e7eSjoerg 
9706f32e7eSjoerg // Simplifying using an assume can only be done in a particular control-flow
9806f32e7eSjoerg // context (the context instruction provides that context). If an assume and
9906f32e7eSjoerg // the context instruction are not in the same block then the DT helps in
10006f32e7eSjoerg // figuring out if we can use it.
10106f32e7eSjoerg struct Query {
10206f32e7eSjoerg   const DataLayout &DL;
10306f32e7eSjoerg   AssumptionCache *AC;
10406f32e7eSjoerg   const Instruction *CxtI;
10506f32e7eSjoerg   const DominatorTree *DT;
10606f32e7eSjoerg 
10706f32e7eSjoerg   // Unlike the other analyses, this may be a nullptr because not all clients
10806f32e7eSjoerg   // provide it currently.
10906f32e7eSjoerg   OptimizationRemarkEmitter *ORE;
11006f32e7eSjoerg 
11106f32e7eSjoerg   /// If true, it is safe to use metadata during simplification.
11206f32e7eSjoerg   InstrInfoQuery IIQ;
11306f32e7eSjoerg 
Query__anonf8211fd40111::Query11406f32e7eSjoerg   Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
11506f32e7eSjoerg         const DominatorTree *DT, bool UseInstrInfo,
11606f32e7eSjoerg         OptimizationRemarkEmitter *ORE = nullptr)
11706f32e7eSjoerg       : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
11806f32e7eSjoerg };
11906f32e7eSjoerg 
12006f32e7eSjoerg } // end anonymous namespace
12106f32e7eSjoerg 
12206f32e7eSjoerg // Given the provided Value and, potentially, a context instruction, return
12306f32e7eSjoerg // the preferred context instruction (if any).
safeCxtI(const Value * V,const Instruction * CxtI)12406f32e7eSjoerg static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
12506f32e7eSjoerg   // If we've been provided with a context instruction, then use that (provided
12606f32e7eSjoerg   // it has been inserted).
12706f32e7eSjoerg   if (CxtI && CxtI->getParent())
12806f32e7eSjoerg     return CxtI;
12906f32e7eSjoerg 
13006f32e7eSjoerg   // If the value is really an already-inserted instruction, then use that.
13106f32e7eSjoerg   CxtI = dyn_cast<Instruction>(V);
13206f32e7eSjoerg   if (CxtI && CxtI->getParent())
13306f32e7eSjoerg     return CxtI;
13406f32e7eSjoerg 
13506f32e7eSjoerg   return nullptr;
13606f32e7eSjoerg }
13706f32e7eSjoerg 
safeCxtI(const Value * V1,const Value * V2,const Instruction * CxtI)138*da58b97aSjoerg static const Instruction *safeCxtI(const Value *V1, const Value *V2, const Instruction *CxtI) {
139*da58b97aSjoerg   // If we've been provided with a context instruction, then use that (provided
140*da58b97aSjoerg   // it has been inserted).
141*da58b97aSjoerg   if (CxtI && CxtI->getParent())
142*da58b97aSjoerg     return CxtI;
143*da58b97aSjoerg 
144*da58b97aSjoerg   // If the value is really an already-inserted instruction, then use that.
145*da58b97aSjoerg   CxtI = dyn_cast<Instruction>(V1);
146*da58b97aSjoerg   if (CxtI && CxtI->getParent())
147*da58b97aSjoerg     return CxtI;
148*da58b97aSjoerg 
149*da58b97aSjoerg   CxtI = dyn_cast<Instruction>(V2);
150*da58b97aSjoerg   if (CxtI && CxtI->getParent())
151*da58b97aSjoerg     return CxtI;
152*da58b97aSjoerg 
153*da58b97aSjoerg   return nullptr;
154*da58b97aSjoerg }
155*da58b97aSjoerg 
getShuffleDemandedElts(const ShuffleVectorInst * Shuf,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)156*da58b97aSjoerg static bool getShuffleDemandedElts(const ShuffleVectorInst *Shuf,
157*da58b97aSjoerg                                    const APInt &DemandedElts,
158*da58b97aSjoerg                                    APInt &DemandedLHS, APInt &DemandedRHS) {
159*da58b97aSjoerg   // The length of scalable vectors is unknown at compile time, thus we
160*da58b97aSjoerg   // cannot check their values
161*da58b97aSjoerg   if (isa<ScalableVectorType>(Shuf->getType()))
162*da58b97aSjoerg     return false;
163*da58b97aSjoerg 
164*da58b97aSjoerg   int NumElts =
165*da58b97aSjoerg       cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
166*da58b97aSjoerg   int NumMaskElts = cast<FixedVectorType>(Shuf->getType())->getNumElements();
167*da58b97aSjoerg   DemandedLHS = DemandedRHS = APInt::getNullValue(NumElts);
168*da58b97aSjoerg   if (DemandedElts.isNullValue())
169*da58b97aSjoerg     return true;
170*da58b97aSjoerg   // Simple case of a shuffle with zeroinitializer.
171*da58b97aSjoerg   if (all_of(Shuf->getShuffleMask(), [](int Elt) { return Elt == 0; })) {
172*da58b97aSjoerg     DemandedLHS.setBit(0);
173*da58b97aSjoerg     return true;
174*da58b97aSjoerg   }
175*da58b97aSjoerg   for (int i = 0; i != NumMaskElts; ++i) {
176*da58b97aSjoerg     if (!DemandedElts[i])
177*da58b97aSjoerg       continue;
178*da58b97aSjoerg     int M = Shuf->getMaskValue(i);
179*da58b97aSjoerg     assert(M < (NumElts * 2) && "Invalid shuffle mask constant");
180*da58b97aSjoerg 
181*da58b97aSjoerg     // For undef elements, we don't know anything about the common state of
182*da58b97aSjoerg     // the shuffle result.
183*da58b97aSjoerg     if (M == -1)
184*da58b97aSjoerg       return false;
185*da58b97aSjoerg     if (M < NumElts)
186*da58b97aSjoerg       DemandedLHS.setBit(M % NumElts);
187*da58b97aSjoerg     else
188*da58b97aSjoerg       DemandedRHS.setBit(M % NumElts);
189*da58b97aSjoerg   }
190*da58b97aSjoerg 
191*da58b97aSjoerg   return true;
192*da58b97aSjoerg }
193*da58b97aSjoerg 
194*da58b97aSjoerg static void computeKnownBits(const Value *V, const APInt &DemandedElts,
195*da58b97aSjoerg                              KnownBits &Known, unsigned Depth, const Query &Q);
196*da58b97aSjoerg 
computeKnownBits(const Value * V,KnownBits & Known,unsigned Depth,const Query & Q)197*da58b97aSjoerg static void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
198*da58b97aSjoerg                              const Query &Q) {
199*da58b97aSjoerg   // FIXME: We currently have no way to represent the DemandedElts of a scalable
200*da58b97aSjoerg   // vector
201*da58b97aSjoerg   if (isa<ScalableVectorType>(V->getType())) {
202*da58b97aSjoerg     Known.resetAll();
203*da58b97aSjoerg     return;
204*da58b97aSjoerg   }
205*da58b97aSjoerg 
206*da58b97aSjoerg   auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
207*da58b97aSjoerg   APInt DemandedElts =
208*da58b97aSjoerg       FVTy ? APInt::getAllOnesValue(FVTy->getNumElements()) : APInt(1, 1);
209*da58b97aSjoerg   computeKnownBits(V, DemandedElts, Known, Depth, Q);
210*da58b97aSjoerg }
21106f32e7eSjoerg 
computeKnownBits(const Value * V,KnownBits & Known,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,OptimizationRemarkEmitter * ORE,bool UseInstrInfo)21206f32e7eSjoerg void llvm::computeKnownBits(const Value *V, KnownBits &Known,
21306f32e7eSjoerg                             const DataLayout &DL, unsigned Depth,
21406f32e7eSjoerg                             AssumptionCache *AC, const Instruction *CxtI,
21506f32e7eSjoerg                             const DominatorTree *DT,
21606f32e7eSjoerg                             OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
21706f32e7eSjoerg   ::computeKnownBits(V, Known, Depth,
21806f32e7eSjoerg                      Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
21906f32e7eSjoerg }
22006f32e7eSjoerg 
computeKnownBits(const Value * V,const APInt & DemandedElts,KnownBits & Known,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,OptimizationRemarkEmitter * ORE,bool UseInstrInfo)221*da58b97aSjoerg void llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
222*da58b97aSjoerg                             KnownBits &Known, const DataLayout &DL,
223*da58b97aSjoerg                             unsigned Depth, AssumptionCache *AC,
224*da58b97aSjoerg                             const Instruction *CxtI, const DominatorTree *DT,
225*da58b97aSjoerg                             OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
226*da58b97aSjoerg   ::computeKnownBits(V, DemandedElts, Known, Depth,
227*da58b97aSjoerg                      Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
228*da58b97aSjoerg }
229*da58b97aSjoerg 
230*da58b97aSjoerg static KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
231*da58b97aSjoerg                                   unsigned Depth, const Query &Q);
232*da58b97aSjoerg 
23306f32e7eSjoerg static KnownBits computeKnownBits(const Value *V, unsigned Depth,
23406f32e7eSjoerg                                   const Query &Q);
23506f32e7eSjoerg 
computeKnownBits(const Value * V,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,OptimizationRemarkEmitter * ORE,bool UseInstrInfo)23606f32e7eSjoerg KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
23706f32e7eSjoerg                                  unsigned Depth, AssumptionCache *AC,
23806f32e7eSjoerg                                  const Instruction *CxtI,
23906f32e7eSjoerg                                  const DominatorTree *DT,
24006f32e7eSjoerg                                  OptimizationRemarkEmitter *ORE,
24106f32e7eSjoerg                                  bool UseInstrInfo) {
24206f32e7eSjoerg   return ::computeKnownBits(
24306f32e7eSjoerg       V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
24406f32e7eSjoerg }
24506f32e7eSjoerg 
computeKnownBits(const Value * V,const APInt & DemandedElts,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,OptimizationRemarkEmitter * ORE,bool UseInstrInfo)246*da58b97aSjoerg KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
247*da58b97aSjoerg                                  const DataLayout &DL, unsigned Depth,
248*da58b97aSjoerg                                  AssumptionCache *AC, const Instruction *CxtI,
249*da58b97aSjoerg                                  const DominatorTree *DT,
250*da58b97aSjoerg                                  OptimizationRemarkEmitter *ORE,
251*da58b97aSjoerg                                  bool UseInstrInfo) {
252*da58b97aSjoerg   return ::computeKnownBits(
253*da58b97aSjoerg       V, DemandedElts, Depth,
254*da58b97aSjoerg       Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
255*da58b97aSjoerg }
256*da58b97aSjoerg 
haveNoCommonBitsSet(const Value * LHS,const Value * RHS,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)25706f32e7eSjoerg bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
25806f32e7eSjoerg                                const DataLayout &DL, AssumptionCache *AC,
25906f32e7eSjoerg                                const Instruction *CxtI, const DominatorTree *DT,
26006f32e7eSjoerg                                bool UseInstrInfo) {
26106f32e7eSjoerg   assert(LHS->getType() == RHS->getType() &&
26206f32e7eSjoerg          "LHS and RHS should have the same type");
26306f32e7eSjoerg   assert(LHS->getType()->isIntOrIntVectorTy() &&
26406f32e7eSjoerg          "LHS and RHS should be integers");
26506f32e7eSjoerg   // Look for an inverted mask: (X & ~M) op (Y & M).
26606f32e7eSjoerg   Value *M;
26706f32e7eSjoerg   if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
26806f32e7eSjoerg       match(RHS, m_c_And(m_Specific(M), m_Value())))
26906f32e7eSjoerg     return true;
27006f32e7eSjoerg   if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
27106f32e7eSjoerg       match(LHS, m_c_And(m_Specific(M), m_Value())))
27206f32e7eSjoerg     return true;
27306f32e7eSjoerg   IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
27406f32e7eSjoerg   KnownBits LHSKnown(IT->getBitWidth());
27506f32e7eSjoerg   KnownBits RHSKnown(IT->getBitWidth());
27606f32e7eSjoerg   computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
27706f32e7eSjoerg   computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
278*da58b97aSjoerg   return KnownBits::haveNoCommonBitsSet(LHSKnown, RHSKnown);
27906f32e7eSjoerg }
28006f32e7eSjoerg 
isOnlyUsedInZeroEqualityComparison(const Instruction * CxtI)28106f32e7eSjoerg bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
28206f32e7eSjoerg   for (const User *U : CxtI->users()) {
28306f32e7eSjoerg     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
28406f32e7eSjoerg       if (IC->isEquality())
28506f32e7eSjoerg         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
28606f32e7eSjoerg           if (C->isNullValue())
28706f32e7eSjoerg             continue;
28806f32e7eSjoerg     return false;
28906f32e7eSjoerg   }
29006f32e7eSjoerg   return true;
29106f32e7eSjoerg }
29206f32e7eSjoerg 
29306f32e7eSjoerg static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
29406f32e7eSjoerg                                    const Query &Q);
29506f32e7eSjoerg 
isKnownToBeAPowerOfTwo(const Value * V,const DataLayout & DL,bool OrZero,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)29606f32e7eSjoerg bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
29706f32e7eSjoerg                                   bool OrZero, unsigned Depth,
29806f32e7eSjoerg                                   AssumptionCache *AC, const Instruction *CxtI,
29906f32e7eSjoerg                                   const DominatorTree *DT, bool UseInstrInfo) {
30006f32e7eSjoerg   return ::isKnownToBeAPowerOfTwo(
30106f32e7eSjoerg       V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
30206f32e7eSjoerg }
30306f32e7eSjoerg 
304*da58b97aSjoerg static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
305*da58b97aSjoerg                            unsigned Depth, const Query &Q);
306*da58b97aSjoerg 
30706f32e7eSjoerg static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
30806f32e7eSjoerg 
isKnownNonZero(const Value * V,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)30906f32e7eSjoerg bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
31006f32e7eSjoerg                           AssumptionCache *AC, const Instruction *CxtI,
31106f32e7eSjoerg                           const DominatorTree *DT, bool UseInstrInfo) {
31206f32e7eSjoerg   return ::isKnownNonZero(V, Depth,
31306f32e7eSjoerg                           Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
31406f32e7eSjoerg }
31506f32e7eSjoerg 
isKnownNonNegative(const Value * V,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)31606f32e7eSjoerg bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
31706f32e7eSjoerg                               unsigned Depth, AssumptionCache *AC,
31806f32e7eSjoerg                               const Instruction *CxtI, const DominatorTree *DT,
31906f32e7eSjoerg                               bool UseInstrInfo) {
32006f32e7eSjoerg   KnownBits Known =
32106f32e7eSjoerg       computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
32206f32e7eSjoerg   return Known.isNonNegative();
32306f32e7eSjoerg }
32406f32e7eSjoerg 
isKnownPositive(const Value * V,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)32506f32e7eSjoerg bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
32606f32e7eSjoerg                            AssumptionCache *AC, const Instruction *CxtI,
32706f32e7eSjoerg                            const DominatorTree *DT, bool UseInstrInfo) {
32806f32e7eSjoerg   if (auto *CI = dyn_cast<ConstantInt>(V))
32906f32e7eSjoerg     return CI->getValue().isStrictlyPositive();
33006f32e7eSjoerg 
33106f32e7eSjoerg   // TODO: We'd doing two recursive queries here.  We should factor this such
33206f32e7eSjoerg   // that only a single query is needed.
33306f32e7eSjoerg   return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
33406f32e7eSjoerg          isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
33506f32e7eSjoerg }
33606f32e7eSjoerg 
isKnownNegative(const Value * V,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)33706f32e7eSjoerg bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
33806f32e7eSjoerg                            AssumptionCache *AC, const Instruction *CxtI,
33906f32e7eSjoerg                            const DominatorTree *DT, bool UseInstrInfo) {
34006f32e7eSjoerg   KnownBits Known =
34106f32e7eSjoerg       computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
34206f32e7eSjoerg   return Known.isNegative();
34306f32e7eSjoerg }
34406f32e7eSjoerg 
345*da58b97aSjoerg static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
346*da58b97aSjoerg                             const Query &Q);
34706f32e7eSjoerg 
isKnownNonEqual(const Value * V1,const Value * V2,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)34806f32e7eSjoerg bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
34906f32e7eSjoerg                            const DataLayout &DL, AssumptionCache *AC,
35006f32e7eSjoerg                            const Instruction *CxtI, const DominatorTree *DT,
35106f32e7eSjoerg                            bool UseInstrInfo) {
352*da58b97aSjoerg   return ::isKnownNonEqual(V1, V2, 0,
353*da58b97aSjoerg                            Query(DL, AC, safeCxtI(V2, V1, CxtI), DT,
35406f32e7eSjoerg                                  UseInstrInfo, /*ORE=*/nullptr));
35506f32e7eSjoerg }
35606f32e7eSjoerg 
35706f32e7eSjoerg static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
35806f32e7eSjoerg                               const Query &Q);
35906f32e7eSjoerg 
MaskedValueIsZero(const Value * V,const APInt & Mask,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)36006f32e7eSjoerg bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
36106f32e7eSjoerg                              const DataLayout &DL, unsigned Depth,
36206f32e7eSjoerg                              AssumptionCache *AC, const Instruction *CxtI,
36306f32e7eSjoerg                              const DominatorTree *DT, bool UseInstrInfo) {
36406f32e7eSjoerg   return ::MaskedValueIsZero(
36506f32e7eSjoerg       V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
36606f32e7eSjoerg }
36706f32e7eSjoerg 
368*da58b97aSjoerg static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
369*da58b97aSjoerg                                    unsigned Depth, const Query &Q);
370*da58b97aSjoerg 
ComputeNumSignBits(const Value * V,unsigned Depth,const Query & Q)37106f32e7eSjoerg static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
372*da58b97aSjoerg                                    const Query &Q) {
373*da58b97aSjoerg   // FIXME: We currently have no way to represent the DemandedElts of a scalable
374*da58b97aSjoerg   // vector
375*da58b97aSjoerg   if (isa<ScalableVectorType>(V->getType()))
376*da58b97aSjoerg     return 1;
377*da58b97aSjoerg 
378*da58b97aSjoerg   auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
379*da58b97aSjoerg   APInt DemandedElts =
380*da58b97aSjoerg       FVTy ? APInt::getAllOnesValue(FVTy->getNumElements()) : APInt(1, 1);
381*da58b97aSjoerg   return ComputeNumSignBits(V, DemandedElts, Depth, Q);
382*da58b97aSjoerg }
38306f32e7eSjoerg 
ComputeNumSignBits(const Value * V,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)38406f32e7eSjoerg unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
38506f32e7eSjoerg                                   unsigned Depth, AssumptionCache *AC,
38606f32e7eSjoerg                                   const Instruction *CxtI,
38706f32e7eSjoerg                                   const DominatorTree *DT, bool UseInstrInfo) {
38806f32e7eSjoerg   return ::ComputeNumSignBits(
38906f32e7eSjoerg       V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
39006f32e7eSjoerg }
39106f32e7eSjoerg 
computeKnownBitsAddSub(bool Add,const Value * Op0,const Value * Op1,bool NSW,const APInt & DemandedElts,KnownBits & KnownOut,KnownBits & Known2,unsigned Depth,const Query & Q)39206f32e7eSjoerg static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
393*da58b97aSjoerg                                    bool NSW, const APInt &DemandedElts,
39406f32e7eSjoerg                                    KnownBits &KnownOut, KnownBits &Known2,
39506f32e7eSjoerg                                    unsigned Depth, const Query &Q) {
396*da58b97aSjoerg   computeKnownBits(Op1, DemandedElts, KnownOut, Depth + 1, Q);
39706f32e7eSjoerg 
398*da58b97aSjoerg   // If one operand is unknown and we have no nowrap information,
399*da58b97aSjoerg   // the result will be unknown independently of the second operand.
400*da58b97aSjoerg   if (KnownOut.isUnknown() && !NSW)
401*da58b97aSjoerg     return;
40206f32e7eSjoerg 
403*da58b97aSjoerg   computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
404*da58b97aSjoerg   KnownOut = KnownBits::computeForAddSub(Add, NSW, Known2, KnownOut);
40506f32e7eSjoerg }
40606f32e7eSjoerg 
computeKnownBitsMul(const Value * Op0,const Value * Op1,bool NSW,const APInt & DemandedElts,KnownBits & Known,KnownBits & Known2,unsigned Depth,const Query & Q)40706f32e7eSjoerg static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
408*da58b97aSjoerg                                 const APInt &DemandedElts, KnownBits &Known,
409*da58b97aSjoerg                                 KnownBits &Known2, unsigned Depth,
410*da58b97aSjoerg                                 const Query &Q) {
411*da58b97aSjoerg   computeKnownBits(Op1, DemandedElts, Known, Depth + 1, Q);
412*da58b97aSjoerg   computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
41306f32e7eSjoerg 
41406f32e7eSjoerg   bool isKnownNegative = false;
41506f32e7eSjoerg   bool isKnownNonNegative = false;
41606f32e7eSjoerg   // If the multiplication is known not to overflow, compute the sign bit.
41706f32e7eSjoerg   if (NSW) {
41806f32e7eSjoerg     if (Op0 == Op1) {
41906f32e7eSjoerg       // The product of a number with itself is non-negative.
42006f32e7eSjoerg       isKnownNonNegative = true;
42106f32e7eSjoerg     } else {
42206f32e7eSjoerg       bool isKnownNonNegativeOp1 = Known.isNonNegative();
42306f32e7eSjoerg       bool isKnownNonNegativeOp0 = Known2.isNonNegative();
42406f32e7eSjoerg       bool isKnownNegativeOp1 = Known.isNegative();
42506f32e7eSjoerg       bool isKnownNegativeOp0 = Known2.isNegative();
42606f32e7eSjoerg       // The product of two numbers with the same sign is non-negative.
42706f32e7eSjoerg       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
42806f32e7eSjoerg                            (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
42906f32e7eSjoerg       // The product of a negative number and a non-negative number is either
43006f32e7eSjoerg       // negative or zero.
43106f32e7eSjoerg       if (!isKnownNonNegative)
432*da58b97aSjoerg         isKnownNegative =
433*da58b97aSjoerg             (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
434*da58b97aSjoerg              Known2.isNonZero()) ||
435*da58b97aSjoerg             (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
43606f32e7eSjoerg     }
43706f32e7eSjoerg   }
43806f32e7eSjoerg 
439*da58b97aSjoerg   Known = KnownBits::mul(Known, Known2);
44006f32e7eSjoerg 
44106f32e7eSjoerg   // Only make use of no-wrap flags if we failed to compute the sign bit
44206f32e7eSjoerg   // directly.  This matters if the multiplication always overflows, in
44306f32e7eSjoerg   // which case we prefer to follow the result of the direct computation,
44406f32e7eSjoerg   // though as the program is invoking undefined behaviour we can choose
44506f32e7eSjoerg   // whatever we like here.
44606f32e7eSjoerg   if (isKnownNonNegative && !Known.isNegative())
44706f32e7eSjoerg     Known.makeNonNegative();
44806f32e7eSjoerg   else if (isKnownNegative && !Known.isNonNegative())
44906f32e7eSjoerg     Known.makeNegative();
45006f32e7eSjoerg }
45106f32e7eSjoerg 
computeKnownBitsFromRangeMetadata(const MDNode & Ranges,KnownBits & Known)45206f32e7eSjoerg void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
45306f32e7eSjoerg                                              KnownBits &Known) {
45406f32e7eSjoerg   unsigned BitWidth = Known.getBitWidth();
45506f32e7eSjoerg   unsigned NumRanges = Ranges.getNumOperands() / 2;
45606f32e7eSjoerg   assert(NumRanges >= 1);
45706f32e7eSjoerg 
45806f32e7eSjoerg   Known.Zero.setAllBits();
45906f32e7eSjoerg   Known.One.setAllBits();
46006f32e7eSjoerg 
46106f32e7eSjoerg   for (unsigned i = 0; i < NumRanges; ++i) {
46206f32e7eSjoerg     ConstantInt *Lower =
46306f32e7eSjoerg         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
46406f32e7eSjoerg     ConstantInt *Upper =
46506f32e7eSjoerg         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
46606f32e7eSjoerg     ConstantRange Range(Lower->getValue(), Upper->getValue());
46706f32e7eSjoerg 
46806f32e7eSjoerg     // The first CommonPrefixBits of all values in Range are equal.
46906f32e7eSjoerg     unsigned CommonPrefixBits =
47006f32e7eSjoerg         (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
47106f32e7eSjoerg     APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
472*da58b97aSjoerg     APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
473*da58b97aSjoerg     Known.One &= UnsignedMax & Mask;
474*da58b97aSjoerg     Known.Zero &= ~UnsignedMax & Mask;
47506f32e7eSjoerg   }
47606f32e7eSjoerg }
47706f32e7eSjoerg 
isEphemeralValueOf(const Instruction * I,const Value * E)47806f32e7eSjoerg static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
47906f32e7eSjoerg   SmallVector<const Value *, 16> WorkSet(1, I);
48006f32e7eSjoerg   SmallPtrSet<const Value *, 32> Visited;
48106f32e7eSjoerg   SmallPtrSet<const Value *, 16> EphValues;
48206f32e7eSjoerg 
48306f32e7eSjoerg   // The instruction defining an assumption's condition itself is always
48406f32e7eSjoerg   // considered ephemeral to that assumption (even if it has other
48506f32e7eSjoerg   // non-ephemeral users). See r246696's test case for an example.
48606f32e7eSjoerg   if (is_contained(I->operands(), E))
48706f32e7eSjoerg     return true;
48806f32e7eSjoerg 
48906f32e7eSjoerg   while (!WorkSet.empty()) {
49006f32e7eSjoerg     const Value *V = WorkSet.pop_back_val();
49106f32e7eSjoerg     if (!Visited.insert(V).second)
49206f32e7eSjoerg       continue;
49306f32e7eSjoerg 
49406f32e7eSjoerg     // If all uses of this value are ephemeral, then so is this value.
49506f32e7eSjoerg     if (llvm::all_of(V->users(), [&](const User *U) {
49606f32e7eSjoerg                                    return EphValues.count(U);
49706f32e7eSjoerg                                  })) {
49806f32e7eSjoerg       if (V == E)
49906f32e7eSjoerg         return true;
50006f32e7eSjoerg 
50106f32e7eSjoerg       if (V == I || isSafeToSpeculativelyExecute(V)) {
50206f32e7eSjoerg        EphValues.insert(V);
50306f32e7eSjoerg        if (const User *U = dyn_cast<User>(V))
504*da58b97aSjoerg          append_range(WorkSet, U->operands());
50506f32e7eSjoerg       }
50606f32e7eSjoerg     }
50706f32e7eSjoerg   }
50806f32e7eSjoerg 
50906f32e7eSjoerg   return false;
51006f32e7eSjoerg }
51106f32e7eSjoerg 
51206f32e7eSjoerg // Is this an intrinsic that cannot be speculated but also cannot trap?
isAssumeLikeIntrinsic(const Instruction * I)51306f32e7eSjoerg bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
514*da58b97aSjoerg   if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
515*da58b97aSjoerg     return CI->isAssumeLikeIntrinsic();
51606f32e7eSjoerg 
51706f32e7eSjoerg   return false;
51806f32e7eSjoerg }
51906f32e7eSjoerg 
isValidAssumeForContext(const Instruction * Inv,const Instruction * CxtI,const DominatorTree * DT)52006f32e7eSjoerg bool llvm::isValidAssumeForContext(const Instruction *Inv,
52106f32e7eSjoerg                                    const Instruction *CxtI,
52206f32e7eSjoerg                                    const DominatorTree *DT) {
52306f32e7eSjoerg   // There are two restrictions on the use of an assume:
52406f32e7eSjoerg   //  1. The assume must dominate the context (or the control flow must
52506f32e7eSjoerg   //     reach the assume whenever it reaches the context).
52606f32e7eSjoerg   //  2. The context must not be in the assume's set of ephemeral values
52706f32e7eSjoerg   //     (otherwise we will use the assume to prove that the condition
52806f32e7eSjoerg   //     feeding the assume is trivially true, thus causing the removal of
52906f32e7eSjoerg   //     the assume).
53006f32e7eSjoerg 
531*da58b97aSjoerg   if (Inv->getParent() == CxtI->getParent()) {
532*da58b97aSjoerg     // If Inv and CtxI are in the same block, check if the assume (Inv) is first
533*da58b97aSjoerg     // in the BB.
534*da58b97aSjoerg     if (Inv->comesBefore(CxtI))
535*da58b97aSjoerg       return true;
536*da58b97aSjoerg 
537*da58b97aSjoerg     // Don't let an assume affect itself - this would cause the problems
538*da58b97aSjoerg     // `isEphemeralValueOf` is trying to prevent, and it would also make
539*da58b97aSjoerg     // the loop below go out of bounds.
540*da58b97aSjoerg     if (Inv == CxtI)
541*da58b97aSjoerg       return false;
542*da58b97aSjoerg 
543*da58b97aSjoerg     // The context comes first, but they're both in the same block.
544*da58b97aSjoerg     // Make sure there is nothing in between that might interrupt
545*da58b97aSjoerg     // the control flow, not even CxtI itself.
546*da58b97aSjoerg     // We limit the scan distance between the assume and its context instruction
547*da58b97aSjoerg     // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
548*da58b97aSjoerg     // it can be adjusted if needed (could be turned into a cl::opt).
549*da58b97aSjoerg     unsigned ScanLimit = 15;
550*da58b97aSjoerg     for (BasicBlock::const_iterator I(CxtI), IE(Inv); I != IE; ++I)
551*da58b97aSjoerg       if (!isGuaranteedToTransferExecutionToSuccessor(&*I) || --ScanLimit == 0)
552*da58b97aSjoerg         return false;
553*da58b97aSjoerg 
554*da58b97aSjoerg     return !isEphemeralValueOf(Inv, CxtI);
555*da58b97aSjoerg   }
556*da58b97aSjoerg 
557*da58b97aSjoerg   // Inv and CxtI are in different blocks.
55806f32e7eSjoerg   if (DT) {
55906f32e7eSjoerg     if (DT->dominates(Inv, CxtI))
56006f32e7eSjoerg       return true;
56106f32e7eSjoerg   } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
56206f32e7eSjoerg     // We don't have a DT, but this trivially dominates.
56306f32e7eSjoerg     return true;
56406f32e7eSjoerg   }
56506f32e7eSjoerg 
566*da58b97aSjoerg   return false;
567*da58b97aSjoerg }
568*da58b97aSjoerg 
cmpExcludesZero(CmpInst::Predicate Pred,const Value * RHS)569*da58b97aSjoerg static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
570*da58b97aSjoerg   // v u> y implies v != 0.
571*da58b97aSjoerg   if (Pred == ICmpInst::ICMP_UGT)
572*da58b97aSjoerg     return true;
573*da58b97aSjoerg 
574*da58b97aSjoerg   // Special-case v != 0 to also handle v != null.
575*da58b97aSjoerg   if (Pred == ICmpInst::ICMP_NE)
576*da58b97aSjoerg     return match(RHS, m_Zero());
577*da58b97aSjoerg 
578*da58b97aSjoerg   // All other predicates - rely on generic ConstantRange handling.
579*da58b97aSjoerg   const APInt *C;
580*da58b97aSjoerg   if (!match(RHS, m_APInt(C)))
58106f32e7eSjoerg     return false;
58206f32e7eSjoerg 
583*da58b97aSjoerg   ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(Pred, *C);
584*da58b97aSjoerg   return !TrueValues.contains(APInt::getNullValue(C->getBitWidth()));
585*da58b97aSjoerg }
586*da58b97aSjoerg 
isKnownNonZeroFromAssume(const Value * V,const Query & Q)587*da58b97aSjoerg static bool isKnownNonZeroFromAssume(const Value *V, const Query &Q) {
588*da58b97aSjoerg   // Use of assumptions is context-sensitive. If we don't have a context, we
589*da58b97aSjoerg   // cannot use them!
590*da58b97aSjoerg   if (!Q.AC || !Q.CxtI)
591*da58b97aSjoerg     return false;
592*da58b97aSjoerg 
593*da58b97aSjoerg   if (Q.CxtI && V->getType()->isPointerTy()) {
594*da58b97aSjoerg     SmallVector<Attribute::AttrKind, 2> AttrKinds{Attribute::NonNull};
595*da58b97aSjoerg     if (!NullPointerIsDefined(Q.CxtI->getFunction(),
596*da58b97aSjoerg                               V->getType()->getPointerAddressSpace()))
597*da58b97aSjoerg       AttrKinds.push_back(Attribute::Dereferenceable);
598*da58b97aSjoerg 
599*da58b97aSjoerg     if (getKnowledgeValidInContext(V, AttrKinds, Q.CxtI, Q.DT, Q.AC))
60006f32e7eSjoerg       return true;
60106f32e7eSjoerg   }
60206f32e7eSjoerg 
603*da58b97aSjoerg   for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
604*da58b97aSjoerg     if (!AssumeVH)
605*da58b97aSjoerg       continue;
606*da58b97aSjoerg     CallInst *I = cast<CallInst>(AssumeVH);
607*da58b97aSjoerg     assert(I->getFunction() == Q.CxtI->getFunction() &&
608*da58b97aSjoerg            "Got assumption for the wrong function!");
609*da58b97aSjoerg 
610*da58b97aSjoerg     // Warning: This loop can end up being somewhat performance sensitive.
611*da58b97aSjoerg     // We're running this loop for once for each value queried resulting in a
612*da58b97aSjoerg     // runtime of ~O(#assumes * #values).
613*da58b97aSjoerg 
614*da58b97aSjoerg     assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
615*da58b97aSjoerg            "must be an assume intrinsic");
616*da58b97aSjoerg 
617*da58b97aSjoerg     Value *RHS;
618*da58b97aSjoerg     CmpInst::Predicate Pred;
619*da58b97aSjoerg     auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
620*da58b97aSjoerg     if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
62106f32e7eSjoerg       return false;
62206f32e7eSjoerg 
623*da58b97aSjoerg     if (cmpExcludesZero(Pred, RHS) && isValidAssumeForContext(I, Q.CxtI, Q.DT))
624*da58b97aSjoerg       return true;
625*da58b97aSjoerg   }
62606f32e7eSjoerg 
627*da58b97aSjoerg   return false;
62806f32e7eSjoerg }
62906f32e7eSjoerg 
computeKnownBitsFromAssume(const Value * V,KnownBits & Known,unsigned Depth,const Query & Q)63006f32e7eSjoerg static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
63106f32e7eSjoerg                                        unsigned Depth, const Query &Q) {
63206f32e7eSjoerg   // Use of assumptions is context-sensitive. If we don't have a context, we
63306f32e7eSjoerg   // cannot use them!
63406f32e7eSjoerg   if (!Q.AC || !Q.CxtI)
63506f32e7eSjoerg     return;
63606f32e7eSjoerg 
63706f32e7eSjoerg   unsigned BitWidth = Known.getBitWidth();
63806f32e7eSjoerg 
639*da58b97aSjoerg   // Refine Known set if the pointer alignment is set by assume bundles.
640*da58b97aSjoerg   if (V->getType()->isPointerTy()) {
641*da58b97aSjoerg     if (RetainedKnowledge RK = getKnowledgeValidInContext(
642*da58b97aSjoerg             V, {Attribute::Alignment}, Q.CxtI, Q.DT, Q.AC)) {
643*da58b97aSjoerg       Known.Zero.setLowBits(Log2_32(RK.ArgValue));
644*da58b97aSjoerg     }
645*da58b97aSjoerg   }
646*da58b97aSjoerg 
64706f32e7eSjoerg   // Note that the patterns below need to be kept in sync with the code
64806f32e7eSjoerg   // in AssumptionCache::updateAffectedValues.
64906f32e7eSjoerg 
65006f32e7eSjoerg   for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
65106f32e7eSjoerg     if (!AssumeVH)
65206f32e7eSjoerg       continue;
65306f32e7eSjoerg     CallInst *I = cast<CallInst>(AssumeVH);
65406f32e7eSjoerg     assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
65506f32e7eSjoerg            "Got assumption for the wrong function!");
65606f32e7eSjoerg 
65706f32e7eSjoerg     // Warning: This loop can end up being somewhat performance sensitive.
65806f32e7eSjoerg     // We're running this loop for once for each value queried resulting in a
65906f32e7eSjoerg     // runtime of ~O(#assumes * #values).
66006f32e7eSjoerg 
66106f32e7eSjoerg     assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
66206f32e7eSjoerg            "must be an assume intrinsic");
66306f32e7eSjoerg 
66406f32e7eSjoerg     Value *Arg = I->getArgOperand(0);
66506f32e7eSjoerg 
66606f32e7eSjoerg     if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
66706f32e7eSjoerg       assert(BitWidth == 1 && "assume operand is not i1?");
66806f32e7eSjoerg       Known.setAllOnes();
66906f32e7eSjoerg       return;
67006f32e7eSjoerg     }
67106f32e7eSjoerg     if (match(Arg, m_Not(m_Specific(V))) &&
67206f32e7eSjoerg         isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
67306f32e7eSjoerg       assert(BitWidth == 1 && "assume operand is not i1?");
67406f32e7eSjoerg       Known.setAllZero();
67506f32e7eSjoerg       return;
67606f32e7eSjoerg     }
67706f32e7eSjoerg 
67806f32e7eSjoerg     // The remaining tests are all recursive, so bail out if we hit the limit.
679*da58b97aSjoerg     if (Depth == MaxAnalysisRecursionDepth)
68006f32e7eSjoerg       continue;
68106f32e7eSjoerg 
68206f32e7eSjoerg     ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
68306f32e7eSjoerg     if (!Cmp)
68406f32e7eSjoerg       continue;
68506f32e7eSjoerg 
686*da58b97aSjoerg     // We are attempting to compute known bits for the operands of an assume.
687*da58b97aSjoerg     // Do not try to use other assumptions for those recursive calls because
688*da58b97aSjoerg     // that can lead to mutual recursion and a compile-time explosion.
689*da58b97aSjoerg     // An example of the mutual recursion: computeKnownBits can call
690*da58b97aSjoerg     // isKnownNonZero which calls computeKnownBitsFromAssume (this function)
691*da58b97aSjoerg     // and so on.
692*da58b97aSjoerg     Query QueryNoAC = Q;
693*da58b97aSjoerg     QueryNoAC.AC = nullptr;
694*da58b97aSjoerg 
695*da58b97aSjoerg     // Note that ptrtoint may change the bitwidth.
69606f32e7eSjoerg     Value *A, *B;
69706f32e7eSjoerg     auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
69806f32e7eSjoerg 
69906f32e7eSjoerg     CmpInst::Predicate Pred;
70006f32e7eSjoerg     uint64_t C;
70106f32e7eSjoerg     switch (Cmp->getPredicate()) {
70206f32e7eSjoerg     default:
70306f32e7eSjoerg       break;
70406f32e7eSjoerg     case ICmpInst::ICMP_EQ:
70506f32e7eSjoerg       // assume(v = a)
70606f32e7eSjoerg       if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) &&
70706f32e7eSjoerg           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
708*da58b97aSjoerg         KnownBits RHSKnown =
709*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
71006f32e7eSjoerg         Known.Zero |= RHSKnown.Zero;
71106f32e7eSjoerg         Known.One  |= RHSKnown.One;
71206f32e7eSjoerg       // assume(v & b = a)
71306f32e7eSjoerg       } else if (match(Cmp,
71406f32e7eSjoerg                        m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
71506f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
716*da58b97aSjoerg         KnownBits RHSKnown =
717*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
718*da58b97aSjoerg         KnownBits MaskKnown =
719*da58b97aSjoerg             computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
72006f32e7eSjoerg 
72106f32e7eSjoerg         // For those bits in the mask that are known to be one, we can propagate
72206f32e7eSjoerg         // known bits from the RHS to V.
72306f32e7eSjoerg         Known.Zero |= RHSKnown.Zero & MaskKnown.One;
72406f32e7eSjoerg         Known.One  |= RHSKnown.One  & MaskKnown.One;
72506f32e7eSjoerg       // assume(~(v & b) = a)
72606f32e7eSjoerg       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
72706f32e7eSjoerg                                      m_Value(A))) &&
72806f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
729*da58b97aSjoerg         KnownBits RHSKnown =
730*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
731*da58b97aSjoerg         KnownBits MaskKnown =
732*da58b97aSjoerg             computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
73306f32e7eSjoerg 
73406f32e7eSjoerg         // For those bits in the mask that are known to be one, we can propagate
73506f32e7eSjoerg         // inverted known bits from the RHS to V.
73606f32e7eSjoerg         Known.Zero |= RHSKnown.One  & MaskKnown.One;
73706f32e7eSjoerg         Known.One  |= RHSKnown.Zero & MaskKnown.One;
73806f32e7eSjoerg       // assume(v | b = a)
73906f32e7eSjoerg       } else if (match(Cmp,
74006f32e7eSjoerg                        m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
74106f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
742*da58b97aSjoerg         KnownBits RHSKnown =
743*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
744*da58b97aSjoerg         KnownBits BKnown =
745*da58b97aSjoerg             computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
74606f32e7eSjoerg 
74706f32e7eSjoerg         // For those bits in B that are known to be zero, we can propagate known
74806f32e7eSjoerg         // bits from the RHS to V.
74906f32e7eSjoerg         Known.Zero |= RHSKnown.Zero & BKnown.Zero;
75006f32e7eSjoerg         Known.One  |= RHSKnown.One  & BKnown.Zero;
75106f32e7eSjoerg       // assume(~(v | b) = a)
75206f32e7eSjoerg       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
75306f32e7eSjoerg                                      m_Value(A))) &&
75406f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
755*da58b97aSjoerg         KnownBits RHSKnown =
756*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
757*da58b97aSjoerg         KnownBits BKnown =
758*da58b97aSjoerg             computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
75906f32e7eSjoerg 
76006f32e7eSjoerg         // For those bits in B that are known to be zero, we can propagate
76106f32e7eSjoerg         // inverted known bits from the RHS to V.
76206f32e7eSjoerg         Known.Zero |= RHSKnown.One  & BKnown.Zero;
76306f32e7eSjoerg         Known.One  |= RHSKnown.Zero & BKnown.Zero;
76406f32e7eSjoerg       // assume(v ^ b = a)
76506f32e7eSjoerg       } else if (match(Cmp,
76606f32e7eSjoerg                        m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
76706f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
768*da58b97aSjoerg         KnownBits RHSKnown =
769*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
770*da58b97aSjoerg         KnownBits BKnown =
771*da58b97aSjoerg             computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
77206f32e7eSjoerg 
77306f32e7eSjoerg         // For those bits in B that are known to be zero, we can propagate known
77406f32e7eSjoerg         // bits from the RHS to V. For those bits in B that are known to be one,
77506f32e7eSjoerg         // we can propagate inverted known bits from the RHS to V.
77606f32e7eSjoerg         Known.Zero |= RHSKnown.Zero & BKnown.Zero;
77706f32e7eSjoerg         Known.One  |= RHSKnown.One  & BKnown.Zero;
77806f32e7eSjoerg         Known.Zero |= RHSKnown.One  & BKnown.One;
77906f32e7eSjoerg         Known.One  |= RHSKnown.Zero & BKnown.One;
78006f32e7eSjoerg       // assume(~(v ^ b) = a)
78106f32e7eSjoerg       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
78206f32e7eSjoerg                                      m_Value(A))) &&
78306f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
784*da58b97aSjoerg         KnownBits RHSKnown =
785*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
786*da58b97aSjoerg         KnownBits BKnown =
787*da58b97aSjoerg             computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
78806f32e7eSjoerg 
78906f32e7eSjoerg         // For those bits in B that are known to be zero, we can propagate
79006f32e7eSjoerg         // inverted known bits from the RHS to V. For those bits in B that are
79106f32e7eSjoerg         // known to be one, we can propagate known bits from the RHS to V.
79206f32e7eSjoerg         Known.Zero |= RHSKnown.One  & BKnown.Zero;
79306f32e7eSjoerg         Known.One  |= RHSKnown.Zero & BKnown.Zero;
79406f32e7eSjoerg         Known.Zero |= RHSKnown.Zero & BKnown.One;
79506f32e7eSjoerg         Known.One  |= RHSKnown.One  & BKnown.One;
79606f32e7eSjoerg       // assume(v << c = a)
79706f32e7eSjoerg       } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
79806f32e7eSjoerg                                      m_Value(A))) &&
79906f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
800*da58b97aSjoerg         KnownBits RHSKnown =
801*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
802*da58b97aSjoerg 
80306f32e7eSjoerg         // For those bits in RHS that are known, we can propagate them to known
80406f32e7eSjoerg         // bits in V shifted to the right by C.
80506f32e7eSjoerg         RHSKnown.Zero.lshrInPlace(C);
80606f32e7eSjoerg         Known.Zero |= RHSKnown.Zero;
80706f32e7eSjoerg         RHSKnown.One.lshrInPlace(C);
80806f32e7eSjoerg         Known.One  |= RHSKnown.One;
80906f32e7eSjoerg       // assume(~(v << c) = a)
81006f32e7eSjoerg       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
81106f32e7eSjoerg                                      m_Value(A))) &&
81206f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
813*da58b97aSjoerg         KnownBits RHSKnown =
814*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
81506f32e7eSjoerg         // For those bits in RHS that are known, we can propagate them inverted
81606f32e7eSjoerg         // to known bits in V shifted to the right by C.
81706f32e7eSjoerg         RHSKnown.One.lshrInPlace(C);
81806f32e7eSjoerg         Known.Zero |= RHSKnown.One;
81906f32e7eSjoerg         RHSKnown.Zero.lshrInPlace(C);
82006f32e7eSjoerg         Known.One  |= RHSKnown.Zero;
82106f32e7eSjoerg       // assume(v >> c = a)
82206f32e7eSjoerg       } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
82306f32e7eSjoerg                                      m_Value(A))) &&
82406f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
825*da58b97aSjoerg         KnownBits RHSKnown =
826*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
82706f32e7eSjoerg         // For those bits in RHS that are known, we can propagate them to known
82806f32e7eSjoerg         // bits in V shifted to the right by C.
82906f32e7eSjoerg         Known.Zero |= RHSKnown.Zero << C;
83006f32e7eSjoerg         Known.One  |= RHSKnown.One  << C;
83106f32e7eSjoerg       // assume(~(v >> c) = a)
83206f32e7eSjoerg       } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
83306f32e7eSjoerg                                      m_Value(A))) &&
83406f32e7eSjoerg                  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
835*da58b97aSjoerg         KnownBits RHSKnown =
836*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
83706f32e7eSjoerg         // For those bits in RHS that are known, we can propagate them inverted
83806f32e7eSjoerg         // to known bits in V shifted to the right by C.
83906f32e7eSjoerg         Known.Zero |= RHSKnown.One  << C;
84006f32e7eSjoerg         Known.One  |= RHSKnown.Zero << C;
84106f32e7eSjoerg       }
84206f32e7eSjoerg       break;
84306f32e7eSjoerg     case ICmpInst::ICMP_SGE:
84406f32e7eSjoerg       // assume(v >=_s c) where c is non-negative
84506f32e7eSjoerg       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
84606f32e7eSjoerg           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
847*da58b97aSjoerg         KnownBits RHSKnown =
848*da58b97aSjoerg             computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
84906f32e7eSjoerg 
85006f32e7eSjoerg         if (RHSKnown.isNonNegative()) {
85106f32e7eSjoerg           // We know that the sign bit is zero.
85206f32e7eSjoerg           Known.makeNonNegative();
85306f32e7eSjoerg         }
85406f32e7eSjoerg       }
85506f32e7eSjoerg       break;
85606f32e7eSjoerg     case ICmpInst::ICMP_SGT:
85706f32e7eSjoerg       // assume(v >_s c) where c is at least -1.
85806f32e7eSjoerg       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
85906f32e7eSjoerg           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
860*da58b97aSjoerg         KnownBits RHSKnown =
861*da58b97aSjoerg             computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
86206f32e7eSjoerg 
86306f32e7eSjoerg         if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
86406f32e7eSjoerg           // We know that the sign bit is zero.
86506f32e7eSjoerg           Known.makeNonNegative();
86606f32e7eSjoerg         }
86706f32e7eSjoerg       }
86806f32e7eSjoerg       break;
86906f32e7eSjoerg     case ICmpInst::ICMP_SLE:
87006f32e7eSjoerg       // assume(v <=_s c) where c is negative
87106f32e7eSjoerg       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
87206f32e7eSjoerg           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
873*da58b97aSjoerg         KnownBits RHSKnown =
874*da58b97aSjoerg             computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
87506f32e7eSjoerg 
87606f32e7eSjoerg         if (RHSKnown.isNegative()) {
87706f32e7eSjoerg           // We know that the sign bit is one.
87806f32e7eSjoerg           Known.makeNegative();
87906f32e7eSjoerg         }
88006f32e7eSjoerg       }
88106f32e7eSjoerg       break;
88206f32e7eSjoerg     case ICmpInst::ICMP_SLT:
88306f32e7eSjoerg       // assume(v <_s c) where c is non-positive
88406f32e7eSjoerg       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
88506f32e7eSjoerg           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
886*da58b97aSjoerg         KnownBits RHSKnown =
887*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
88806f32e7eSjoerg 
88906f32e7eSjoerg         if (RHSKnown.isZero() || RHSKnown.isNegative()) {
89006f32e7eSjoerg           // We know that the sign bit is one.
89106f32e7eSjoerg           Known.makeNegative();
89206f32e7eSjoerg         }
89306f32e7eSjoerg       }
89406f32e7eSjoerg       break;
89506f32e7eSjoerg     case ICmpInst::ICMP_ULE:
89606f32e7eSjoerg       // assume(v <=_u c)
89706f32e7eSjoerg       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
89806f32e7eSjoerg           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
899*da58b97aSjoerg         KnownBits RHSKnown =
900*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
90106f32e7eSjoerg 
90206f32e7eSjoerg         // Whatever high bits in c are zero are known to be zero.
90306f32e7eSjoerg         Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
90406f32e7eSjoerg       }
90506f32e7eSjoerg       break;
90606f32e7eSjoerg     case ICmpInst::ICMP_ULT:
90706f32e7eSjoerg       // assume(v <_u c)
90806f32e7eSjoerg       if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
90906f32e7eSjoerg           isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
910*da58b97aSjoerg         KnownBits RHSKnown =
911*da58b97aSjoerg             computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
91206f32e7eSjoerg 
91306f32e7eSjoerg         // If the RHS is known zero, then this assumption must be wrong (nothing
91406f32e7eSjoerg         // is unsigned less than zero). Signal a conflict and get out of here.
91506f32e7eSjoerg         if (RHSKnown.isZero()) {
91606f32e7eSjoerg           Known.Zero.setAllBits();
91706f32e7eSjoerg           Known.One.setAllBits();
91806f32e7eSjoerg           break;
91906f32e7eSjoerg         }
92006f32e7eSjoerg 
92106f32e7eSjoerg         // Whatever high bits in c are zero are known to be zero (if c is a power
92206f32e7eSjoerg         // of 2, then one more).
923*da58b97aSjoerg         if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, QueryNoAC))
92406f32e7eSjoerg           Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
92506f32e7eSjoerg         else
92606f32e7eSjoerg           Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
92706f32e7eSjoerg       }
92806f32e7eSjoerg       break;
92906f32e7eSjoerg     }
93006f32e7eSjoerg   }
93106f32e7eSjoerg 
93206f32e7eSjoerg   // If assumptions conflict with each other or previous known bits, then we
93306f32e7eSjoerg   // have a logical fallacy. It's possible that the assumption is not reachable,
93406f32e7eSjoerg   // so this isn't a real bug. On the other hand, the program may have undefined
93506f32e7eSjoerg   // behavior, or we might have a bug in the compiler. We can't assert/crash, so
93606f32e7eSjoerg   // clear out the known bits, try to warn the user, and hope for the best.
93706f32e7eSjoerg   if (Known.Zero.intersects(Known.One)) {
93806f32e7eSjoerg     Known.resetAll();
93906f32e7eSjoerg 
94006f32e7eSjoerg     if (Q.ORE)
94106f32e7eSjoerg       Q.ORE->emit([&]() {
94206f32e7eSjoerg         auto *CxtI = const_cast<Instruction *>(Q.CxtI);
94306f32e7eSjoerg         return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
94406f32e7eSjoerg                                           CxtI)
94506f32e7eSjoerg                << "Detected conflicting code assumptions. Program may "
94606f32e7eSjoerg                   "have undefined behavior, or compiler may have "
94706f32e7eSjoerg                   "internal error.";
94806f32e7eSjoerg       });
94906f32e7eSjoerg   }
95006f32e7eSjoerg }
95106f32e7eSjoerg 
95206f32e7eSjoerg /// Compute known bits from a shift operator, including those with a
95306f32e7eSjoerg /// non-constant shift amount. Known is the output of this function. Known2 is a
954*da58b97aSjoerg /// pre-allocated temporary with the same bit width as Known and on return
955*da58b97aSjoerg /// contains the known bit of the shift value source. KF is an
956*da58b97aSjoerg /// operator-specific function that, given the known-bits and a shift amount,
957*da58b97aSjoerg /// compute the implied known-bits of the shift operator's result respectively
958*da58b97aSjoerg /// for that shift amount. The results from calling KF are conservatively
959*da58b97aSjoerg /// combined for all permitted shift amounts.
computeKnownBitsFromShiftOperator(const Operator * I,const APInt & DemandedElts,KnownBits & Known,KnownBits & Known2,unsigned Depth,const Query & Q,function_ref<KnownBits (const KnownBits &,const KnownBits &)> KF)96006f32e7eSjoerg static void computeKnownBitsFromShiftOperator(
961*da58b97aSjoerg     const Operator *I, const APInt &DemandedElts, KnownBits &Known,
962*da58b97aSjoerg     KnownBits &Known2, unsigned Depth, const Query &Q,
963*da58b97aSjoerg     function_ref<KnownBits(const KnownBits &, const KnownBits &)> KF) {
96406f32e7eSjoerg   unsigned BitWidth = Known.getBitWidth();
965*da58b97aSjoerg   computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
966*da58b97aSjoerg   computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
96706f32e7eSjoerg 
968*da58b97aSjoerg   // Note: We cannot use Known.Zero.getLimitedValue() here, because if
969*da58b97aSjoerg   // BitWidth > 64 and any upper bits are known, we'll end up returning the
970*da58b97aSjoerg   // limit value (which implies all bits are known).
971*da58b97aSjoerg   uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
972*da58b97aSjoerg   uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
973*da58b97aSjoerg   bool ShiftAmtIsConstant = Known.isConstant();
974*da58b97aSjoerg   bool MaxShiftAmtIsOutOfRange = Known.getMaxValue().uge(BitWidth);
97506f32e7eSjoerg 
976*da58b97aSjoerg   if (ShiftAmtIsConstant) {
977*da58b97aSjoerg     Known = KF(Known2, Known);
978*da58b97aSjoerg 
97906f32e7eSjoerg     // If the known bits conflict, this must be an overflowing left shift, so
98006f32e7eSjoerg     // the shift result is poison. We can return anything we want. Choose 0 for
98106f32e7eSjoerg     // the best folding opportunity.
98206f32e7eSjoerg     if (Known.hasConflict())
98306f32e7eSjoerg       Known.setAllZero();
98406f32e7eSjoerg 
98506f32e7eSjoerg     return;
98606f32e7eSjoerg   }
98706f32e7eSjoerg 
98806f32e7eSjoerg   // If the shift amount could be greater than or equal to the bit-width of the
98906f32e7eSjoerg   // LHS, the value could be poison, but bail out because the check below is
990*da58b97aSjoerg   // expensive.
991*da58b97aSjoerg   // TODO: Should we just carry on?
992*da58b97aSjoerg   if (MaxShiftAmtIsOutOfRange) {
99306f32e7eSjoerg     Known.resetAll();
99406f32e7eSjoerg     return;
99506f32e7eSjoerg   }
99606f32e7eSjoerg 
99706f32e7eSjoerg   // It would be more-clearly correct to use the two temporaries for this
99806f32e7eSjoerg   // calculation. Reusing the APInts here to prevent unnecessary allocations.
99906f32e7eSjoerg   Known.resetAll();
100006f32e7eSjoerg 
100106f32e7eSjoerg   // If we know the shifter operand is nonzero, we can sometimes infer more
100206f32e7eSjoerg   // known bits. However this is expensive to compute, so be lazy about it and
100306f32e7eSjoerg   // only compute it when absolutely necessary.
100406f32e7eSjoerg   Optional<bool> ShifterOperandIsNonZero;
100506f32e7eSjoerg 
100606f32e7eSjoerg   // Early exit if we can't constrain any well-defined shift amount.
100706f32e7eSjoerg   if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
100806f32e7eSjoerg       !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
1009*da58b97aSjoerg     ShifterOperandIsNonZero =
1010*da58b97aSjoerg         isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q);
101106f32e7eSjoerg     if (!*ShifterOperandIsNonZero)
101206f32e7eSjoerg       return;
101306f32e7eSjoerg   }
101406f32e7eSjoerg 
101506f32e7eSjoerg   Known.Zero.setAllBits();
101606f32e7eSjoerg   Known.One.setAllBits();
101706f32e7eSjoerg   for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
101806f32e7eSjoerg     // Combine the shifted known input bits only for those shift amounts
101906f32e7eSjoerg     // compatible with its known constraints.
102006f32e7eSjoerg     if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
102106f32e7eSjoerg       continue;
102206f32e7eSjoerg     if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
102306f32e7eSjoerg       continue;
102406f32e7eSjoerg     // If we know the shifter is nonzero, we may be able to infer more known
102506f32e7eSjoerg     // bits. This check is sunk down as far as possible to avoid the expensive
102606f32e7eSjoerg     // call to isKnownNonZero if the cheaper checks above fail.
102706f32e7eSjoerg     if (ShiftAmt == 0) {
102806f32e7eSjoerg       if (!ShifterOperandIsNonZero.hasValue())
102906f32e7eSjoerg         ShifterOperandIsNonZero =
1030*da58b97aSjoerg             isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q);
103106f32e7eSjoerg       if (*ShifterOperandIsNonZero)
103206f32e7eSjoerg         continue;
103306f32e7eSjoerg     }
103406f32e7eSjoerg 
1035*da58b97aSjoerg     Known = KnownBits::commonBits(
1036*da58b97aSjoerg         Known, KF(Known2, KnownBits::makeConstant(APInt(32, ShiftAmt))));
103706f32e7eSjoerg   }
103806f32e7eSjoerg 
103906f32e7eSjoerg   // If the known bits conflict, the result is poison. Return a 0 and hope the
104006f32e7eSjoerg   // caller can further optimize that.
104106f32e7eSjoerg   if (Known.hasConflict())
104206f32e7eSjoerg     Known.setAllZero();
104306f32e7eSjoerg }
104406f32e7eSjoerg 
computeKnownBitsFromOperator(const Operator * I,const APInt & DemandedElts,KnownBits & Known,unsigned Depth,const Query & Q)1045*da58b97aSjoerg static void computeKnownBitsFromOperator(const Operator *I,
1046*da58b97aSjoerg                                          const APInt &DemandedElts,
1047*da58b97aSjoerg                                          KnownBits &Known, unsigned Depth,
1048*da58b97aSjoerg                                          const Query &Q) {
104906f32e7eSjoerg   unsigned BitWidth = Known.getBitWidth();
105006f32e7eSjoerg 
1051*da58b97aSjoerg   KnownBits Known2(BitWidth);
105206f32e7eSjoerg   switch (I->getOpcode()) {
105306f32e7eSjoerg   default: break;
105406f32e7eSjoerg   case Instruction::Load:
105506f32e7eSjoerg     if (MDNode *MD =
105606f32e7eSjoerg             Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
105706f32e7eSjoerg       computeKnownBitsFromRangeMetadata(*MD, Known);
105806f32e7eSjoerg     break;
105906f32e7eSjoerg   case Instruction::And: {
106006f32e7eSjoerg     // If either the LHS or the RHS are Zero, the result is zero.
1061*da58b97aSjoerg     computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1062*da58b97aSjoerg     computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
106306f32e7eSjoerg 
1064*da58b97aSjoerg     Known &= Known2;
106506f32e7eSjoerg 
106606f32e7eSjoerg     // and(x, add (x, -1)) is a common idiom that always clears the low bit;
106706f32e7eSjoerg     // here we handle the more general case of adding any odd number by
106806f32e7eSjoerg     // matching the form add(x, add(x, y)) where y is odd.
106906f32e7eSjoerg     // TODO: This could be generalized to clearing any bit set in y where the
107006f32e7eSjoerg     // following bit is known to be unset in y.
107106f32e7eSjoerg     Value *X = nullptr, *Y = nullptr;
107206f32e7eSjoerg     if (!Known.Zero[0] && !Known.One[0] &&
107306f32e7eSjoerg         match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
107406f32e7eSjoerg       Known2.resetAll();
1075*da58b97aSjoerg       computeKnownBits(Y, DemandedElts, Known2, Depth + 1, Q);
107606f32e7eSjoerg       if (Known2.countMinTrailingOnes() > 0)
107706f32e7eSjoerg         Known.Zero.setBit(0);
107806f32e7eSjoerg     }
107906f32e7eSjoerg     break;
108006f32e7eSjoerg   }
108106f32e7eSjoerg   case Instruction::Or:
1082*da58b97aSjoerg     computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1083*da58b97aSjoerg     computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
108406f32e7eSjoerg 
1085*da58b97aSjoerg     Known |= Known2;
108606f32e7eSjoerg     break;
1087*da58b97aSjoerg   case Instruction::Xor:
1088*da58b97aSjoerg     computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1089*da58b97aSjoerg     computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
109006f32e7eSjoerg 
1091*da58b97aSjoerg     Known ^= Known2;
109206f32e7eSjoerg     break;
109306f32e7eSjoerg   case Instruction::Mul: {
109406f32e7eSjoerg     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1095*da58b97aSjoerg     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, DemandedElts,
1096*da58b97aSjoerg                         Known, Known2, Depth, Q);
109706f32e7eSjoerg     break;
109806f32e7eSjoerg   }
109906f32e7eSjoerg   case Instruction::UDiv: {
1100*da58b97aSjoerg     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
110106f32e7eSjoerg     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1102*da58b97aSjoerg     Known = KnownBits::udiv(Known, Known2);
110306f32e7eSjoerg     break;
110406f32e7eSjoerg   }
110506f32e7eSjoerg   case Instruction::Select: {
110606f32e7eSjoerg     const Value *LHS = nullptr, *RHS = nullptr;
110706f32e7eSjoerg     SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
110806f32e7eSjoerg     if (SelectPatternResult::isMinOrMax(SPF)) {
110906f32e7eSjoerg       computeKnownBits(RHS, Known, Depth + 1, Q);
111006f32e7eSjoerg       computeKnownBits(LHS, Known2, Depth + 1, Q);
1111*da58b97aSjoerg       switch (SPF) {
1112*da58b97aSjoerg       default:
1113*da58b97aSjoerg         llvm_unreachable("Unhandled select pattern flavor!");
1114*da58b97aSjoerg       case SPF_SMAX:
1115*da58b97aSjoerg         Known = KnownBits::smax(Known, Known2);
1116*da58b97aSjoerg         break;
1117*da58b97aSjoerg       case SPF_SMIN:
1118*da58b97aSjoerg         Known = KnownBits::smin(Known, Known2);
1119*da58b97aSjoerg         break;
1120*da58b97aSjoerg       case SPF_UMAX:
1121*da58b97aSjoerg         Known = KnownBits::umax(Known, Known2);
1122*da58b97aSjoerg         break;
1123*da58b97aSjoerg       case SPF_UMIN:
1124*da58b97aSjoerg         Known = KnownBits::umin(Known, Known2);
1125*da58b97aSjoerg         break;
1126*da58b97aSjoerg       }
1127*da58b97aSjoerg       break;
112806f32e7eSjoerg     }
112906f32e7eSjoerg 
1130*da58b97aSjoerg     computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1131*da58b97aSjoerg     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1132*da58b97aSjoerg 
1133*da58b97aSjoerg     // Only known if known in both the LHS and RHS.
1134*da58b97aSjoerg     Known = KnownBits::commonBits(Known, Known2);
1135*da58b97aSjoerg 
1136*da58b97aSjoerg     if (SPF == SPF_ABS) {
113706f32e7eSjoerg       // RHS from matchSelectPattern returns the negation part of abs pattern.
113806f32e7eSjoerg       // If the negate has an NSW flag we can assume the sign bit of the result
113906f32e7eSjoerg       // will be 0 because that makes abs(INT_MIN) undefined.
114006f32e7eSjoerg       if (match(RHS, m_Neg(m_Specific(LHS))) &&
114106f32e7eSjoerg           Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
1142*da58b97aSjoerg         Known.Zero.setSignBit();
114306f32e7eSjoerg     }
114406f32e7eSjoerg 
114506f32e7eSjoerg     break;
114606f32e7eSjoerg   }
114706f32e7eSjoerg   case Instruction::FPTrunc:
114806f32e7eSjoerg   case Instruction::FPExt:
114906f32e7eSjoerg   case Instruction::FPToUI:
115006f32e7eSjoerg   case Instruction::FPToSI:
115106f32e7eSjoerg   case Instruction::SIToFP:
115206f32e7eSjoerg   case Instruction::UIToFP:
115306f32e7eSjoerg     break; // Can't work with floating point.
115406f32e7eSjoerg   case Instruction::PtrToInt:
115506f32e7eSjoerg   case Instruction::IntToPtr:
115606f32e7eSjoerg     // Fall through and handle them the same as zext/trunc.
115706f32e7eSjoerg     LLVM_FALLTHROUGH;
115806f32e7eSjoerg   case Instruction::ZExt:
115906f32e7eSjoerg   case Instruction::Trunc: {
116006f32e7eSjoerg     Type *SrcTy = I->getOperand(0)->getType();
116106f32e7eSjoerg 
116206f32e7eSjoerg     unsigned SrcBitWidth;
116306f32e7eSjoerg     // Note that we handle pointer operands here because of inttoptr/ptrtoint
116406f32e7eSjoerg     // which fall through here.
116506f32e7eSjoerg     Type *ScalarTy = SrcTy->getScalarType();
116606f32e7eSjoerg     SrcBitWidth = ScalarTy->isPointerTy() ?
1167*da58b97aSjoerg       Q.DL.getPointerTypeSizeInBits(ScalarTy) :
116806f32e7eSjoerg       Q.DL.getTypeSizeInBits(ScalarTy);
116906f32e7eSjoerg 
117006f32e7eSjoerg     assert(SrcBitWidth && "SrcBitWidth can't be zero");
1171*da58b97aSjoerg     Known = Known.anyextOrTrunc(SrcBitWidth);
117206f32e7eSjoerg     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1173*da58b97aSjoerg     Known = Known.zextOrTrunc(BitWidth);
117406f32e7eSjoerg     break;
117506f32e7eSjoerg   }
117606f32e7eSjoerg   case Instruction::BitCast: {
117706f32e7eSjoerg     Type *SrcTy = I->getOperand(0)->getType();
117806f32e7eSjoerg     if (SrcTy->isIntOrPtrTy() &&
117906f32e7eSjoerg         // TODO: For now, not handling conversions like:
118006f32e7eSjoerg         // (bitcast i64 %x to <2 x i32>)
118106f32e7eSjoerg         !I->getType()->isVectorTy()) {
118206f32e7eSjoerg       computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
118306f32e7eSjoerg       break;
118406f32e7eSjoerg     }
118506f32e7eSjoerg     break;
118606f32e7eSjoerg   }
118706f32e7eSjoerg   case Instruction::SExt: {
118806f32e7eSjoerg     // Compute the bits in the result that are not present in the input.
118906f32e7eSjoerg     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
119006f32e7eSjoerg 
119106f32e7eSjoerg     Known = Known.trunc(SrcBitWidth);
119206f32e7eSjoerg     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
119306f32e7eSjoerg     // If the sign bit of the input is known set or clear, then we know the
119406f32e7eSjoerg     // top bits of the result.
119506f32e7eSjoerg     Known = Known.sext(BitWidth);
119606f32e7eSjoerg     break;
119706f32e7eSjoerg   }
119806f32e7eSjoerg   case Instruction::Shl: {
119906f32e7eSjoerg     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1200*da58b97aSjoerg     auto KF = [NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1201*da58b97aSjoerg       KnownBits Result = KnownBits::shl(KnownVal, KnownAmt);
120206f32e7eSjoerg       // If this shift has "nsw" keyword, then the result is either a poison
120306f32e7eSjoerg       // value or has the same sign bit as the first operand.
1204*da58b97aSjoerg       if (NSW) {
1205*da58b97aSjoerg         if (KnownVal.Zero.isSignBitSet())
1206*da58b97aSjoerg           Result.Zero.setSignBit();
1207*da58b97aSjoerg         if (KnownVal.One.isSignBitSet())
1208*da58b97aSjoerg           Result.One.setSignBit();
1209*da58b97aSjoerg       }
1210*da58b97aSjoerg       return Result;
121106f32e7eSjoerg     };
1212*da58b97aSjoerg     computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1213*da58b97aSjoerg                                       KF);
1214*da58b97aSjoerg     // Trailing zeros of a right-shifted constant never decrease.
1215*da58b97aSjoerg     const APInt *C;
1216*da58b97aSjoerg     if (match(I->getOperand(0), m_APInt(C)))
1217*da58b97aSjoerg       Known.Zero.setLowBits(C->countTrailingZeros());
121806f32e7eSjoerg     break;
121906f32e7eSjoerg   }
122006f32e7eSjoerg   case Instruction::LShr: {
1221*da58b97aSjoerg     auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1222*da58b97aSjoerg       return KnownBits::lshr(KnownVal, KnownAmt);
122306f32e7eSjoerg     };
1224*da58b97aSjoerg     computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1225*da58b97aSjoerg                                       KF);
1226*da58b97aSjoerg     // Leading zeros of a left-shifted constant never decrease.
1227*da58b97aSjoerg     const APInt *C;
1228*da58b97aSjoerg     if (match(I->getOperand(0), m_APInt(C)))
1229*da58b97aSjoerg       Known.Zero.setHighBits(C->countLeadingZeros());
123006f32e7eSjoerg     break;
123106f32e7eSjoerg   }
123206f32e7eSjoerg   case Instruction::AShr: {
1233*da58b97aSjoerg     auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1234*da58b97aSjoerg       return KnownBits::ashr(KnownVal, KnownAmt);
123506f32e7eSjoerg     };
1236*da58b97aSjoerg     computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1237*da58b97aSjoerg                                       KF);
123806f32e7eSjoerg     break;
123906f32e7eSjoerg   }
124006f32e7eSjoerg   case Instruction::Sub: {
124106f32e7eSjoerg     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
124206f32e7eSjoerg     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1243*da58b97aSjoerg                            DemandedElts, Known, Known2, Depth, Q);
124406f32e7eSjoerg     break;
124506f32e7eSjoerg   }
124606f32e7eSjoerg   case Instruction::Add: {
124706f32e7eSjoerg     bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
124806f32e7eSjoerg     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1249*da58b97aSjoerg                            DemandedElts, Known, Known2, Depth, Q);
125006f32e7eSjoerg     break;
125106f32e7eSjoerg   }
125206f32e7eSjoerg   case Instruction::SRem:
125306f32e7eSjoerg     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
125406f32e7eSjoerg     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1255*da58b97aSjoerg     Known = KnownBits::srem(Known, Known2);
125606f32e7eSjoerg     break;
125706f32e7eSjoerg 
1258*da58b97aSjoerg   case Instruction::URem:
1259*da58b97aSjoerg     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1260*da58b97aSjoerg     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1261*da58b97aSjoerg     Known = KnownBits::urem(Known, Known2);
126206f32e7eSjoerg     break;
1263*da58b97aSjoerg   case Instruction::Alloca:
1264*da58b97aSjoerg     Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1265*da58b97aSjoerg     break;
126606f32e7eSjoerg   case Instruction::GetElementPtr: {
126706f32e7eSjoerg     // Analyze all of the subscripts of this getelementptr instruction
126806f32e7eSjoerg     // to determine if we can prove known low zero bits.
1269*da58b97aSjoerg     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1270*da58b97aSjoerg     // Accumulate the constant indices in a separate variable
1271*da58b97aSjoerg     // to minimize the number of calls to computeForAddSub.
1272*da58b97aSjoerg     APInt AccConstIndices(BitWidth, 0, /*IsSigned*/ true);
127306f32e7eSjoerg 
127406f32e7eSjoerg     gep_type_iterator GTI = gep_type_begin(I);
127506f32e7eSjoerg     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1276*da58b97aSjoerg       // TrailZ can only become smaller, short-circuit if we hit zero.
1277*da58b97aSjoerg       if (Known.isUnknown())
1278*da58b97aSjoerg         break;
1279*da58b97aSjoerg 
128006f32e7eSjoerg       Value *Index = I->getOperand(i);
1281*da58b97aSjoerg 
1282*da58b97aSjoerg       // Handle case when index is zero.
1283*da58b97aSjoerg       Constant *CIndex = dyn_cast<Constant>(Index);
1284*da58b97aSjoerg       if (CIndex && CIndex->isZeroValue())
1285*da58b97aSjoerg         continue;
1286*da58b97aSjoerg 
128706f32e7eSjoerg       if (StructType *STy = GTI.getStructTypeOrNull()) {
128806f32e7eSjoerg         // Handle struct member offset arithmetic.
128906f32e7eSjoerg 
1290*da58b97aSjoerg         assert(CIndex &&
1291*da58b97aSjoerg                "Access to structure field must be known at compile time");
129206f32e7eSjoerg 
129306f32e7eSjoerg         if (CIndex->getType()->isVectorTy())
129406f32e7eSjoerg           Index = CIndex->getSplatValue();
129506f32e7eSjoerg 
129606f32e7eSjoerg         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
129706f32e7eSjoerg         const StructLayout *SL = Q.DL.getStructLayout(STy);
129806f32e7eSjoerg         uint64_t Offset = SL->getElementOffset(Idx);
1299*da58b97aSjoerg         AccConstIndices += Offset;
1300*da58b97aSjoerg         continue;
1301*da58b97aSjoerg       }
1302*da58b97aSjoerg 
130306f32e7eSjoerg       // Handle array index arithmetic.
130406f32e7eSjoerg       Type *IndexedTy = GTI.getIndexedType();
130506f32e7eSjoerg       if (!IndexedTy->isSized()) {
1306*da58b97aSjoerg         Known.resetAll();
130706f32e7eSjoerg         break;
130806f32e7eSjoerg       }
130906f32e7eSjoerg 
1310*da58b97aSjoerg       unsigned IndexBitWidth = Index->getType()->getScalarSizeInBits();
1311*da58b97aSjoerg       KnownBits IndexBits(IndexBitWidth);
1312*da58b97aSjoerg       computeKnownBits(Index, IndexBits, Depth + 1, Q);
1313*da58b97aSjoerg       TypeSize IndexTypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1314*da58b97aSjoerg       uint64_t TypeSizeInBytes = IndexTypeSize.getKnownMinSize();
1315*da58b97aSjoerg       KnownBits ScalingFactor(IndexBitWidth);
1316*da58b97aSjoerg       // Multiply by current sizeof type.
1317*da58b97aSjoerg       // &A[i] == A + i * sizeof(*A[i]).
1318*da58b97aSjoerg       if (IndexTypeSize.isScalable()) {
1319*da58b97aSjoerg         // For scalable types the only thing we know about sizeof is
1320*da58b97aSjoerg         // that this is a multiple of the minimum size.
1321*da58b97aSjoerg         ScalingFactor.Zero.setLowBits(countTrailingZeros(TypeSizeInBytes));
1322*da58b97aSjoerg       } else if (IndexBits.isConstant()) {
1323*da58b97aSjoerg         APInt IndexConst = IndexBits.getConstant();
1324*da58b97aSjoerg         APInt ScalingFactor(IndexBitWidth, TypeSizeInBytes);
1325*da58b97aSjoerg         IndexConst *= ScalingFactor;
1326*da58b97aSjoerg         AccConstIndices += IndexConst.sextOrTrunc(BitWidth);
1327*da58b97aSjoerg         continue;
1328*da58b97aSjoerg       } else {
1329*da58b97aSjoerg         ScalingFactor =
1330*da58b97aSjoerg             KnownBits::makeConstant(APInt(IndexBitWidth, TypeSizeInBytes));
1331*da58b97aSjoerg       }
1332*da58b97aSjoerg       IndexBits = KnownBits::mul(IndexBits, ScalingFactor);
1333*da58b97aSjoerg 
1334*da58b97aSjoerg       // If the offsets have a different width from the pointer, according
1335*da58b97aSjoerg       // to the language reference we need to sign-extend or truncate them
1336*da58b97aSjoerg       // to the width of the pointer.
1337*da58b97aSjoerg       IndexBits = IndexBits.sextOrTrunc(BitWidth);
1338*da58b97aSjoerg 
1339*da58b97aSjoerg       // Note that inbounds does *not* guarantee nsw for the addition, as only
1340*da58b97aSjoerg       // the offset is signed, while the base address is unsigned.
1341*da58b97aSjoerg       Known = KnownBits::computeForAddSub(
1342*da58b97aSjoerg           /*Add=*/true, /*NSW=*/false, Known, IndexBits);
1343*da58b97aSjoerg     }
1344*da58b97aSjoerg     if (!Known.isUnknown() && !AccConstIndices.isNullValue()) {
1345*da58b97aSjoerg       KnownBits Index = KnownBits::makeConstant(AccConstIndices);
1346*da58b97aSjoerg       Known = KnownBits::computeForAddSub(
1347*da58b97aSjoerg           /*Add=*/true, /*NSW=*/false, Known, Index);
1348*da58b97aSjoerg     }
134906f32e7eSjoerg     break;
135006f32e7eSjoerg   }
135106f32e7eSjoerg   case Instruction::PHI: {
135206f32e7eSjoerg     const PHINode *P = cast<PHINode>(I);
1353*da58b97aSjoerg     BinaryOperator *BO = nullptr;
1354*da58b97aSjoerg     Value *R = nullptr, *L = nullptr;
1355*da58b97aSjoerg     if (matchSimpleRecurrence(P, BO, R, L)) {
135606f32e7eSjoerg       // Handle the case of a simple two-predecessor recurrence PHI.
135706f32e7eSjoerg       // There's a lot more that could theoretically be done here, but
135806f32e7eSjoerg       // this is sufficient to catch some interesting cases.
1359*da58b97aSjoerg       unsigned Opcode = BO->getOpcode();
1360*da58b97aSjoerg 
1361*da58b97aSjoerg       // If this is a shift recurrence, we know the bits being shifted in.
1362*da58b97aSjoerg       // We can combine that with information about the start value of the
1363*da58b97aSjoerg       // recurrence to conclude facts about the result.
1364*da58b97aSjoerg       if ((Opcode == Instruction::LShr || Opcode == Instruction::AShr ||
1365*da58b97aSjoerg            Opcode == Instruction::Shl) &&
1366*da58b97aSjoerg           BO->getOperand(0) == I) {
1367*da58b97aSjoerg 
1368*da58b97aSjoerg         // We have matched a recurrence of the form:
1369*da58b97aSjoerg         // %iv = [R, %entry], [%iv.next, %backedge]
1370*da58b97aSjoerg         // %iv.next = shift_op %iv, L
1371*da58b97aSjoerg 
1372*da58b97aSjoerg         // Recurse with the phi context to avoid concern about whether facts
1373*da58b97aSjoerg         // inferred hold at original context instruction.  TODO: It may be
1374*da58b97aSjoerg         // correct to use the original context.  IF warranted, explore and
1375*da58b97aSjoerg         // add sufficient tests to cover.
1376*da58b97aSjoerg         Query RecQ = Q;
1377*da58b97aSjoerg         RecQ.CxtI = P;
1378*da58b97aSjoerg         computeKnownBits(R, DemandedElts, Known2, Depth + 1, RecQ);
1379*da58b97aSjoerg         switch (Opcode) {
1380*da58b97aSjoerg         case Instruction::Shl:
1381*da58b97aSjoerg           // A shl recurrence will only increase the tailing zeros
1382*da58b97aSjoerg           Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1383*da58b97aSjoerg           break;
1384*da58b97aSjoerg         case Instruction::LShr:
1385*da58b97aSjoerg           // A lshr recurrence will preserve the leading zeros of the
1386*da58b97aSjoerg           // start value
1387*da58b97aSjoerg           Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1388*da58b97aSjoerg           break;
1389*da58b97aSjoerg         case Instruction::AShr:
1390*da58b97aSjoerg           // An ashr recurrence will extend the initial sign bit
1391*da58b97aSjoerg           Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1392*da58b97aSjoerg           Known.One.setHighBits(Known2.countMinLeadingOnes());
1393*da58b97aSjoerg           break;
1394*da58b97aSjoerg         };
1395*da58b97aSjoerg       }
1396*da58b97aSjoerg 
139706f32e7eSjoerg       // Check for operations that have the property that if
139806f32e7eSjoerg       // both their operands have low zero bits, the result
139906f32e7eSjoerg       // will have low zero bits.
140006f32e7eSjoerg       if (Opcode == Instruction::Add ||
140106f32e7eSjoerg           Opcode == Instruction::Sub ||
140206f32e7eSjoerg           Opcode == Instruction::And ||
140306f32e7eSjoerg           Opcode == Instruction::Or ||
140406f32e7eSjoerg           Opcode == Instruction::Mul) {
1405*da58b97aSjoerg         // Change the context instruction to the "edge" that flows into the
1406*da58b97aSjoerg         // phi. This is important because that is where the value is actually
1407*da58b97aSjoerg         // "evaluated" even though it is used later somewhere else. (see also
1408*da58b97aSjoerg         // D69571).
1409*da58b97aSjoerg         Query RecQ = Q;
1410*da58b97aSjoerg 
1411*da58b97aSjoerg         unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1412*da58b97aSjoerg         Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1413*da58b97aSjoerg         Instruction *LInst = P->getIncomingBlock(1-OpNum)->getTerminator();
1414*da58b97aSjoerg 
141506f32e7eSjoerg         // Ok, we have a PHI of the form L op= R. Check for low
141606f32e7eSjoerg         // zero bits.
1417*da58b97aSjoerg         RecQ.CxtI = RInst;
1418*da58b97aSjoerg         computeKnownBits(R, Known2, Depth + 1, RecQ);
141906f32e7eSjoerg 
142006f32e7eSjoerg         // We need to take the minimum number of known bits
1421*da58b97aSjoerg         KnownBits Known3(BitWidth);
1422*da58b97aSjoerg         RecQ.CxtI = LInst;
1423*da58b97aSjoerg         computeKnownBits(L, Known3, Depth + 1, RecQ);
142406f32e7eSjoerg 
142506f32e7eSjoerg         Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
142606f32e7eSjoerg                                        Known3.countMinTrailingZeros()));
142706f32e7eSjoerg 
1428*da58b97aSjoerg         auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
142906f32e7eSjoerg         if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
143006f32e7eSjoerg           // If initial value of recurrence is nonnegative, and we are adding
143106f32e7eSjoerg           // a nonnegative number with nsw, the result can only be nonnegative
143206f32e7eSjoerg           // or poison value regardless of the number of times we execute the
143306f32e7eSjoerg           // add in phi recurrence. If initial value is negative and we are
143406f32e7eSjoerg           // adding a negative number with nsw, the result can only be
143506f32e7eSjoerg           // negative or poison value. Similar arguments apply to sub and mul.
143606f32e7eSjoerg           //
143706f32e7eSjoerg           // (add non-negative, non-negative) --> non-negative
143806f32e7eSjoerg           // (add negative, negative) --> negative
143906f32e7eSjoerg           if (Opcode == Instruction::Add) {
144006f32e7eSjoerg             if (Known2.isNonNegative() && Known3.isNonNegative())
144106f32e7eSjoerg               Known.makeNonNegative();
144206f32e7eSjoerg             else if (Known2.isNegative() && Known3.isNegative())
144306f32e7eSjoerg               Known.makeNegative();
144406f32e7eSjoerg           }
144506f32e7eSjoerg 
144606f32e7eSjoerg           // (sub nsw non-negative, negative) --> non-negative
144706f32e7eSjoerg           // (sub nsw negative, non-negative) --> negative
1448*da58b97aSjoerg           else if (Opcode == Instruction::Sub && BO->getOperand(0) == I) {
144906f32e7eSjoerg             if (Known2.isNonNegative() && Known3.isNegative())
145006f32e7eSjoerg               Known.makeNonNegative();
145106f32e7eSjoerg             else if (Known2.isNegative() && Known3.isNonNegative())
145206f32e7eSjoerg               Known.makeNegative();
145306f32e7eSjoerg           }
145406f32e7eSjoerg 
145506f32e7eSjoerg           // (mul nsw non-negative, non-negative) --> non-negative
145606f32e7eSjoerg           else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
145706f32e7eSjoerg                    Known3.isNonNegative())
145806f32e7eSjoerg             Known.makeNonNegative();
145906f32e7eSjoerg         }
146006f32e7eSjoerg 
146106f32e7eSjoerg         break;
146206f32e7eSjoerg       }
146306f32e7eSjoerg     }
146406f32e7eSjoerg 
146506f32e7eSjoerg     // Unreachable blocks may have zero-operand PHI nodes.
146606f32e7eSjoerg     if (P->getNumIncomingValues() == 0)
146706f32e7eSjoerg       break;
146806f32e7eSjoerg 
146906f32e7eSjoerg     // Otherwise take the unions of the known bit sets of the operands,
147006f32e7eSjoerg     // taking conservative care to avoid excessive recursion.
1471*da58b97aSjoerg     if (Depth < MaxAnalysisRecursionDepth - 1 && !Known.Zero && !Known.One) {
147206f32e7eSjoerg       // Skip if every incoming value references to ourself.
147306f32e7eSjoerg       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
147406f32e7eSjoerg         break;
147506f32e7eSjoerg 
147606f32e7eSjoerg       Known.Zero.setAllBits();
147706f32e7eSjoerg       Known.One.setAllBits();
1478*da58b97aSjoerg       for (unsigned u = 0, e = P->getNumIncomingValues(); u < e; ++u) {
1479*da58b97aSjoerg         Value *IncValue = P->getIncomingValue(u);
148006f32e7eSjoerg         // Skip direct self references.
148106f32e7eSjoerg         if (IncValue == P) continue;
148206f32e7eSjoerg 
1483*da58b97aSjoerg         // Change the context instruction to the "edge" that flows into the
1484*da58b97aSjoerg         // phi. This is important because that is where the value is actually
1485*da58b97aSjoerg         // "evaluated" even though it is used later somewhere else. (see also
1486*da58b97aSjoerg         // D69571).
1487*da58b97aSjoerg         Query RecQ = Q;
1488*da58b97aSjoerg         RecQ.CxtI = P->getIncomingBlock(u)->getTerminator();
1489*da58b97aSjoerg 
149006f32e7eSjoerg         Known2 = KnownBits(BitWidth);
149106f32e7eSjoerg         // Recurse, but cap the recursion to one level, because we don't
149206f32e7eSjoerg         // want to waste time spinning around in loops.
1493*da58b97aSjoerg         computeKnownBits(IncValue, Known2, MaxAnalysisRecursionDepth - 1, RecQ);
1494*da58b97aSjoerg         Known = KnownBits::commonBits(Known, Known2);
149506f32e7eSjoerg         // If all bits have been ruled out, there's no need to check
149606f32e7eSjoerg         // more operands.
1497*da58b97aSjoerg         if (Known.isUnknown())
149806f32e7eSjoerg           break;
149906f32e7eSjoerg       }
150006f32e7eSjoerg     }
150106f32e7eSjoerg     break;
150206f32e7eSjoerg   }
150306f32e7eSjoerg   case Instruction::Call:
150406f32e7eSjoerg   case Instruction::Invoke:
150506f32e7eSjoerg     // If range metadata is attached to this call, set known bits from that,
150606f32e7eSjoerg     // and then intersect with known bits based on other properties of the
150706f32e7eSjoerg     // function.
150806f32e7eSjoerg     if (MDNode *MD =
150906f32e7eSjoerg             Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
151006f32e7eSjoerg       computeKnownBitsFromRangeMetadata(*MD, Known);
1511*da58b97aSjoerg     if (const Value *RV = cast<CallBase>(I)->getReturnedArgOperand()) {
151206f32e7eSjoerg       computeKnownBits(RV, Known2, Depth + 1, Q);
151306f32e7eSjoerg       Known.Zero |= Known2.Zero;
151406f32e7eSjoerg       Known.One |= Known2.One;
151506f32e7eSjoerg     }
151606f32e7eSjoerg     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
151706f32e7eSjoerg       switch (II->getIntrinsicID()) {
151806f32e7eSjoerg       default: break;
1519*da58b97aSjoerg       case Intrinsic::abs: {
152006f32e7eSjoerg         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1521*da58b97aSjoerg         bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
1522*da58b97aSjoerg         Known = Known2.abs(IntMinIsPoison);
1523*da58b97aSjoerg         break;
1524*da58b97aSjoerg       }
1525*da58b97aSjoerg       case Intrinsic::bitreverse:
1526*da58b97aSjoerg         computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
152706f32e7eSjoerg         Known.Zero |= Known2.Zero.reverseBits();
152806f32e7eSjoerg         Known.One |= Known2.One.reverseBits();
152906f32e7eSjoerg         break;
153006f32e7eSjoerg       case Intrinsic::bswap:
1531*da58b97aSjoerg         computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
153206f32e7eSjoerg         Known.Zero |= Known2.Zero.byteSwap();
153306f32e7eSjoerg         Known.One |= Known2.One.byteSwap();
153406f32e7eSjoerg         break;
153506f32e7eSjoerg       case Intrinsic::ctlz: {
153606f32e7eSjoerg         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
153706f32e7eSjoerg         // If we have a known 1, its position is our upper bound.
1538*da58b97aSjoerg         unsigned PossibleLZ = Known2.countMaxLeadingZeros();
153906f32e7eSjoerg         // If this call is undefined for 0, the result will be less than 2^n.
154006f32e7eSjoerg         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
154106f32e7eSjoerg           PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
154206f32e7eSjoerg         unsigned LowBits = Log2_32(PossibleLZ)+1;
154306f32e7eSjoerg         Known.Zero.setBitsFrom(LowBits);
154406f32e7eSjoerg         break;
154506f32e7eSjoerg       }
154606f32e7eSjoerg       case Intrinsic::cttz: {
154706f32e7eSjoerg         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
154806f32e7eSjoerg         // If we have a known 1, its position is our upper bound.
1549*da58b97aSjoerg         unsigned PossibleTZ = Known2.countMaxTrailingZeros();
155006f32e7eSjoerg         // If this call is undefined for 0, the result will be less than 2^n.
155106f32e7eSjoerg         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
155206f32e7eSjoerg           PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
155306f32e7eSjoerg         unsigned LowBits = Log2_32(PossibleTZ)+1;
155406f32e7eSjoerg         Known.Zero.setBitsFrom(LowBits);
155506f32e7eSjoerg         break;
155606f32e7eSjoerg       }
155706f32e7eSjoerg       case Intrinsic::ctpop: {
155806f32e7eSjoerg         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
155906f32e7eSjoerg         // We can bound the space the count needs.  Also, bits known to be zero
156006f32e7eSjoerg         // can't contribute to the population.
156106f32e7eSjoerg         unsigned BitsPossiblySet = Known2.countMaxPopulation();
156206f32e7eSjoerg         unsigned LowBits = Log2_32(BitsPossiblySet)+1;
156306f32e7eSjoerg         Known.Zero.setBitsFrom(LowBits);
156406f32e7eSjoerg         // TODO: we could bound KnownOne using the lower bound on the number
156506f32e7eSjoerg         // of bits which might be set provided by popcnt KnownOne2.
156606f32e7eSjoerg         break;
156706f32e7eSjoerg       }
156806f32e7eSjoerg       case Intrinsic::fshr:
156906f32e7eSjoerg       case Intrinsic::fshl: {
157006f32e7eSjoerg         const APInt *SA;
157106f32e7eSjoerg         if (!match(I->getOperand(2), m_APInt(SA)))
157206f32e7eSjoerg           break;
157306f32e7eSjoerg 
157406f32e7eSjoerg         // Normalize to funnel shift left.
157506f32e7eSjoerg         uint64_t ShiftAmt = SA->urem(BitWidth);
157606f32e7eSjoerg         if (II->getIntrinsicID() == Intrinsic::fshr)
157706f32e7eSjoerg           ShiftAmt = BitWidth - ShiftAmt;
157806f32e7eSjoerg 
1579*da58b97aSjoerg         KnownBits Known3(BitWidth);
158006f32e7eSjoerg         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
158106f32e7eSjoerg         computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
158206f32e7eSjoerg 
158306f32e7eSjoerg         Known.Zero =
158406f32e7eSjoerg             Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
158506f32e7eSjoerg         Known.One =
158606f32e7eSjoerg             Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
158706f32e7eSjoerg         break;
158806f32e7eSjoerg       }
158906f32e7eSjoerg       case Intrinsic::uadd_sat:
159006f32e7eSjoerg       case Intrinsic::usub_sat: {
159106f32e7eSjoerg         bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
159206f32e7eSjoerg         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
159306f32e7eSjoerg         computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
159406f32e7eSjoerg 
159506f32e7eSjoerg         // Add: Leading ones of either operand are preserved.
159606f32e7eSjoerg         // Sub: Leading zeros of LHS and leading ones of RHS are preserved
159706f32e7eSjoerg         // as leading zeros in the result.
159806f32e7eSjoerg         unsigned LeadingKnown;
159906f32e7eSjoerg         if (IsAdd)
160006f32e7eSjoerg           LeadingKnown = std::max(Known.countMinLeadingOnes(),
160106f32e7eSjoerg                                   Known2.countMinLeadingOnes());
160206f32e7eSjoerg         else
160306f32e7eSjoerg           LeadingKnown = std::max(Known.countMinLeadingZeros(),
160406f32e7eSjoerg                                   Known2.countMinLeadingOnes());
160506f32e7eSjoerg 
160606f32e7eSjoerg         Known = KnownBits::computeForAddSub(
160706f32e7eSjoerg             IsAdd, /* NSW */ false, Known, Known2);
160806f32e7eSjoerg 
160906f32e7eSjoerg         // We select between the operation result and all-ones/zero
161006f32e7eSjoerg         // respectively, so we can preserve known ones/zeros.
161106f32e7eSjoerg         if (IsAdd) {
161206f32e7eSjoerg           Known.One.setHighBits(LeadingKnown);
161306f32e7eSjoerg           Known.Zero.clearAllBits();
161406f32e7eSjoerg         } else {
161506f32e7eSjoerg           Known.Zero.setHighBits(LeadingKnown);
161606f32e7eSjoerg           Known.One.clearAllBits();
161706f32e7eSjoerg         }
161806f32e7eSjoerg         break;
161906f32e7eSjoerg       }
1620*da58b97aSjoerg       case Intrinsic::umin:
1621*da58b97aSjoerg         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1622*da58b97aSjoerg         computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1623*da58b97aSjoerg         Known = KnownBits::umin(Known, Known2);
1624*da58b97aSjoerg         break;
1625*da58b97aSjoerg       case Intrinsic::umax:
1626*da58b97aSjoerg         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1627*da58b97aSjoerg         computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1628*da58b97aSjoerg         Known = KnownBits::umax(Known, Known2);
1629*da58b97aSjoerg         break;
1630*da58b97aSjoerg       case Intrinsic::smin:
1631*da58b97aSjoerg         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1632*da58b97aSjoerg         computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1633*da58b97aSjoerg         Known = KnownBits::smin(Known, Known2);
1634*da58b97aSjoerg         break;
1635*da58b97aSjoerg       case Intrinsic::smax:
1636*da58b97aSjoerg         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1637*da58b97aSjoerg         computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1638*da58b97aSjoerg         Known = KnownBits::smax(Known, Known2);
1639*da58b97aSjoerg         break;
164006f32e7eSjoerg       case Intrinsic::x86_sse42_crc32_64_64:
164106f32e7eSjoerg         Known.Zero.setBitsFrom(32);
164206f32e7eSjoerg         break;
1643*da58b97aSjoerg       case Intrinsic::riscv_vsetvli:
1644*da58b97aSjoerg       case Intrinsic::riscv_vsetvlimax:
1645*da58b97aSjoerg         // Assume that VL output is positive and would fit in an int32_t.
1646*da58b97aSjoerg         // TODO: VLEN might be capped at 16 bits in a future V spec update.
1647*da58b97aSjoerg         if (BitWidth >= 32)
1648*da58b97aSjoerg           Known.Zero.setBitsFrom(31);
1649*da58b97aSjoerg         break;
165006f32e7eSjoerg       }
165106f32e7eSjoerg     }
165206f32e7eSjoerg     break;
1653*da58b97aSjoerg   case Instruction::ShuffleVector: {
1654*da58b97aSjoerg     auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
1655*da58b97aSjoerg     // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
1656*da58b97aSjoerg     if (!Shuf) {
1657*da58b97aSjoerg       Known.resetAll();
1658*da58b97aSjoerg       return;
1659*da58b97aSjoerg     }
1660*da58b97aSjoerg     // For undef elements, we don't know anything about the common state of
1661*da58b97aSjoerg     // the shuffle result.
1662*da58b97aSjoerg     APInt DemandedLHS, DemandedRHS;
1663*da58b97aSjoerg     if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
1664*da58b97aSjoerg       Known.resetAll();
1665*da58b97aSjoerg       return;
1666*da58b97aSjoerg     }
1667*da58b97aSjoerg     Known.One.setAllBits();
1668*da58b97aSjoerg     Known.Zero.setAllBits();
1669*da58b97aSjoerg     if (!!DemandedLHS) {
1670*da58b97aSjoerg       const Value *LHS = Shuf->getOperand(0);
1671*da58b97aSjoerg       computeKnownBits(LHS, DemandedLHS, Known, Depth + 1, Q);
1672*da58b97aSjoerg       // If we don't know any bits, early out.
1673*da58b97aSjoerg       if (Known.isUnknown())
167406f32e7eSjoerg         break;
1675*da58b97aSjoerg     }
1676*da58b97aSjoerg     if (!!DemandedRHS) {
1677*da58b97aSjoerg       const Value *RHS = Shuf->getOperand(1);
1678*da58b97aSjoerg       computeKnownBits(RHS, DemandedRHS, Known2, Depth + 1, Q);
1679*da58b97aSjoerg       Known = KnownBits::commonBits(Known, Known2);
1680*da58b97aSjoerg     }
1681*da58b97aSjoerg     break;
1682*da58b97aSjoerg   }
1683*da58b97aSjoerg   case Instruction::InsertElement: {
1684*da58b97aSjoerg     const Value *Vec = I->getOperand(0);
1685*da58b97aSjoerg     const Value *Elt = I->getOperand(1);
1686*da58b97aSjoerg     auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
1687*da58b97aSjoerg     // Early out if the index is non-constant or out-of-range.
1688*da58b97aSjoerg     unsigned NumElts = DemandedElts.getBitWidth();
1689*da58b97aSjoerg     if (!CIdx || CIdx->getValue().uge(NumElts)) {
1690*da58b97aSjoerg       Known.resetAll();
1691*da58b97aSjoerg       return;
1692*da58b97aSjoerg     }
1693*da58b97aSjoerg     Known.One.setAllBits();
1694*da58b97aSjoerg     Known.Zero.setAllBits();
1695*da58b97aSjoerg     unsigned EltIdx = CIdx->getZExtValue();
1696*da58b97aSjoerg     // Do we demand the inserted element?
1697*da58b97aSjoerg     if (DemandedElts[EltIdx]) {
1698*da58b97aSjoerg       computeKnownBits(Elt, Known, Depth + 1, Q);
1699*da58b97aSjoerg       // If we don't know any bits, early out.
1700*da58b97aSjoerg       if (Known.isUnknown())
1701*da58b97aSjoerg         break;
1702*da58b97aSjoerg     }
1703*da58b97aSjoerg     // We don't need the base vector element that has been inserted.
1704*da58b97aSjoerg     APInt DemandedVecElts = DemandedElts;
1705*da58b97aSjoerg     DemandedVecElts.clearBit(EltIdx);
1706*da58b97aSjoerg     if (!!DemandedVecElts) {
1707*da58b97aSjoerg       computeKnownBits(Vec, DemandedVecElts, Known2, Depth + 1, Q);
1708*da58b97aSjoerg       Known = KnownBits::commonBits(Known, Known2);
1709*da58b97aSjoerg     }
1710*da58b97aSjoerg     break;
1711*da58b97aSjoerg   }
1712*da58b97aSjoerg   case Instruction::ExtractElement: {
1713*da58b97aSjoerg     // Look through extract element. If the index is non-constant or
1714*da58b97aSjoerg     // out-of-range demand all elements, otherwise just the extracted element.
1715*da58b97aSjoerg     const Value *Vec = I->getOperand(0);
1716*da58b97aSjoerg     const Value *Idx = I->getOperand(1);
1717*da58b97aSjoerg     auto *CIdx = dyn_cast<ConstantInt>(Idx);
1718*da58b97aSjoerg     if (isa<ScalableVectorType>(Vec->getType())) {
1719*da58b97aSjoerg       // FIXME: there's probably *something* we can do with scalable vectors
1720*da58b97aSjoerg       Known.resetAll();
1721*da58b97aSjoerg       break;
1722*da58b97aSjoerg     }
1723*da58b97aSjoerg     unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1724*da58b97aSjoerg     APInt DemandedVecElts = APInt::getAllOnesValue(NumElts);
1725*da58b97aSjoerg     if (CIdx && CIdx->getValue().ult(NumElts))
1726*da58b97aSjoerg       DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
1727*da58b97aSjoerg     computeKnownBits(Vec, DemandedVecElts, Known, Depth + 1, Q);
1728*da58b97aSjoerg     break;
1729*da58b97aSjoerg   }
173006f32e7eSjoerg   case Instruction::ExtractValue:
173106f32e7eSjoerg     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
173206f32e7eSjoerg       const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
173306f32e7eSjoerg       if (EVI->getNumIndices() != 1) break;
173406f32e7eSjoerg       if (EVI->getIndices()[0] == 0) {
173506f32e7eSjoerg         switch (II->getIntrinsicID()) {
173606f32e7eSjoerg         default: break;
173706f32e7eSjoerg         case Intrinsic::uadd_with_overflow:
173806f32e7eSjoerg         case Intrinsic::sadd_with_overflow:
173906f32e7eSjoerg           computeKnownBitsAddSub(true, II->getArgOperand(0),
1740*da58b97aSjoerg                                  II->getArgOperand(1), false, DemandedElts,
1741*da58b97aSjoerg                                  Known, Known2, Depth, Q);
174206f32e7eSjoerg           break;
174306f32e7eSjoerg         case Intrinsic::usub_with_overflow:
174406f32e7eSjoerg         case Intrinsic::ssub_with_overflow:
174506f32e7eSjoerg           computeKnownBitsAddSub(false, II->getArgOperand(0),
1746*da58b97aSjoerg                                  II->getArgOperand(1), false, DemandedElts,
1747*da58b97aSjoerg                                  Known, Known2, Depth, Q);
174806f32e7eSjoerg           break;
174906f32e7eSjoerg         case Intrinsic::umul_with_overflow:
175006f32e7eSjoerg         case Intrinsic::smul_with_overflow:
175106f32e7eSjoerg           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1752*da58b97aSjoerg                               DemandedElts, Known, Known2, Depth, Q);
175306f32e7eSjoerg           break;
175406f32e7eSjoerg         }
175506f32e7eSjoerg       }
175606f32e7eSjoerg     }
1757*da58b97aSjoerg     break;
1758*da58b97aSjoerg   case Instruction::Freeze:
1759*da58b97aSjoerg     if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
1760*da58b97aSjoerg                                   Depth + 1))
1761*da58b97aSjoerg       computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1762*da58b97aSjoerg     break;
176306f32e7eSjoerg   }
176406f32e7eSjoerg }
176506f32e7eSjoerg 
176606f32e7eSjoerg /// Determine which bits of V are known to be either zero or one and return
176706f32e7eSjoerg /// them.
computeKnownBits(const Value * V,const APInt & DemandedElts,unsigned Depth,const Query & Q)1768*da58b97aSjoerg KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
1769*da58b97aSjoerg                            unsigned Depth, const Query &Q) {
1770*da58b97aSjoerg   KnownBits Known(getBitWidth(V->getType(), Q.DL));
1771*da58b97aSjoerg   computeKnownBits(V, DemandedElts, Known, Depth, Q);
1772*da58b97aSjoerg   return Known;
1773*da58b97aSjoerg }
1774*da58b97aSjoerg 
1775*da58b97aSjoerg /// Determine which bits of V are known to be either zero or one and return
1776*da58b97aSjoerg /// them.
computeKnownBits(const Value * V,unsigned Depth,const Query & Q)177706f32e7eSjoerg KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
177806f32e7eSjoerg   KnownBits Known(getBitWidth(V->getType(), Q.DL));
177906f32e7eSjoerg   computeKnownBits(V, Known, Depth, Q);
178006f32e7eSjoerg   return Known;
178106f32e7eSjoerg }
178206f32e7eSjoerg 
178306f32e7eSjoerg /// Determine which bits of V are known to be either zero or one and return
178406f32e7eSjoerg /// them in the Known bit set.
178506f32e7eSjoerg ///
178606f32e7eSjoerg /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
178706f32e7eSjoerg /// we cannot optimize based on the assumption that it is zero without changing
178806f32e7eSjoerg /// it to be an explicit zero.  If we don't change it to zero, other code could
178906f32e7eSjoerg /// optimized based on the contradictory assumption that it is non-zero.
179006f32e7eSjoerg /// Because instcombine aggressively folds operations with undef args anyway,
179106f32e7eSjoerg /// this won't lose us code quality.
179206f32e7eSjoerg ///
179306f32e7eSjoerg /// This function is defined on values with integer type, values with pointer
179406f32e7eSjoerg /// type, and vectors of integers.  In the case
179506f32e7eSjoerg /// where V is a vector, known zero, and known one values are the
179606f32e7eSjoerg /// same width as the vector element, and the bit is set only if it is true
1797*da58b97aSjoerg /// for all of the demanded elements in the vector specified by DemandedElts.
computeKnownBits(const Value * V,const APInt & DemandedElts,KnownBits & Known,unsigned Depth,const Query & Q)1798*da58b97aSjoerg void computeKnownBits(const Value *V, const APInt &DemandedElts,
1799*da58b97aSjoerg                       KnownBits &Known, unsigned Depth, const Query &Q) {
1800*da58b97aSjoerg   if (!DemandedElts || isa<ScalableVectorType>(V->getType())) {
1801*da58b97aSjoerg     // No demanded elts or V is a scalable vector, better to assume we don't
1802*da58b97aSjoerg     // know anything.
1803*da58b97aSjoerg     Known.resetAll();
1804*da58b97aSjoerg     return;
1805*da58b97aSjoerg   }
1806*da58b97aSjoerg 
180706f32e7eSjoerg   assert(V && "No Value?");
1808*da58b97aSjoerg   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1809*da58b97aSjoerg 
1810*da58b97aSjoerg #ifndef NDEBUG
1811*da58b97aSjoerg   Type *Ty = V->getType();
181206f32e7eSjoerg   unsigned BitWidth = Known.getBitWidth();
181306f32e7eSjoerg 
1814*da58b97aSjoerg   assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
181506f32e7eSjoerg          "Not integer or pointer type!");
181606f32e7eSjoerg 
1817*da58b97aSjoerg   if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
1818*da58b97aSjoerg     assert(
1819*da58b97aSjoerg         FVTy->getNumElements() == DemandedElts.getBitWidth() &&
1820*da58b97aSjoerg         "DemandedElt width should equal the fixed vector number of elements");
1821*da58b97aSjoerg   } else {
1822*da58b97aSjoerg     assert(DemandedElts == APInt(1, 1) &&
1823*da58b97aSjoerg            "DemandedElt width should be 1 for scalars");
1824*da58b97aSjoerg   }
1825*da58b97aSjoerg 
1826*da58b97aSjoerg   Type *ScalarTy = Ty->getScalarType();
1827*da58b97aSjoerg   if (ScalarTy->isPointerTy()) {
1828*da58b97aSjoerg     assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
1829*da58b97aSjoerg            "V and Known should have same BitWidth");
1830*da58b97aSjoerg   } else {
1831*da58b97aSjoerg     assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
1832*da58b97aSjoerg            "V and Known should have same BitWidth");
1833*da58b97aSjoerg   }
1834*da58b97aSjoerg #endif
183506f32e7eSjoerg 
183606f32e7eSjoerg   const APInt *C;
183706f32e7eSjoerg   if (match(V, m_APInt(C))) {
183806f32e7eSjoerg     // We know all of the bits for a scalar constant or a splat vector constant!
1839*da58b97aSjoerg     Known = KnownBits::makeConstant(*C);
184006f32e7eSjoerg     return;
184106f32e7eSjoerg   }
184206f32e7eSjoerg   // Null and aggregate-zero are all-zeros.
184306f32e7eSjoerg   if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
184406f32e7eSjoerg     Known.setAllZero();
184506f32e7eSjoerg     return;
184606f32e7eSjoerg   }
184706f32e7eSjoerg   // Handle a constant vector by taking the intersection of the known bits of
184806f32e7eSjoerg   // each element.
1849*da58b97aSjoerg   if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
1850*da58b97aSjoerg     // We know that CDV must be a vector of integers. Take the intersection of
185106f32e7eSjoerg     // each element.
185206f32e7eSjoerg     Known.Zero.setAllBits(); Known.One.setAllBits();
1853*da58b97aSjoerg     for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
1854*da58b97aSjoerg       if (!DemandedElts[i])
1855*da58b97aSjoerg         continue;
1856*da58b97aSjoerg       APInt Elt = CDV->getElementAsAPInt(i);
185706f32e7eSjoerg       Known.Zero &= ~Elt;
185806f32e7eSjoerg       Known.One &= Elt;
185906f32e7eSjoerg     }
186006f32e7eSjoerg     return;
186106f32e7eSjoerg   }
186206f32e7eSjoerg 
186306f32e7eSjoerg   if (const auto *CV = dyn_cast<ConstantVector>(V)) {
186406f32e7eSjoerg     // We know that CV must be a vector of integers. Take the intersection of
186506f32e7eSjoerg     // each element.
186606f32e7eSjoerg     Known.Zero.setAllBits(); Known.One.setAllBits();
186706f32e7eSjoerg     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1868*da58b97aSjoerg       if (!DemandedElts[i])
1869*da58b97aSjoerg         continue;
187006f32e7eSjoerg       Constant *Element = CV->getAggregateElement(i);
187106f32e7eSjoerg       auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
187206f32e7eSjoerg       if (!ElementCI) {
187306f32e7eSjoerg         Known.resetAll();
187406f32e7eSjoerg         return;
187506f32e7eSjoerg       }
187606f32e7eSjoerg       const APInt &Elt = ElementCI->getValue();
187706f32e7eSjoerg       Known.Zero &= ~Elt;
187806f32e7eSjoerg       Known.One &= Elt;
187906f32e7eSjoerg     }
188006f32e7eSjoerg     return;
188106f32e7eSjoerg   }
188206f32e7eSjoerg 
188306f32e7eSjoerg   // Start out not knowing anything.
188406f32e7eSjoerg   Known.resetAll();
188506f32e7eSjoerg 
188606f32e7eSjoerg   // We can't imply anything about undefs.
188706f32e7eSjoerg   if (isa<UndefValue>(V))
188806f32e7eSjoerg     return;
188906f32e7eSjoerg 
189006f32e7eSjoerg   // There's no point in looking through other users of ConstantData for
189106f32e7eSjoerg   // assumptions.  Confirm that we've handled them all.
189206f32e7eSjoerg   assert(!isa<ConstantData>(V) && "Unhandled constant data!");
189306f32e7eSjoerg 
189406f32e7eSjoerg   // All recursive calls that increase depth must come after this.
1895*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
189606f32e7eSjoerg     return;
189706f32e7eSjoerg 
189806f32e7eSjoerg   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
189906f32e7eSjoerg   // the bits of its aliasee.
190006f32e7eSjoerg   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
190106f32e7eSjoerg     if (!GA->isInterposable())
190206f32e7eSjoerg       computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
190306f32e7eSjoerg     return;
190406f32e7eSjoerg   }
190506f32e7eSjoerg 
190606f32e7eSjoerg   if (const Operator *I = dyn_cast<Operator>(V))
1907*da58b97aSjoerg     computeKnownBitsFromOperator(I, DemandedElts, Known, Depth, Q);
190806f32e7eSjoerg 
190906f32e7eSjoerg   // Aligned pointers have trailing zeros - refine Known.Zero set
1910*da58b97aSjoerg   if (isa<PointerType>(V->getType())) {
1911*da58b97aSjoerg     Align Alignment = V->getPointerAlignment(Q.DL);
1912*da58b97aSjoerg     Known.Zero.setLowBits(Log2(Alignment));
191306f32e7eSjoerg   }
191406f32e7eSjoerg 
191506f32e7eSjoerg   // computeKnownBitsFromAssume strictly refines Known.
191606f32e7eSjoerg   // Therefore, we run them after computeKnownBitsFromOperator.
191706f32e7eSjoerg 
191806f32e7eSjoerg   // Check whether a nearby assume intrinsic can determine some known bits.
191906f32e7eSjoerg   computeKnownBitsFromAssume(V, Known, Depth, Q);
192006f32e7eSjoerg 
192106f32e7eSjoerg   assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
192206f32e7eSjoerg }
192306f32e7eSjoerg 
192406f32e7eSjoerg /// Return true if the given value is known to have exactly one
192506f32e7eSjoerg /// bit set when defined. For vectors return true if every element is known to
192606f32e7eSjoerg /// be a power of two when defined. Supports values with integer or pointer
192706f32e7eSjoerg /// types and vectors of integers.
isKnownToBeAPowerOfTwo(const Value * V,bool OrZero,unsigned Depth,const Query & Q)192806f32e7eSjoerg bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
192906f32e7eSjoerg                             const Query &Q) {
1930*da58b97aSjoerg   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
193106f32e7eSjoerg 
193206f32e7eSjoerg   // Attempt to match against constants.
193306f32e7eSjoerg   if (OrZero && match(V, m_Power2OrZero()))
193406f32e7eSjoerg       return true;
193506f32e7eSjoerg   if (match(V, m_Power2()))
193606f32e7eSjoerg       return true;
193706f32e7eSjoerg 
193806f32e7eSjoerg   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
193906f32e7eSjoerg   // it is shifted off the end then the result is undefined.
194006f32e7eSjoerg   if (match(V, m_Shl(m_One(), m_Value())))
194106f32e7eSjoerg     return true;
194206f32e7eSjoerg 
194306f32e7eSjoerg   // (signmask) >>l X is clearly a power of two if the one is not shifted off
194406f32e7eSjoerg   // the bottom.  If it is shifted off the bottom then the result is undefined.
194506f32e7eSjoerg   if (match(V, m_LShr(m_SignMask(), m_Value())))
194606f32e7eSjoerg     return true;
194706f32e7eSjoerg 
194806f32e7eSjoerg   // The remaining tests are all recursive, so bail out if we hit the limit.
1949*da58b97aSjoerg   if (Depth++ == MaxAnalysisRecursionDepth)
195006f32e7eSjoerg     return false;
195106f32e7eSjoerg 
195206f32e7eSjoerg   Value *X = nullptr, *Y = nullptr;
195306f32e7eSjoerg   // A shift left or a logical shift right of a power of two is a power of two
195406f32e7eSjoerg   // or zero.
195506f32e7eSjoerg   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
195606f32e7eSjoerg                  match(V, m_LShr(m_Value(X), m_Value()))))
195706f32e7eSjoerg     return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
195806f32e7eSjoerg 
195906f32e7eSjoerg   if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
196006f32e7eSjoerg     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
196106f32e7eSjoerg 
196206f32e7eSjoerg   if (const SelectInst *SI = dyn_cast<SelectInst>(V))
196306f32e7eSjoerg     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
196406f32e7eSjoerg            isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
196506f32e7eSjoerg 
1966*da58b97aSjoerg   // Peek through min/max.
1967*da58b97aSjoerg   if (match(V, m_MaxOrMin(m_Value(X), m_Value(Y)))) {
1968*da58b97aSjoerg     return isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q) &&
1969*da58b97aSjoerg            isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q);
1970*da58b97aSjoerg   }
1971*da58b97aSjoerg 
197206f32e7eSjoerg   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
197306f32e7eSjoerg     // A power of two and'd with anything is a power of two or zero.
197406f32e7eSjoerg     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
197506f32e7eSjoerg         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
197606f32e7eSjoerg       return true;
197706f32e7eSjoerg     // X & (-X) is always a power of two or zero.
197806f32e7eSjoerg     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
197906f32e7eSjoerg       return true;
198006f32e7eSjoerg     return false;
198106f32e7eSjoerg   }
198206f32e7eSjoerg 
198306f32e7eSjoerg   // Adding a power-of-two or zero to the same power-of-two or zero yields
198406f32e7eSjoerg   // either the original power-of-two, a larger power-of-two or zero.
198506f32e7eSjoerg   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
198606f32e7eSjoerg     const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
198706f32e7eSjoerg     if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
198806f32e7eSjoerg         Q.IIQ.hasNoSignedWrap(VOBO)) {
198906f32e7eSjoerg       if (match(X, m_And(m_Specific(Y), m_Value())) ||
199006f32e7eSjoerg           match(X, m_And(m_Value(), m_Specific(Y))))
199106f32e7eSjoerg         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
199206f32e7eSjoerg           return true;
199306f32e7eSjoerg       if (match(Y, m_And(m_Specific(X), m_Value())) ||
199406f32e7eSjoerg           match(Y, m_And(m_Value(), m_Specific(X))))
199506f32e7eSjoerg         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
199606f32e7eSjoerg           return true;
199706f32e7eSjoerg 
199806f32e7eSjoerg       unsigned BitWidth = V->getType()->getScalarSizeInBits();
199906f32e7eSjoerg       KnownBits LHSBits(BitWidth);
200006f32e7eSjoerg       computeKnownBits(X, LHSBits, Depth, Q);
200106f32e7eSjoerg 
200206f32e7eSjoerg       KnownBits RHSBits(BitWidth);
200306f32e7eSjoerg       computeKnownBits(Y, RHSBits, Depth, Q);
200406f32e7eSjoerg       // If i8 V is a power of two or zero:
200506f32e7eSjoerg       //  ZeroBits: 1 1 1 0 1 1 1 1
200606f32e7eSjoerg       // ~ZeroBits: 0 0 0 1 0 0 0 0
200706f32e7eSjoerg       if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
200806f32e7eSjoerg         // If OrZero isn't set, we cannot give back a zero result.
200906f32e7eSjoerg         // Make sure either the LHS or RHS has a bit set.
201006f32e7eSjoerg         if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
201106f32e7eSjoerg           return true;
201206f32e7eSjoerg     }
201306f32e7eSjoerg   }
201406f32e7eSjoerg 
201506f32e7eSjoerg   // An exact divide or right shift can only shift off zero bits, so the result
201606f32e7eSjoerg   // is a power of two only if the first operand is a power of two and not
201706f32e7eSjoerg   // copying a sign bit (sdiv int_min, 2).
201806f32e7eSjoerg   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
201906f32e7eSjoerg       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
202006f32e7eSjoerg     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
202106f32e7eSjoerg                                   Depth, Q);
202206f32e7eSjoerg   }
202306f32e7eSjoerg 
202406f32e7eSjoerg   return false;
202506f32e7eSjoerg }
202606f32e7eSjoerg 
202706f32e7eSjoerg /// Test whether a GEP's result is known to be non-null.
202806f32e7eSjoerg ///
202906f32e7eSjoerg /// Uses properties inherent in a GEP to try to determine whether it is known
203006f32e7eSjoerg /// to be non-null.
203106f32e7eSjoerg ///
203206f32e7eSjoerg /// Currently this routine does not support vector GEPs.
isGEPKnownNonNull(const GEPOperator * GEP,unsigned Depth,const Query & Q)203306f32e7eSjoerg static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
203406f32e7eSjoerg                               const Query &Q) {
203506f32e7eSjoerg   const Function *F = nullptr;
203606f32e7eSjoerg   if (const Instruction *I = dyn_cast<Instruction>(GEP))
203706f32e7eSjoerg     F = I->getFunction();
203806f32e7eSjoerg 
203906f32e7eSjoerg   if (!GEP->isInBounds() ||
204006f32e7eSjoerg       NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
204106f32e7eSjoerg     return false;
204206f32e7eSjoerg 
204306f32e7eSjoerg   // FIXME: Support vector-GEPs.
204406f32e7eSjoerg   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
204506f32e7eSjoerg 
204606f32e7eSjoerg   // If the base pointer is non-null, we cannot walk to a null address with an
204706f32e7eSjoerg   // inbounds GEP in address space zero.
204806f32e7eSjoerg   if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
204906f32e7eSjoerg     return true;
205006f32e7eSjoerg 
205106f32e7eSjoerg   // Walk the GEP operands and see if any operand introduces a non-zero offset.
205206f32e7eSjoerg   // If so, then the GEP cannot produce a null pointer, as doing so would
205306f32e7eSjoerg   // inherently violate the inbounds contract within address space zero.
205406f32e7eSjoerg   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
205506f32e7eSjoerg        GTI != GTE; ++GTI) {
205606f32e7eSjoerg     // Struct types are easy -- they must always be indexed by a constant.
205706f32e7eSjoerg     if (StructType *STy = GTI.getStructTypeOrNull()) {
205806f32e7eSjoerg       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
205906f32e7eSjoerg       unsigned ElementIdx = OpC->getZExtValue();
206006f32e7eSjoerg       const StructLayout *SL = Q.DL.getStructLayout(STy);
206106f32e7eSjoerg       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
206206f32e7eSjoerg       if (ElementOffset > 0)
206306f32e7eSjoerg         return true;
206406f32e7eSjoerg       continue;
206506f32e7eSjoerg     }
206606f32e7eSjoerg 
206706f32e7eSjoerg     // If we have a zero-sized type, the index doesn't matter. Keep looping.
2068*da58b97aSjoerg     if (Q.DL.getTypeAllocSize(GTI.getIndexedType()).getKnownMinSize() == 0)
206906f32e7eSjoerg       continue;
207006f32e7eSjoerg 
207106f32e7eSjoerg     // Fast path the constant operand case both for efficiency and so we don't
207206f32e7eSjoerg     // increment Depth when just zipping down an all-constant GEP.
207306f32e7eSjoerg     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
207406f32e7eSjoerg       if (!OpC->isZero())
207506f32e7eSjoerg         return true;
207606f32e7eSjoerg       continue;
207706f32e7eSjoerg     }
207806f32e7eSjoerg 
207906f32e7eSjoerg     // We post-increment Depth here because while isKnownNonZero increments it
208006f32e7eSjoerg     // as well, when we pop back up that increment won't persist. We don't want
208106f32e7eSjoerg     // to recurse 10k times just because we have 10k GEP operands. We don't
208206f32e7eSjoerg     // bail completely out because we want to handle constant GEPs regardless
208306f32e7eSjoerg     // of depth.
2084*da58b97aSjoerg     if (Depth++ >= MaxAnalysisRecursionDepth)
208506f32e7eSjoerg       continue;
208606f32e7eSjoerg 
208706f32e7eSjoerg     if (isKnownNonZero(GTI.getOperand(), Depth, Q))
208806f32e7eSjoerg       return true;
208906f32e7eSjoerg   }
209006f32e7eSjoerg 
209106f32e7eSjoerg   return false;
209206f32e7eSjoerg }
209306f32e7eSjoerg 
isKnownNonNullFromDominatingCondition(const Value * V,const Instruction * CtxI,const DominatorTree * DT)209406f32e7eSjoerg static bool isKnownNonNullFromDominatingCondition(const Value *V,
209506f32e7eSjoerg                                                   const Instruction *CtxI,
209606f32e7eSjoerg                                                   const DominatorTree *DT) {
2097*da58b97aSjoerg   if (isa<Constant>(V))
2098*da58b97aSjoerg     return false;
209906f32e7eSjoerg 
210006f32e7eSjoerg   if (!CtxI || !DT)
210106f32e7eSjoerg     return false;
210206f32e7eSjoerg 
210306f32e7eSjoerg   unsigned NumUsesExplored = 0;
210406f32e7eSjoerg   for (auto *U : V->users()) {
210506f32e7eSjoerg     // Avoid massive lists
210606f32e7eSjoerg     if (NumUsesExplored >= DomConditionsMaxUses)
210706f32e7eSjoerg       break;
210806f32e7eSjoerg     NumUsesExplored++;
210906f32e7eSjoerg 
211006f32e7eSjoerg     // If the value is used as an argument to a call or invoke, then argument
211106f32e7eSjoerg     // attributes may provide an answer about null-ness.
2112*da58b97aSjoerg     if (const auto *CB = dyn_cast<CallBase>(U))
2113*da58b97aSjoerg       if (auto *CalledFunc = CB->getCalledFunction())
211406f32e7eSjoerg         for (const Argument &Arg : CalledFunc->args())
2115*da58b97aSjoerg           if (CB->getArgOperand(Arg.getArgNo()) == V &&
2116*da58b97aSjoerg               Arg.hasNonNullAttr(/* AllowUndefOrPoison */ false) &&
2117*da58b97aSjoerg               DT->dominates(CB, CtxI))
211806f32e7eSjoerg             return true;
211906f32e7eSjoerg 
2120*da58b97aSjoerg     // If the value is used as a load/store, then the pointer must be non null.
2121*da58b97aSjoerg     if (V == getLoadStorePointerOperand(U)) {
2122*da58b97aSjoerg       const Instruction *I = cast<Instruction>(U);
2123*da58b97aSjoerg       if (!NullPointerIsDefined(I->getFunction(),
2124*da58b97aSjoerg                                 V->getType()->getPointerAddressSpace()) &&
2125*da58b97aSjoerg           DT->dominates(I, CtxI))
2126*da58b97aSjoerg         return true;
2127*da58b97aSjoerg     }
2128*da58b97aSjoerg 
212906f32e7eSjoerg     // Consider only compare instructions uniquely controlling a branch
2130*da58b97aSjoerg     Value *RHS;
213106f32e7eSjoerg     CmpInst::Predicate Pred;
2132*da58b97aSjoerg     if (!match(U, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2133*da58b97aSjoerg       continue;
2134*da58b97aSjoerg 
2135*da58b97aSjoerg     bool NonNullIfTrue;
2136*da58b97aSjoerg     if (cmpExcludesZero(Pred, RHS))
2137*da58b97aSjoerg       NonNullIfTrue = true;
2138*da58b97aSjoerg     else if (cmpExcludesZero(CmpInst::getInversePredicate(Pred), RHS))
2139*da58b97aSjoerg       NonNullIfTrue = false;
2140*da58b97aSjoerg     else
214106f32e7eSjoerg       continue;
214206f32e7eSjoerg 
214306f32e7eSjoerg     SmallVector<const User *, 4> WorkList;
214406f32e7eSjoerg     SmallPtrSet<const User *, 4> Visited;
214506f32e7eSjoerg     for (auto *CmpU : U->users()) {
214606f32e7eSjoerg       assert(WorkList.empty() && "Should be!");
214706f32e7eSjoerg       if (Visited.insert(CmpU).second)
214806f32e7eSjoerg         WorkList.push_back(CmpU);
214906f32e7eSjoerg 
215006f32e7eSjoerg       while (!WorkList.empty()) {
215106f32e7eSjoerg         auto *Curr = WorkList.pop_back_val();
215206f32e7eSjoerg 
215306f32e7eSjoerg         // If a user is an AND, add all its users to the work list. We only
215406f32e7eSjoerg         // propagate "pred != null" condition through AND because it is only
215506f32e7eSjoerg         // correct to assume that all conditions of AND are met in true branch.
215606f32e7eSjoerg         // TODO: Support similar logic of OR and EQ predicate?
2157*da58b97aSjoerg         if (NonNullIfTrue)
2158*da58b97aSjoerg           if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
2159*da58b97aSjoerg             for (auto *CurrU : Curr->users())
2160*da58b97aSjoerg               if (Visited.insert(CurrU).second)
2161*da58b97aSjoerg                 WorkList.push_back(CurrU);
216206f32e7eSjoerg             continue;
216306f32e7eSjoerg           }
216406f32e7eSjoerg 
216506f32e7eSjoerg         if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
216606f32e7eSjoerg           assert(BI->isConditional() && "uses a comparison!");
216706f32e7eSjoerg 
216806f32e7eSjoerg           BasicBlock *NonNullSuccessor =
2169*da58b97aSjoerg               BI->getSuccessor(NonNullIfTrue ? 0 : 1);
217006f32e7eSjoerg           BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
217106f32e7eSjoerg           if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
217206f32e7eSjoerg             return true;
2173*da58b97aSjoerg         } else if (NonNullIfTrue && isGuard(Curr) &&
217406f32e7eSjoerg                    DT->dominates(cast<Instruction>(Curr), CtxI)) {
217506f32e7eSjoerg           return true;
217606f32e7eSjoerg         }
217706f32e7eSjoerg       }
217806f32e7eSjoerg     }
217906f32e7eSjoerg   }
218006f32e7eSjoerg 
218106f32e7eSjoerg   return false;
218206f32e7eSjoerg }
218306f32e7eSjoerg 
218406f32e7eSjoerg /// Does the 'Range' metadata (which must be a valid MD_range operand list)
218506f32e7eSjoerg /// ensure that the value it's attached to is never Value?  'RangeType' is
218606f32e7eSjoerg /// is the type of the value described by the range.
rangeMetadataExcludesValue(const MDNode * Ranges,const APInt & Value)218706f32e7eSjoerg static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
218806f32e7eSjoerg   const unsigned NumRanges = Ranges->getNumOperands() / 2;
218906f32e7eSjoerg   assert(NumRanges >= 1);
219006f32e7eSjoerg   for (unsigned i = 0; i < NumRanges; ++i) {
219106f32e7eSjoerg     ConstantInt *Lower =
219206f32e7eSjoerg         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
219306f32e7eSjoerg     ConstantInt *Upper =
219406f32e7eSjoerg         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
219506f32e7eSjoerg     ConstantRange Range(Lower->getValue(), Upper->getValue());
219606f32e7eSjoerg     if (Range.contains(Value))
219706f32e7eSjoerg       return false;
219806f32e7eSjoerg   }
219906f32e7eSjoerg   return true;
220006f32e7eSjoerg }
220106f32e7eSjoerg 
2202*da58b97aSjoerg /// Try to detect a recurrence that monotonically increases/decreases from a
2203*da58b97aSjoerg /// non-zero starting value. These are common as induction variables.
isNonZeroRecurrence(const PHINode * PN)2204*da58b97aSjoerg static bool isNonZeroRecurrence(const PHINode *PN) {
2205*da58b97aSjoerg   BinaryOperator *BO = nullptr;
2206*da58b97aSjoerg   Value *Start = nullptr, *Step = nullptr;
2207*da58b97aSjoerg   const APInt *StartC, *StepC;
2208*da58b97aSjoerg   if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
2209*da58b97aSjoerg       !match(Start, m_APInt(StartC)) || StartC->isNullValue())
2210*da58b97aSjoerg     return false;
2211*da58b97aSjoerg 
2212*da58b97aSjoerg   switch (BO->getOpcode()) {
2213*da58b97aSjoerg   case Instruction::Add:
2214*da58b97aSjoerg     // Starting from non-zero and stepping away from zero can never wrap back
2215*da58b97aSjoerg     // to zero.
2216*da58b97aSjoerg     return BO->hasNoUnsignedWrap() ||
2217*da58b97aSjoerg            (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
2218*da58b97aSjoerg             StartC->isNegative() == StepC->isNegative());
2219*da58b97aSjoerg   case Instruction::Mul:
2220*da58b97aSjoerg     return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
2221*da58b97aSjoerg            match(Step, m_APInt(StepC)) && !StepC->isNullValue();
2222*da58b97aSjoerg   case Instruction::Shl:
2223*da58b97aSjoerg     return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
2224*da58b97aSjoerg   case Instruction::AShr:
2225*da58b97aSjoerg   case Instruction::LShr:
2226*da58b97aSjoerg     return BO->isExact();
2227*da58b97aSjoerg   default:
2228*da58b97aSjoerg     return false;
2229*da58b97aSjoerg   }
2230*da58b97aSjoerg }
2231*da58b97aSjoerg 
223206f32e7eSjoerg /// Return true if the given value is known to be non-zero when defined. For
2233*da58b97aSjoerg /// vectors, return true if every demanded element is known to be non-zero when
223406f32e7eSjoerg /// defined. For pointers, if the context instruction and dominator tree are
223506f32e7eSjoerg /// specified, perform context-sensitive analysis and return true if the
223606f32e7eSjoerg /// pointer couldn't possibly be null at the specified instruction.
223706f32e7eSjoerg /// Supports values with integer or pointer type and vectors of integers.
isKnownNonZero(const Value * V,const APInt & DemandedElts,unsigned Depth,const Query & Q)2238*da58b97aSjoerg bool isKnownNonZero(const Value *V, const APInt &DemandedElts, unsigned Depth,
2239*da58b97aSjoerg                     const Query &Q) {
2240*da58b97aSjoerg   // FIXME: We currently have no way to represent the DemandedElts of a scalable
2241*da58b97aSjoerg   // vector
2242*da58b97aSjoerg   if (isa<ScalableVectorType>(V->getType()))
2243*da58b97aSjoerg     return false;
2244*da58b97aSjoerg 
224506f32e7eSjoerg   if (auto *C = dyn_cast<Constant>(V)) {
224606f32e7eSjoerg     if (C->isNullValue())
224706f32e7eSjoerg       return false;
224806f32e7eSjoerg     if (isa<ConstantInt>(C))
224906f32e7eSjoerg       // Must be non-zero due to null test above.
225006f32e7eSjoerg       return true;
225106f32e7eSjoerg 
225206f32e7eSjoerg     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
225306f32e7eSjoerg       // See the comment for IntToPtr/PtrToInt instructions below.
225406f32e7eSjoerg       if (CE->getOpcode() == Instruction::IntToPtr ||
225506f32e7eSjoerg           CE->getOpcode() == Instruction::PtrToInt)
2256*da58b97aSjoerg         if (Q.DL.getTypeSizeInBits(CE->getOperand(0)->getType())
2257*da58b97aSjoerg                 .getFixedSize() <=
2258*da58b97aSjoerg             Q.DL.getTypeSizeInBits(CE->getType()).getFixedSize())
225906f32e7eSjoerg           return isKnownNonZero(CE->getOperand(0), Depth, Q);
226006f32e7eSjoerg     }
226106f32e7eSjoerg 
226206f32e7eSjoerg     // For constant vectors, check that all elements are undefined or known
226306f32e7eSjoerg     // non-zero to determine that the whole vector is known non-zero.
2264*da58b97aSjoerg     if (auto *VecTy = dyn_cast<FixedVectorType>(C->getType())) {
226506f32e7eSjoerg       for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2266*da58b97aSjoerg         if (!DemandedElts[i])
2267*da58b97aSjoerg           continue;
226806f32e7eSjoerg         Constant *Elt = C->getAggregateElement(i);
226906f32e7eSjoerg         if (!Elt || Elt->isNullValue())
227006f32e7eSjoerg           return false;
227106f32e7eSjoerg         if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
227206f32e7eSjoerg           return false;
227306f32e7eSjoerg       }
227406f32e7eSjoerg       return true;
227506f32e7eSjoerg     }
227606f32e7eSjoerg 
227706f32e7eSjoerg     // A global variable in address space 0 is non null unless extern weak
227806f32e7eSjoerg     // or an absolute symbol reference. Other address spaces may have null as a
227906f32e7eSjoerg     // valid address for a global, so we can't assume anything.
228006f32e7eSjoerg     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
228106f32e7eSjoerg       if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
228206f32e7eSjoerg           GV->getType()->getAddressSpace() == 0)
228306f32e7eSjoerg         return true;
228406f32e7eSjoerg     } else
228506f32e7eSjoerg       return false;
228606f32e7eSjoerg   }
228706f32e7eSjoerg 
228806f32e7eSjoerg   if (auto *I = dyn_cast<Instruction>(V)) {
228906f32e7eSjoerg     if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
229006f32e7eSjoerg       // If the possible ranges don't contain zero, then the value is
229106f32e7eSjoerg       // definitely non-zero.
229206f32e7eSjoerg       if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
229306f32e7eSjoerg         const APInt ZeroValue(Ty->getBitWidth(), 0);
229406f32e7eSjoerg         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
229506f32e7eSjoerg           return true;
229606f32e7eSjoerg       }
229706f32e7eSjoerg     }
229806f32e7eSjoerg   }
229906f32e7eSjoerg 
2300*da58b97aSjoerg   if (isKnownNonZeroFromAssume(V, Q))
2301*da58b97aSjoerg     return true;
2302*da58b97aSjoerg 
230306f32e7eSjoerg   // Some of the tests below are recursive, so bail out if we hit the limit.
2304*da58b97aSjoerg   if (Depth++ >= MaxAnalysisRecursionDepth)
230506f32e7eSjoerg     return false;
230606f32e7eSjoerg 
230706f32e7eSjoerg   // Check for pointer simplifications.
2308*da58b97aSjoerg 
2309*da58b97aSjoerg   if (PointerType *PtrTy = dyn_cast<PointerType>(V->getType())) {
231006f32e7eSjoerg     // Alloca never returns null, malloc might.
231106f32e7eSjoerg     if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
231206f32e7eSjoerg       return true;
231306f32e7eSjoerg 
2314*da58b97aSjoerg     // A byval, inalloca may not be null in a non-default addres space. A
2315*da58b97aSjoerg     // nonnull argument is assumed never 0.
2316*da58b97aSjoerg     if (const Argument *A = dyn_cast<Argument>(V)) {
2317*da58b97aSjoerg       if (((A->hasPassPointeeByValueCopyAttr() &&
2318*da58b97aSjoerg             !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
2319*da58b97aSjoerg            A->hasNonNullAttr()))
232006f32e7eSjoerg         return true;
2321*da58b97aSjoerg     }
232206f32e7eSjoerg 
232306f32e7eSjoerg     // A Load tagged with nonnull metadata is never null.
232406f32e7eSjoerg     if (const LoadInst *LI = dyn_cast<LoadInst>(V))
232506f32e7eSjoerg       if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
232606f32e7eSjoerg         return true;
232706f32e7eSjoerg 
232806f32e7eSjoerg     if (const auto *Call = dyn_cast<CallBase>(V)) {
232906f32e7eSjoerg       if (Call->isReturnNonNull())
233006f32e7eSjoerg         return true;
233106f32e7eSjoerg       if (const auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
233206f32e7eSjoerg         return isKnownNonZero(RP, Depth, Q);
233306f32e7eSjoerg     }
233406f32e7eSjoerg   }
233506f32e7eSjoerg 
233606f32e7eSjoerg   if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
233706f32e7eSjoerg     return true;
233806f32e7eSjoerg 
2339*da58b97aSjoerg   // Check for recursive pointer simplifications.
2340*da58b97aSjoerg   if (V->getType()->isPointerTy()) {
234106f32e7eSjoerg     // Look through bitcast operations, GEPs, and int2ptr instructions as they
234206f32e7eSjoerg     // do not alter the value, or at least not the nullness property of the
234306f32e7eSjoerg     // value, e.g., int2ptr is allowed to zero/sign extend the value.
234406f32e7eSjoerg     //
234506f32e7eSjoerg     // Note that we have to take special care to avoid looking through
234606f32e7eSjoerg     // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
234706f32e7eSjoerg     // as casts that can alter the value, e.g., AddrSpaceCasts.
234806f32e7eSjoerg     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
2349*da58b97aSjoerg       return isGEPKnownNonNull(GEP, Depth, Q);
235006f32e7eSjoerg 
235106f32e7eSjoerg     if (auto *BCO = dyn_cast<BitCastOperator>(V))
235206f32e7eSjoerg       return isKnownNonZero(BCO->getOperand(0), Depth, Q);
235306f32e7eSjoerg 
235406f32e7eSjoerg     if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2355*da58b97aSjoerg       if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()).getFixedSize() <=
2356*da58b97aSjoerg           Q.DL.getTypeSizeInBits(I2P->getDestTy()).getFixedSize())
235706f32e7eSjoerg         return isKnownNonZero(I2P->getOperand(0), Depth, Q);
235806f32e7eSjoerg   }
235906f32e7eSjoerg 
236006f32e7eSjoerg   // Similar to int2ptr above, we can look through ptr2int here if the cast
236106f32e7eSjoerg   // is a no-op or an extend and not a truncate.
236206f32e7eSjoerg   if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2363*da58b97aSjoerg     if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()).getFixedSize() <=
2364*da58b97aSjoerg         Q.DL.getTypeSizeInBits(P2I->getDestTy()).getFixedSize())
236506f32e7eSjoerg       return isKnownNonZero(P2I->getOperand(0), Depth, Q);
236606f32e7eSjoerg 
236706f32e7eSjoerg   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
236806f32e7eSjoerg 
236906f32e7eSjoerg   // X | Y != 0 if X != 0 or Y != 0.
237006f32e7eSjoerg   Value *X = nullptr, *Y = nullptr;
237106f32e7eSjoerg   if (match(V, m_Or(m_Value(X), m_Value(Y))))
2372*da58b97aSjoerg     return isKnownNonZero(X, DemandedElts, Depth, Q) ||
2373*da58b97aSjoerg            isKnownNonZero(Y, DemandedElts, Depth, Q);
237406f32e7eSjoerg 
237506f32e7eSjoerg   // ext X != 0 if X != 0.
237606f32e7eSjoerg   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
237706f32e7eSjoerg     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
237806f32e7eSjoerg 
237906f32e7eSjoerg   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
238006f32e7eSjoerg   // if the lowest bit is shifted off the end.
238106f32e7eSjoerg   if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
238206f32e7eSjoerg     // shl nuw can't remove any non-zero bits.
238306f32e7eSjoerg     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
238406f32e7eSjoerg     if (Q.IIQ.hasNoUnsignedWrap(BO))
238506f32e7eSjoerg       return isKnownNonZero(X, Depth, Q);
238606f32e7eSjoerg 
238706f32e7eSjoerg     KnownBits Known(BitWidth);
2388*da58b97aSjoerg     computeKnownBits(X, DemandedElts, Known, Depth, Q);
238906f32e7eSjoerg     if (Known.One[0])
239006f32e7eSjoerg       return true;
239106f32e7eSjoerg   }
239206f32e7eSjoerg   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
239306f32e7eSjoerg   // defined if the sign bit is shifted off the end.
239406f32e7eSjoerg   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
239506f32e7eSjoerg     // shr exact can only shift out zero bits.
239606f32e7eSjoerg     const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
239706f32e7eSjoerg     if (BO->isExact())
239806f32e7eSjoerg       return isKnownNonZero(X, Depth, Q);
239906f32e7eSjoerg 
2400*da58b97aSjoerg     KnownBits Known = computeKnownBits(X, DemandedElts, Depth, Q);
240106f32e7eSjoerg     if (Known.isNegative())
240206f32e7eSjoerg       return true;
240306f32e7eSjoerg 
240406f32e7eSjoerg     // If the shifter operand is a constant, and all of the bits shifted
240506f32e7eSjoerg     // out are known to be zero, and X is known non-zero then at least one
240606f32e7eSjoerg     // non-zero bit must remain.
240706f32e7eSjoerg     if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
240806f32e7eSjoerg       auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
240906f32e7eSjoerg       // Is there a known one in the portion not shifted out?
241006f32e7eSjoerg       if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
241106f32e7eSjoerg         return true;
241206f32e7eSjoerg       // Are all the bits to be shifted out known zero?
241306f32e7eSjoerg       if (Known.countMinTrailingZeros() >= ShiftVal)
2414*da58b97aSjoerg         return isKnownNonZero(X, DemandedElts, Depth, Q);
241506f32e7eSjoerg     }
241606f32e7eSjoerg   }
241706f32e7eSjoerg   // div exact can only produce a zero if the dividend is zero.
241806f32e7eSjoerg   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
2419*da58b97aSjoerg     return isKnownNonZero(X, DemandedElts, Depth, Q);
242006f32e7eSjoerg   }
242106f32e7eSjoerg   // X + Y.
242206f32e7eSjoerg   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2423*da58b97aSjoerg     KnownBits XKnown = computeKnownBits(X, DemandedElts, Depth, Q);
2424*da58b97aSjoerg     KnownBits YKnown = computeKnownBits(Y, DemandedElts, Depth, Q);
242506f32e7eSjoerg 
242606f32e7eSjoerg     // If X and Y are both non-negative (as signed values) then their sum is not
242706f32e7eSjoerg     // zero unless both X and Y are zero.
242806f32e7eSjoerg     if (XKnown.isNonNegative() && YKnown.isNonNegative())
2429*da58b97aSjoerg       if (isKnownNonZero(X, DemandedElts, Depth, Q) ||
2430*da58b97aSjoerg           isKnownNonZero(Y, DemandedElts, Depth, Q))
243106f32e7eSjoerg         return true;
243206f32e7eSjoerg 
243306f32e7eSjoerg     // If X and Y are both negative (as signed values) then their sum is not
243406f32e7eSjoerg     // zero unless both X and Y equal INT_MIN.
243506f32e7eSjoerg     if (XKnown.isNegative() && YKnown.isNegative()) {
243606f32e7eSjoerg       APInt Mask = APInt::getSignedMaxValue(BitWidth);
243706f32e7eSjoerg       // The sign bit of X is set.  If some other bit is set then X is not equal
243806f32e7eSjoerg       // to INT_MIN.
243906f32e7eSjoerg       if (XKnown.One.intersects(Mask))
244006f32e7eSjoerg         return true;
244106f32e7eSjoerg       // The sign bit of Y is set.  If some other bit is set then Y is not equal
244206f32e7eSjoerg       // to INT_MIN.
244306f32e7eSjoerg       if (YKnown.One.intersects(Mask))
244406f32e7eSjoerg         return true;
244506f32e7eSjoerg     }
244606f32e7eSjoerg 
244706f32e7eSjoerg     // The sum of a non-negative number and a power of two is not zero.
244806f32e7eSjoerg     if (XKnown.isNonNegative() &&
244906f32e7eSjoerg         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
245006f32e7eSjoerg       return true;
245106f32e7eSjoerg     if (YKnown.isNonNegative() &&
245206f32e7eSjoerg         isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
245306f32e7eSjoerg       return true;
245406f32e7eSjoerg   }
245506f32e7eSjoerg   // X * Y.
245606f32e7eSjoerg   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
245706f32e7eSjoerg     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
245806f32e7eSjoerg     // If X and Y are non-zero then so is X * Y as long as the multiplication
245906f32e7eSjoerg     // does not overflow.
246006f32e7eSjoerg     if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
2461*da58b97aSjoerg         isKnownNonZero(X, DemandedElts, Depth, Q) &&
2462*da58b97aSjoerg         isKnownNonZero(Y, DemandedElts, Depth, Q))
246306f32e7eSjoerg       return true;
246406f32e7eSjoerg   }
246506f32e7eSjoerg   // (C ? X : Y) != 0 if X != 0 and Y != 0.
246606f32e7eSjoerg   else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
2467*da58b97aSjoerg     if (isKnownNonZero(SI->getTrueValue(), DemandedElts, Depth, Q) &&
2468*da58b97aSjoerg         isKnownNonZero(SI->getFalseValue(), DemandedElts, Depth, Q))
246906f32e7eSjoerg       return true;
247006f32e7eSjoerg   }
247106f32e7eSjoerg   // PHI
247206f32e7eSjoerg   else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
2473*da58b97aSjoerg     if (Q.IIQ.UseInstrInfo && isNonZeroRecurrence(PN))
247406f32e7eSjoerg       return true;
2475*da58b97aSjoerg 
2476*da58b97aSjoerg     // Check if all incoming values are non-zero using recursion.
2477*da58b97aSjoerg     Query RecQ = Q;
2478*da58b97aSjoerg     unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2479*da58b97aSjoerg     return llvm::all_of(PN->operands(), [&](const Use &U) {
2480*da58b97aSjoerg       if (U.get() == PN)
2481*da58b97aSjoerg         return true;
2482*da58b97aSjoerg       RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2483*da58b97aSjoerg       return isKnownNonZero(U.get(), DemandedElts, NewDepth, RecQ);
248406f32e7eSjoerg     });
2485*da58b97aSjoerg   }
2486*da58b97aSjoerg   // ExtractElement
2487*da58b97aSjoerg   else if (const auto *EEI = dyn_cast<ExtractElementInst>(V)) {
2488*da58b97aSjoerg     const Value *Vec = EEI->getVectorOperand();
2489*da58b97aSjoerg     const Value *Idx = EEI->getIndexOperand();
2490*da58b97aSjoerg     auto *CIdx = dyn_cast<ConstantInt>(Idx);
2491*da58b97aSjoerg     if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
2492*da58b97aSjoerg       unsigned NumElts = VecTy->getNumElements();
2493*da58b97aSjoerg       APInt DemandedVecElts = APInt::getAllOnesValue(NumElts);
2494*da58b97aSjoerg       if (CIdx && CIdx->getValue().ult(NumElts))
2495*da58b97aSjoerg         DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2496*da58b97aSjoerg       return isKnownNonZero(Vec, DemandedVecElts, Depth, Q);
2497*da58b97aSjoerg     }
2498*da58b97aSjoerg   }
2499*da58b97aSjoerg   // Freeze
2500*da58b97aSjoerg   else if (const FreezeInst *FI = dyn_cast<FreezeInst>(V)) {
2501*da58b97aSjoerg     auto *Op = FI->getOperand(0);
2502*da58b97aSjoerg     if (isKnownNonZero(Op, Depth, Q) &&
2503*da58b97aSjoerg         isGuaranteedNotToBePoison(Op, Q.AC, Q.CxtI, Q.DT, Depth))
250406f32e7eSjoerg       return true;
250506f32e7eSjoerg   }
250606f32e7eSjoerg 
250706f32e7eSjoerg   KnownBits Known(BitWidth);
2508*da58b97aSjoerg   computeKnownBits(V, DemandedElts, Known, Depth, Q);
250906f32e7eSjoerg   return Known.One != 0;
251006f32e7eSjoerg }
251106f32e7eSjoerg 
isKnownNonZero(const Value * V,unsigned Depth,const Query & Q)2512*da58b97aSjoerg bool isKnownNonZero(const Value* V, unsigned Depth, const Query& Q) {
2513*da58b97aSjoerg   // FIXME: We currently have no way to represent the DemandedElts of a scalable
2514*da58b97aSjoerg   // vector
2515*da58b97aSjoerg   if (isa<ScalableVectorType>(V->getType()))
2516*da58b97aSjoerg     return false;
2517*da58b97aSjoerg 
2518*da58b97aSjoerg   auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
2519*da58b97aSjoerg   APInt DemandedElts =
2520*da58b97aSjoerg       FVTy ? APInt::getAllOnesValue(FVTy->getNumElements()) : APInt(1, 1);
2521*da58b97aSjoerg   return isKnownNonZero(V, DemandedElts, Depth, Q);
2522*da58b97aSjoerg }
2523*da58b97aSjoerg 
2524*da58b97aSjoerg /// If the pair of operators are the same invertible function, return the
2525*da58b97aSjoerg /// the operands of the function corresponding to each input. Otherwise,
2526*da58b97aSjoerg /// return None.  An invertible function is one that is 1-to-1 and maps
2527*da58b97aSjoerg /// every input value to exactly one output value.  This is equivalent to
2528*da58b97aSjoerg /// saying that Op1 and Op2 are equal exactly when the specified pair of
2529*da58b97aSjoerg /// operands are equal, (except that Op1 and Op2 may be poison more often.)
2530*da58b97aSjoerg static Optional<std::pair<Value*, Value*>>
getInvertibleOperands(const Operator * Op1,const Operator * Op2)2531*da58b97aSjoerg getInvertibleOperands(const Operator *Op1,
2532*da58b97aSjoerg                       const Operator *Op2) {
2533*da58b97aSjoerg   if (Op1->getOpcode() != Op2->getOpcode())
2534*da58b97aSjoerg     return None;
2535*da58b97aSjoerg 
2536*da58b97aSjoerg   auto getOperands = [&](unsigned OpNum) -> auto {
2537*da58b97aSjoerg     return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
2538*da58b97aSjoerg   };
2539*da58b97aSjoerg 
2540*da58b97aSjoerg   switch (Op1->getOpcode()) {
2541*da58b97aSjoerg   default:
2542*da58b97aSjoerg     break;
2543*da58b97aSjoerg   case Instruction::Add:
2544*da58b97aSjoerg   case Instruction::Sub:
2545*da58b97aSjoerg     if (Op1->getOperand(0) == Op2->getOperand(0))
2546*da58b97aSjoerg       return getOperands(1);
2547*da58b97aSjoerg     if (Op1->getOperand(1) == Op2->getOperand(1))
2548*da58b97aSjoerg       return getOperands(0);
2549*da58b97aSjoerg     break;
2550*da58b97aSjoerg   case Instruction::Mul: {
2551*da58b97aSjoerg     // invertible if A * B == (A * B) mod 2^N where A, and B are integers
2552*da58b97aSjoerg     // and N is the bitwdith.  The nsw case is non-obvious, but proven by
2553*da58b97aSjoerg     // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
2554*da58b97aSjoerg     auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2555*da58b97aSjoerg     auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2556*da58b97aSjoerg     if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2557*da58b97aSjoerg         (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2558*da58b97aSjoerg       break;
2559*da58b97aSjoerg 
2560*da58b97aSjoerg     // Assume operand order has been canonicalized
2561*da58b97aSjoerg     if (Op1->getOperand(1) == Op2->getOperand(1) &&
2562*da58b97aSjoerg         isa<ConstantInt>(Op1->getOperand(1)) &&
2563*da58b97aSjoerg         !cast<ConstantInt>(Op1->getOperand(1))->isZero())
2564*da58b97aSjoerg       return getOperands(0);
2565*da58b97aSjoerg     break;
2566*da58b97aSjoerg   }
2567*da58b97aSjoerg   case Instruction::Shl: {
2568*da58b97aSjoerg     // Same as multiplies, with the difference that we don't need to check
2569*da58b97aSjoerg     // for a non-zero multiply. Shifts always multiply by non-zero.
2570*da58b97aSjoerg     auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2571*da58b97aSjoerg     auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2572*da58b97aSjoerg     if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2573*da58b97aSjoerg         (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2574*da58b97aSjoerg       break;
2575*da58b97aSjoerg 
2576*da58b97aSjoerg     if (Op1->getOperand(1) == Op2->getOperand(1))
2577*da58b97aSjoerg       return getOperands(0);
2578*da58b97aSjoerg     break;
2579*da58b97aSjoerg   }
2580*da58b97aSjoerg   case Instruction::AShr:
2581*da58b97aSjoerg   case Instruction::LShr: {
2582*da58b97aSjoerg     auto *PEO1 = cast<PossiblyExactOperator>(Op1);
2583*da58b97aSjoerg     auto *PEO2 = cast<PossiblyExactOperator>(Op2);
2584*da58b97aSjoerg     if (!PEO1->isExact() || !PEO2->isExact())
2585*da58b97aSjoerg       break;
2586*da58b97aSjoerg 
2587*da58b97aSjoerg     if (Op1->getOperand(1) == Op2->getOperand(1))
2588*da58b97aSjoerg       return getOperands(0);
2589*da58b97aSjoerg     break;
2590*da58b97aSjoerg   }
2591*da58b97aSjoerg   case Instruction::SExt:
2592*da58b97aSjoerg   case Instruction::ZExt:
2593*da58b97aSjoerg     if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
2594*da58b97aSjoerg       return getOperands(0);
2595*da58b97aSjoerg     break;
2596*da58b97aSjoerg   case Instruction::PHI: {
2597*da58b97aSjoerg     const PHINode *PN1 = cast<PHINode>(Op1);
2598*da58b97aSjoerg     const PHINode *PN2 = cast<PHINode>(Op2);
2599*da58b97aSjoerg 
2600*da58b97aSjoerg     // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
2601*da58b97aSjoerg     // are a single invertible function of the start values? Note that repeated
2602*da58b97aSjoerg     // application of an invertible function is also invertible
2603*da58b97aSjoerg     BinaryOperator *BO1 = nullptr;
2604*da58b97aSjoerg     Value *Start1 = nullptr, *Step1 = nullptr;
2605*da58b97aSjoerg     BinaryOperator *BO2 = nullptr;
2606*da58b97aSjoerg     Value *Start2 = nullptr, *Step2 = nullptr;
2607*da58b97aSjoerg     if (PN1->getParent() != PN2->getParent() ||
2608*da58b97aSjoerg         !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
2609*da58b97aSjoerg         !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
2610*da58b97aSjoerg       break;
2611*da58b97aSjoerg 
2612*da58b97aSjoerg     auto Values = getInvertibleOperands(cast<Operator>(BO1),
2613*da58b97aSjoerg                                         cast<Operator>(BO2));
2614*da58b97aSjoerg     if (!Values)
2615*da58b97aSjoerg        break;
2616*da58b97aSjoerg 
2617*da58b97aSjoerg     // We have to be careful of mutually defined recurrences here.  Ex:
2618*da58b97aSjoerg     // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
2619*da58b97aSjoerg     // * X_i = Y_i = X_(i-1) OP Y_(i-1)
2620*da58b97aSjoerg     // The invertibility of these is complicated, and not worth reasoning
2621*da58b97aSjoerg     // about (yet?).
2622*da58b97aSjoerg     if (Values->first != PN1 || Values->second != PN2)
2623*da58b97aSjoerg       break;
2624*da58b97aSjoerg 
2625*da58b97aSjoerg     return std::make_pair(Start1, Start2);
2626*da58b97aSjoerg   }
2627*da58b97aSjoerg   }
2628*da58b97aSjoerg   return None;
2629*da58b97aSjoerg }
2630*da58b97aSjoerg 
263106f32e7eSjoerg /// Return true if V2 == V1 + X, where X is known non-zero.
isAddOfNonZero(const Value * V1,const Value * V2,unsigned Depth,const Query & Q)2632*da58b97aSjoerg static bool isAddOfNonZero(const Value *V1, const Value *V2, unsigned Depth,
2633*da58b97aSjoerg                            const Query &Q) {
263406f32e7eSjoerg   const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
263506f32e7eSjoerg   if (!BO || BO->getOpcode() != Instruction::Add)
263606f32e7eSjoerg     return false;
263706f32e7eSjoerg   Value *Op = nullptr;
263806f32e7eSjoerg   if (V2 == BO->getOperand(0))
263906f32e7eSjoerg     Op = BO->getOperand(1);
264006f32e7eSjoerg   else if (V2 == BO->getOperand(1))
264106f32e7eSjoerg     Op = BO->getOperand(0);
264206f32e7eSjoerg   else
264306f32e7eSjoerg     return false;
2644*da58b97aSjoerg   return isKnownNonZero(Op, Depth + 1, Q);
2645*da58b97aSjoerg }
2646*da58b97aSjoerg 
2647*da58b97aSjoerg /// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
2648*da58b97aSjoerg /// the multiplication is nuw or nsw.
isNonEqualMul(const Value * V1,const Value * V2,unsigned Depth,const Query & Q)2649*da58b97aSjoerg static bool isNonEqualMul(const Value *V1, const Value *V2, unsigned Depth,
2650*da58b97aSjoerg                           const Query &Q) {
2651*da58b97aSjoerg   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2652*da58b97aSjoerg     const APInt *C;
2653*da58b97aSjoerg     return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
2654*da58b97aSjoerg            (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2655*da58b97aSjoerg            !C->isNullValue() && !C->isOneValue() &&
2656*da58b97aSjoerg            isKnownNonZero(V1, Depth + 1, Q);
2657*da58b97aSjoerg   }
2658*da58b97aSjoerg   return false;
2659*da58b97aSjoerg }
2660*da58b97aSjoerg 
2661*da58b97aSjoerg /// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
2662*da58b97aSjoerg /// the shift is nuw or nsw.
isNonEqualShl(const Value * V1,const Value * V2,unsigned Depth,const Query & Q)2663*da58b97aSjoerg static bool isNonEqualShl(const Value *V1, const Value *V2, unsigned Depth,
2664*da58b97aSjoerg                           const Query &Q) {
2665*da58b97aSjoerg   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2666*da58b97aSjoerg     const APInt *C;
2667*da58b97aSjoerg     return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
2668*da58b97aSjoerg            (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2669*da58b97aSjoerg            !C->isNullValue() && isKnownNonZero(V1, Depth + 1, Q);
2670*da58b97aSjoerg   }
2671*da58b97aSjoerg   return false;
2672*da58b97aSjoerg }
2673*da58b97aSjoerg 
isNonEqualPHIs(const PHINode * PN1,const PHINode * PN2,unsigned Depth,const Query & Q)2674*da58b97aSjoerg static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
2675*da58b97aSjoerg                            unsigned Depth, const Query &Q) {
2676*da58b97aSjoerg   // Check two PHIs are in same block.
2677*da58b97aSjoerg   if (PN1->getParent() != PN2->getParent())
2678*da58b97aSjoerg     return false;
2679*da58b97aSjoerg 
2680*da58b97aSjoerg   SmallPtrSet<const BasicBlock *, 8> VisitedBBs;
2681*da58b97aSjoerg   bool UsedFullRecursion = false;
2682*da58b97aSjoerg   for (const BasicBlock *IncomBB : PN1->blocks()) {
2683*da58b97aSjoerg     if (!VisitedBBs.insert(IncomBB).second)
2684*da58b97aSjoerg       continue; // Don't reprocess blocks that we have dealt with already.
2685*da58b97aSjoerg     const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
2686*da58b97aSjoerg     const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
2687*da58b97aSjoerg     const APInt *C1, *C2;
2688*da58b97aSjoerg     if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
2689*da58b97aSjoerg       continue;
2690*da58b97aSjoerg 
2691*da58b97aSjoerg     // Only one pair of phi operands is allowed for full recursion.
2692*da58b97aSjoerg     if (UsedFullRecursion)
2693*da58b97aSjoerg       return false;
2694*da58b97aSjoerg 
2695*da58b97aSjoerg     Query RecQ = Q;
2696*da58b97aSjoerg     RecQ.CxtI = IncomBB->getTerminator();
2697*da58b97aSjoerg     if (!isKnownNonEqual(IV1, IV2, Depth + 1, RecQ))
2698*da58b97aSjoerg       return false;
2699*da58b97aSjoerg     UsedFullRecursion = true;
2700*da58b97aSjoerg   }
2701*da58b97aSjoerg   return true;
270206f32e7eSjoerg }
270306f32e7eSjoerg 
270406f32e7eSjoerg /// Return true if it is known that V1 != V2.
isKnownNonEqual(const Value * V1,const Value * V2,unsigned Depth,const Query & Q)2705*da58b97aSjoerg static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
2706*da58b97aSjoerg                             const Query &Q) {
270706f32e7eSjoerg   if (V1 == V2)
270806f32e7eSjoerg     return false;
270906f32e7eSjoerg   if (V1->getType() != V2->getType())
271006f32e7eSjoerg     // We can't look through casts yet.
271106f32e7eSjoerg     return false;
2712*da58b97aSjoerg 
2713*da58b97aSjoerg   if (Depth >= MaxAnalysisRecursionDepth)
2714*da58b97aSjoerg     return false;
2715*da58b97aSjoerg 
2716*da58b97aSjoerg   // See if we can recurse through (exactly one of) our operands.  This
2717*da58b97aSjoerg   // requires our operation be 1-to-1 and map every input value to exactly
2718*da58b97aSjoerg   // one output value.  Such an operation is invertible.
2719*da58b97aSjoerg   auto *O1 = dyn_cast<Operator>(V1);
2720*da58b97aSjoerg   auto *O2 = dyn_cast<Operator>(V2);
2721*da58b97aSjoerg   if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
2722*da58b97aSjoerg     if (auto Values = getInvertibleOperands(O1, O2))
2723*da58b97aSjoerg       return isKnownNonEqual(Values->first, Values->second, Depth + 1, Q);
2724*da58b97aSjoerg 
2725*da58b97aSjoerg     if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
2726*da58b97aSjoerg       const PHINode *PN2 = cast<PHINode>(V2);
2727*da58b97aSjoerg       // FIXME: This is missing a generalization to handle the case where one is
2728*da58b97aSjoerg       // a PHI and another one isn't.
2729*da58b97aSjoerg       if (isNonEqualPHIs(PN1, PN2, Depth, Q))
2730*da58b97aSjoerg         return true;
2731*da58b97aSjoerg     };
2732*da58b97aSjoerg   }
2733*da58b97aSjoerg 
2734*da58b97aSjoerg   if (isAddOfNonZero(V1, V2, Depth, Q) || isAddOfNonZero(V2, V1, Depth, Q))
2735*da58b97aSjoerg     return true;
2736*da58b97aSjoerg 
2737*da58b97aSjoerg   if (isNonEqualMul(V1, V2, Depth, Q) || isNonEqualMul(V2, V1, Depth, Q))
2738*da58b97aSjoerg     return true;
2739*da58b97aSjoerg 
2740*da58b97aSjoerg   if (isNonEqualShl(V1, V2, Depth, Q) || isNonEqualShl(V2, V1, Depth, Q))
274106f32e7eSjoerg     return true;
274206f32e7eSjoerg 
274306f32e7eSjoerg   if (V1->getType()->isIntOrIntVectorTy()) {
274406f32e7eSjoerg     // Are any known bits in V1 contradictory to known bits in V2? If V1
274506f32e7eSjoerg     // has a known zero where V2 has a known one, they must not be equal.
2746*da58b97aSjoerg     KnownBits Known1 = computeKnownBits(V1, Depth, Q);
2747*da58b97aSjoerg     KnownBits Known2 = computeKnownBits(V2, Depth, Q);
274806f32e7eSjoerg 
274906f32e7eSjoerg     if (Known1.Zero.intersects(Known2.One) ||
275006f32e7eSjoerg         Known2.Zero.intersects(Known1.One))
275106f32e7eSjoerg       return true;
275206f32e7eSjoerg   }
275306f32e7eSjoerg   return false;
275406f32e7eSjoerg }
275506f32e7eSjoerg 
275606f32e7eSjoerg /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
275706f32e7eSjoerg /// simplify operations downstream. Mask is known to be zero for bits that V
275806f32e7eSjoerg /// cannot have.
275906f32e7eSjoerg ///
276006f32e7eSjoerg /// This function is defined on values with integer type, values with pointer
276106f32e7eSjoerg /// type, and vectors of integers.  In the case
276206f32e7eSjoerg /// where V is a vector, the mask, known zero, and known one values are the
276306f32e7eSjoerg /// same width as the vector element, and the bit is set only if it is true
276406f32e7eSjoerg /// for all of the elements in the vector.
MaskedValueIsZero(const Value * V,const APInt & Mask,unsigned Depth,const Query & Q)276506f32e7eSjoerg bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
276606f32e7eSjoerg                        const Query &Q) {
276706f32e7eSjoerg   KnownBits Known(Mask.getBitWidth());
276806f32e7eSjoerg   computeKnownBits(V, Known, Depth, Q);
276906f32e7eSjoerg   return Mask.isSubsetOf(Known.Zero);
277006f32e7eSjoerg }
277106f32e7eSjoerg 
277206f32e7eSjoerg // Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
277306f32e7eSjoerg // Returns the input and lower/upper bounds.
isSignedMinMaxClamp(const Value * Select,const Value * & In,const APInt * & CLow,const APInt * & CHigh)277406f32e7eSjoerg static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
277506f32e7eSjoerg                                 const APInt *&CLow, const APInt *&CHigh) {
277606f32e7eSjoerg   assert(isa<Operator>(Select) &&
277706f32e7eSjoerg          cast<Operator>(Select)->getOpcode() == Instruction::Select &&
277806f32e7eSjoerg          "Input should be a Select!");
277906f32e7eSjoerg 
278006f32e7eSjoerg   const Value *LHS = nullptr, *RHS = nullptr;
278106f32e7eSjoerg   SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
278206f32e7eSjoerg   if (SPF != SPF_SMAX && SPF != SPF_SMIN)
278306f32e7eSjoerg     return false;
278406f32e7eSjoerg 
278506f32e7eSjoerg   if (!match(RHS, m_APInt(CLow)))
278606f32e7eSjoerg     return false;
278706f32e7eSjoerg 
278806f32e7eSjoerg   const Value *LHS2 = nullptr, *RHS2 = nullptr;
278906f32e7eSjoerg   SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
279006f32e7eSjoerg   if (getInverseMinMaxFlavor(SPF) != SPF2)
279106f32e7eSjoerg     return false;
279206f32e7eSjoerg 
279306f32e7eSjoerg   if (!match(RHS2, m_APInt(CHigh)))
279406f32e7eSjoerg     return false;
279506f32e7eSjoerg 
279606f32e7eSjoerg   if (SPF == SPF_SMIN)
279706f32e7eSjoerg     std::swap(CLow, CHigh);
279806f32e7eSjoerg 
279906f32e7eSjoerg   In = LHS2;
280006f32e7eSjoerg   return CLow->sle(*CHigh);
280106f32e7eSjoerg }
280206f32e7eSjoerg 
280306f32e7eSjoerg /// For vector constants, loop over the elements and find the constant with the
280406f32e7eSjoerg /// minimum number of sign bits. Return 0 if the value is not a vector constant
280506f32e7eSjoerg /// or if any element was not analyzed; otherwise, return the count for the
280606f32e7eSjoerg /// element with the minimum number of sign bits.
computeNumSignBitsVectorConstant(const Value * V,const APInt & DemandedElts,unsigned TyBits)280706f32e7eSjoerg static unsigned computeNumSignBitsVectorConstant(const Value *V,
2808*da58b97aSjoerg                                                  const APInt &DemandedElts,
280906f32e7eSjoerg                                                  unsigned TyBits) {
281006f32e7eSjoerg   const auto *CV = dyn_cast<Constant>(V);
2811*da58b97aSjoerg   if (!CV || !isa<FixedVectorType>(CV->getType()))
281206f32e7eSjoerg     return 0;
281306f32e7eSjoerg 
281406f32e7eSjoerg   unsigned MinSignBits = TyBits;
2815*da58b97aSjoerg   unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
281606f32e7eSjoerg   for (unsigned i = 0; i != NumElts; ++i) {
2817*da58b97aSjoerg     if (!DemandedElts[i])
2818*da58b97aSjoerg       continue;
281906f32e7eSjoerg     // If we find a non-ConstantInt, bail out.
282006f32e7eSjoerg     auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
282106f32e7eSjoerg     if (!Elt)
282206f32e7eSjoerg       return 0;
282306f32e7eSjoerg 
282406f32e7eSjoerg     MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
282506f32e7eSjoerg   }
282606f32e7eSjoerg 
282706f32e7eSjoerg   return MinSignBits;
282806f32e7eSjoerg }
282906f32e7eSjoerg 
2830*da58b97aSjoerg static unsigned ComputeNumSignBitsImpl(const Value *V,
2831*da58b97aSjoerg                                        const APInt &DemandedElts,
2832*da58b97aSjoerg                                        unsigned Depth, const Query &Q);
283306f32e7eSjoerg 
ComputeNumSignBits(const Value * V,const APInt & DemandedElts,unsigned Depth,const Query & Q)2834*da58b97aSjoerg static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
2835*da58b97aSjoerg                                    unsigned Depth, const Query &Q) {
2836*da58b97aSjoerg   unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Depth, Q);
283706f32e7eSjoerg   assert(Result > 0 && "At least one sign bit needs to be present!");
283806f32e7eSjoerg   return Result;
283906f32e7eSjoerg }
284006f32e7eSjoerg 
284106f32e7eSjoerg /// Return the number of times the sign bit of the register is replicated into
284206f32e7eSjoerg /// the other bits. We know that at least 1 bit is always equal to the sign bit
284306f32e7eSjoerg /// (itself), but other cases can give us information. For example, immediately
284406f32e7eSjoerg /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
284506f32e7eSjoerg /// other, so we return 3. For vectors, return the number of sign bits for the
2846*da58b97aSjoerg /// vector element with the minimum number of known sign bits of the demanded
2847*da58b97aSjoerg /// elements in the vector specified by DemandedElts.
ComputeNumSignBitsImpl(const Value * V,const APInt & DemandedElts,unsigned Depth,const Query & Q)2848*da58b97aSjoerg static unsigned ComputeNumSignBitsImpl(const Value *V,
2849*da58b97aSjoerg                                        const APInt &DemandedElts,
2850*da58b97aSjoerg                                        unsigned Depth, const Query &Q) {
2851*da58b97aSjoerg   Type *Ty = V->getType();
2852*da58b97aSjoerg 
2853*da58b97aSjoerg   // FIXME: We currently have no way to represent the DemandedElts of a scalable
2854*da58b97aSjoerg   // vector
2855*da58b97aSjoerg   if (isa<ScalableVectorType>(Ty))
2856*da58b97aSjoerg     return 1;
2857*da58b97aSjoerg 
2858*da58b97aSjoerg #ifndef NDEBUG
2859*da58b97aSjoerg   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2860*da58b97aSjoerg 
2861*da58b97aSjoerg   if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2862*da58b97aSjoerg     assert(
2863*da58b97aSjoerg         FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2864*da58b97aSjoerg         "DemandedElt width should equal the fixed vector number of elements");
2865*da58b97aSjoerg   } else {
2866*da58b97aSjoerg     assert(DemandedElts == APInt(1, 1) &&
2867*da58b97aSjoerg            "DemandedElt width should be 1 for scalars");
2868*da58b97aSjoerg   }
2869*da58b97aSjoerg #endif
287006f32e7eSjoerg 
287106f32e7eSjoerg   // We return the minimum number of sign bits that are guaranteed to be present
287206f32e7eSjoerg   // in V, so for undef we have to conservatively return 1.  We don't have the
287306f32e7eSjoerg   // same behavior for poison though -- that's a FIXME today.
287406f32e7eSjoerg 
2875*da58b97aSjoerg   Type *ScalarTy = Ty->getScalarType();
287606f32e7eSjoerg   unsigned TyBits = ScalarTy->isPointerTy() ?
2877*da58b97aSjoerg     Q.DL.getPointerTypeSizeInBits(ScalarTy) :
287806f32e7eSjoerg     Q.DL.getTypeSizeInBits(ScalarTy);
287906f32e7eSjoerg 
288006f32e7eSjoerg   unsigned Tmp, Tmp2;
288106f32e7eSjoerg   unsigned FirstAnswer = 1;
288206f32e7eSjoerg 
288306f32e7eSjoerg   // Note that ConstantInt is handled by the general computeKnownBits case
288406f32e7eSjoerg   // below.
288506f32e7eSjoerg 
2886*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
2887*da58b97aSjoerg     return 1;
288806f32e7eSjoerg 
288906f32e7eSjoerg   if (auto *U = dyn_cast<Operator>(V)) {
289006f32e7eSjoerg     switch (Operator::getOpcode(V)) {
289106f32e7eSjoerg     default: break;
289206f32e7eSjoerg     case Instruction::SExt:
289306f32e7eSjoerg       Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
289406f32e7eSjoerg       return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
289506f32e7eSjoerg 
289606f32e7eSjoerg     case Instruction::SDiv: {
289706f32e7eSjoerg       const APInt *Denominator;
289806f32e7eSjoerg       // sdiv X, C -> adds log(C) sign bits.
289906f32e7eSjoerg       if (match(U->getOperand(1), m_APInt(Denominator))) {
290006f32e7eSjoerg 
290106f32e7eSjoerg         // Ignore non-positive denominator.
290206f32e7eSjoerg         if (!Denominator->isStrictlyPositive())
290306f32e7eSjoerg           break;
290406f32e7eSjoerg 
290506f32e7eSjoerg         // Calculate the incoming numerator bits.
290606f32e7eSjoerg         unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
290706f32e7eSjoerg 
290806f32e7eSjoerg         // Add floor(log(C)) bits to the numerator bits.
290906f32e7eSjoerg         return std::min(TyBits, NumBits + Denominator->logBase2());
291006f32e7eSjoerg       }
291106f32e7eSjoerg       break;
291206f32e7eSjoerg     }
291306f32e7eSjoerg 
291406f32e7eSjoerg     case Instruction::SRem: {
2915*da58b97aSjoerg       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2916*da58b97aSjoerg 
291706f32e7eSjoerg       const APInt *Denominator;
291806f32e7eSjoerg       // srem X, C -> we know that the result is within [-C+1,C) when C is a
291906f32e7eSjoerg       // positive constant.  This let us put a lower bound on the number of sign
292006f32e7eSjoerg       // bits.
292106f32e7eSjoerg       if (match(U->getOperand(1), m_APInt(Denominator))) {
292206f32e7eSjoerg 
292306f32e7eSjoerg         // Ignore non-positive denominator.
2924*da58b97aSjoerg         if (Denominator->isStrictlyPositive()) {
292506f32e7eSjoerg           // Calculate the leading sign bit constraints by examining the
292606f32e7eSjoerg           // denominator.  Given that the denominator is positive, there are two
292706f32e7eSjoerg           // cases:
292806f32e7eSjoerg           //
2929*da58b97aSjoerg           //  1. The numerator is positive. The result range is [0,C) and
2930*da58b97aSjoerg           //     [0,C) u< (1 << ceilLogBase2(C)).
293106f32e7eSjoerg           //
2932*da58b97aSjoerg           //  2. The numerator is negative. Then the result range is (-C,0] and
293306f32e7eSjoerg           //     integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
293406f32e7eSjoerg           //
293506f32e7eSjoerg           // Thus a lower bound on the number of sign bits is `TyBits -
293606f32e7eSjoerg           // ceilLogBase2(C)`.
293706f32e7eSjoerg 
293806f32e7eSjoerg           unsigned ResBits = TyBits - Denominator->ceilLogBase2();
2939*da58b97aSjoerg           Tmp = std::max(Tmp, ResBits);
294006f32e7eSjoerg         }
2941*da58b97aSjoerg       }
2942*da58b97aSjoerg       return Tmp;
294306f32e7eSjoerg     }
294406f32e7eSjoerg 
294506f32e7eSjoerg     case Instruction::AShr: {
294606f32e7eSjoerg       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
294706f32e7eSjoerg       // ashr X, C   -> adds C sign bits.  Vectors too.
294806f32e7eSjoerg       const APInt *ShAmt;
294906f32e7eSjoerg       if (match(U->getOperand(1), m_APInt(ShAmt))) {
295006f32e7eSjoerg         if (ShAmt->uge(TyBits))
295106f32e7eSjoerg           break; // Bad shift.
295206f32e7eSjoerg         unsigned ShAmtLimited = ShAmt->getZExtValue();
295306f32e7eSjoerg         Tmp += ShAmtLimited;
295406f32e7eSjoerg         if (Tmp > TyBits) Tmp = TyBits;
295506f32e7eSjoerg       }
295606f32e7eSjoerg       return Tmp;
295706f32e7eSjoerg     }
295806f32e7eSjoerg     case Instruction::Shl: {
295906f32e7eSjoerg       const APInt *ShAmt;
296006f32e7eSjoerg       if (match(U->getOperand(1), m_APInt(ShAmt))) {
296106f32e7eSjoerg         // shl destroys sign bits.
296206f32e7eSjoerg         Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
296306f32e7eSjoerg         if (ShAmt->uge(TyBits) ||   // Bad shift.
296406f32e7eSjoerg             ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
296506f32e7eSjoerg         Tmp2 = ShAmt->getZExtValue();
296606f32e7eSjoerg         return Tmp - Tmp2;
296706f32e7eSjoerg       }
296806f32e7eSjoerg       break;
296906f32e7eSjoerg     }
297006f32e7eSjoerg     case Instruction::And:
297106f32e7eSjoerg     case Instruction::Or:
297206f32e7eSjoerg     case Instruction::Xor: // NOT is handled here.
297306f32e7eSjoerg       // Logical binary ops preserve the number of sign bits at the worst.
297406f32e7eSjoerg       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
297506f32e7eSjoerg       if (Tmp != 1) {
297606f32e7eSjoerg         Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
297706f32e7eSjoerg         FirstAnswer = std::min(Tmp, Tmp2);
297806f32e7eSjoerg         // We computed what we know about the sign bits as our first
297906f32e7eSjoerg         // answer. Now proceed to the generic code that uses
298006f32e7eSjoerg         // computeKnownBits, and pick whichever answer is better.
298106f32e7eSjoerg       }
298206f32e7eSjoerg       break;
298306f32e7eSjoerg 
298406f32e7eSjoerg     case Instruction::Select: {
298506f32e7eSjoerg       // If we have a clamp pattern, we know that the number of sign bits will
298606f32e7eSjoerg       // be the minimum of the clamp min/max range.
298706f32e7eSjoerg       const Value *X;
298806f32e7eSjoerg       const APInt *CLow, *CHigh;
298906f32e7eSjoerg       if (isSignedMinMaxClamp(U, X, CLow, CHigh))
299006f32e7eSjoerg         return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
299106f32e7eSjoerg 
299206f32e7eSjoerg       Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
299306f32e7eSjoerg       if (Tmp == 1) break;
299406f32e7eSjoerg       Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
299506f32e7eSjoerg       return std::min(Tmp, Tmp2);
299606f32e7eSjoerg     }
299706f32e7eSjoerg 
299806f32e7eSjoerg     case Instruction::Add:
299906f32e7eSjoerg       // Add can have at most one carry bit.  Thus we know that the output
300006f32e7eSjoerg       // is, at worst, one more bit than the inputs.
300106f32e7eSjoerg       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
300206f32e7eSjoerg       if (Tmp == 1) break;
300306f32e7eSjoerg 
300406f32e7eSjoerg       // Special case decrementing a value (ADD X, -1):
300506f32e7eSjoerg       if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
300606f32e7eSjoerg         if (CRHS->isAllOnesValue()) {
300706f32e7eSjoerg           KnownBits Known(TyBits);
300806f32e7eSjoerg           computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
300906f32e7eSjoerg 
301006f32e7eSjoerg           // If the input is known to be 0 or 1, the output is 0/-1, which is
301106f32e7eSjoerg           // all sign bits set.
301206f32e7eSjoerg           if ((Known.Zero | 1).isAllOnesValue())
301306f32e7eSjoerg             return TyBits;
301406f32e7eSjoerg 
301506f32e7eSjoerg           // If we are subtracting one from a positive number, there is no carry
301606f32e7eSjoerg           // out of the result.
301706f32e7eSjoerg           if (Known.isNonNegative())
301806f32e7eSjoerg             return Tmp;
301906f32e7eSjoerg         }
302006f32e7eSjoerg 
302106f32e7eSjoerg       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
302206f32e7eSjoerg       if (Tmp2 == 1) break;
302306f32e7eSjoerg       return std::min(Tmp, Tmp2) - 1;
302406f32e7eSjoerg 
302506f32e7eSjoerg     case Instruction::Sub:
302606f32e7eSjoerg       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
302706f32e7eSjoerg       if (Tmp2 == 1) break;
302806f32e7eSjoerg 
302906f32e7eSjoerg       // Handle NEG.
303006f32e7eSjoerg       if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
303106f32e7eSjoerg         if (CLHS->isNullValue()) {
303206f32e7eSjoerg           KnownBits Known(TyBits);
303306f32e7eSjoerg           computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
303406f32e7eSjoerg           // If the input is known to be 0 or 1, the output is 0/-1, which is
303506f32e7eSjoerg           // all sign bits set.
303606f32e7eSjoerg           if ((Known.Zero | 1).isAllOnesValue())
303706f32e7eSjoerg             return TyBits;
303806f32e7eSjoerg 
303906f32e7eSjoerg           // If the input is known to be positive (the sign bit is known clear),
304006f32e7eSjoerg           // the output of the NEG has the same number of sign bits as the
304106f32e7eSjoerg           // input.
304206f32e7eSjoerg           if (Known.isNonNegative())
304306f32e7eSjoerg             return Tmp2;
304406f32e7eSjoerg 
304506f32e7eSjoerg           // Otherwise, we treat this like a SUB.
304606f32e7eSjoerg         }
304706f32e7eSjoerg 
304806f32e7eSjoerg       // Sub can have at most one carry bit.  Thus we know that the output
304906f32e7eSjoerg       // is, at worst, one more bit than the inputs.
305006f32e7eSjoerg       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
305106f32e7eSjoerg       if (Tmp == 1) break;
305206f32e7eSjoerg       return std::min(Tmp, Tmp2) - 1;
305306f32e7eSjoerg 
305406f32e7eSjoerg     case Instruction::Mul: {
305506f32e7eSjoerg       // The output of the Mul can be at most twice the valid bits in the
305606f32e7eSjoerg       // inputs.
305706f32e7eSjoerg       unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
305806f32e7eSjoerg       if (SignBitsOp0 == 1) break;
305906f32e7eSjoerg       unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
306006f32e7eSjoerg       if (SignBitsOp1 == 1) break;
306106f32e7eSjoerg       unsigned OutValidBits =
306206f32e7eSjoerg           (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
306306f32e7eSjoerg       return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
306406f32e7eSjoerg     }
306506f32e7eSjoerg 
306606f32e7eSjoerg     case Instruction::PHI: {
306706f32e7eSjoerg       const PHINode *PN = cast<PHINode>(U);
306806f32e7eSjoerg       unsigned NumIncomingValues = PN->getNumIncomingValues();
306906f32e7eSjoerg       // Don't analyze large in-degree PHIs.
307006f32e7eSjoerg       if (NumIncomingValues > 4) break;
307106f32e7eSjoerg       // Unreachable blocks may have zero-operand PHI nodes.
307206f32e7eSjoerg       if (NumIncomingValues == 0) break;
307306f32e7eSjoerg 
307406f32e7eSjoerg       // Take the minimum of all incoming values.  This can't infinitely loop
307506f32e7eSjoerg       // because of our depth threshold.
3076*da58b97aSjoerg       Query RecQ = Q;
3077*da58b97aSjoerg       Tmp = TyBits;
3078*da58b97aSjoerg       for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
307906f32e7eSjoerg         if (Tmp == 1) return Tmp;
3080*da58b97aSjoerg         RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
308106f32e7eSjoerg         Tmp = std::min(
3082*da58b97aSjoerg             Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, RecQ));
308306f32e7eSjoerg       }
308406f32e7eSjoerg       return Tmp;
308506f32e7eSjoerg     }
308606f32e7eSjoerg 
308706f32e7eSjoerg     case Instruction::Trunc:
308806f32e7eSjoerg       // FIXME: it's tricky to do anything useful for this, but it is an
308906f32e7eSjoerg       // important case for targets like X86.
309006f32e7eSjoerg       break;
309106f32e7eSjoerg 
309206f32e7eSjoerg     case Instruction::ExtractElement:
309306f32e7eSjoerg       // Look through extract element. At the moment we keep this simple and
309406f32e7eSjoerg       // skip tracking the specific element. But at least we might find
309506f32e7eSjoerg       // information valid for all elements of the vector (for example if vector
309606f32e7eSjoerg       // is sign extended, shifted, etc).
309706f32e7eSjoerg       return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
309806f32e7eSjoerg 
309906f32e7eSjoerg     case Instruction::ShuffleVector: {
310006f32e7eSjoerg       // Collect the minimum number of sign bits that are shared by every vector
310106f32e7eSjoerg       // element referenced by the shuffle.
3102*da58b97aSjoerg       auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
3103*da58b97aSjoerg       if (!Shuf) {
3104*da58b97aSjoerg         // FIXME: Add support for shufflevector constant expressions.
3105*da58b97aSjoerg         return 1;
3106*da58b97aSjoerg       }
3107*da58b97aSjoerg       APInt DemandedLHS, DemandedRHS;
310806f32e7eSjoerg       // For undef elements, we don't know anything about the common state of
310906f32e7eSjoerg       // the shuffle result.
3110*da58b97aSjoerg       if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
311106f32e7eSjoerg         return 1;
311206f32e7eSjoerg       Tmp = std::numeric_limits<unsigned>::max();
3113*da58b97aSjoerg       if (!!DemandedLHS) {
3114*da58b97aSjoerg         const Value *LHS = Shuf->getOperand(0);
3115*da58b97aSjoerg         Tmp = ComputeNumSignBits(LHS, DemandedLHS, Depth + 1, Q);
3116*da58b97aSjoerg       }
3117*da58b97aSjoerg       // If we don't know anything, early out and try computeKnownBits
3118*da58b97aSjoerg       // fall-back.
3119*da58b97aSjoerg       if (Tmp == 1)
3120*da58b97aSjoerg         break;
312106f32e7eSjoerg       if (!!DemandedRHS) {
3122*da58b97aSjoerg         const Value *RHS = Shuf->getOperand(1);
3123*da58b97aSjoerg         Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Depth + 1, Q);
312406f32e7eSjoerg         Tmp = std::min(Tmp, Tmp2);
312506f32e7eSjoerg       }
312606f32e7eSjoerg       // If we don't know anything, early out and try computeKnownBits
312706f32e7eSjoerg       // fall-back.
312806f32e7eSjoerg       if (Tmp == 1)
312906f32e7eSjoerg         break;
3130*da58b97aSjoerg       assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
313106f32e7eSjoerg       return Tmp;
313206f32e7eSjoerg     }
3133*da58b97aSjoerg     case Instruction::Call: {
3134*da58b97aSjoerg       if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
3135*da58b97aSjoerg         switch (II->getIntrinsicID()) {
3136*da58b97aSjoerg         default: break;
3137*da58b97aSjoerg         case Intrinsic::abs:
3138*da58b97aSjoerg           Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3139*da58b97aSjoerg           if (Tmp == 1) break;
3140*da58b97aSjoerg 
3141*da58b97aSjoerg           // Absolute value reduces number of sign bits by at most 1.
3142*da58b97aSjoerg           return Tmp - 1;
3143*da58b97aSjoerg         }
3144*da58b97aSjoerg       }
3145*da58b97aSjoerg     }
314606f32e7eSjoerg     }
314706f32e7eSjoerg   }
314806f32e7eSjoerg 
314906f32e7eSjoerg   // Finally, if we can prove that the top bits of the result are 0's or 1's,
315006f32e7eSjoerg   // use this information.
315106f32e7eSjoerg 
315206f32e7eSjoerg   // If we can examine all elements of a vector constant successfully, we're
315306f32e7eSjoerg   // done (we can't do any better than that). If not, keep trying.
3154*da58b97aSjoerg   if (unsigned VecSignBits =
3155*da58b97aSjoerg           computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
315606f32e7eSjoerg     return VecSignBits;
315706f32e7eSjoerg 
315806f32e7eSjoerg   KnownBits Known(TyBits);
3159*da58b97aSjoerg   computeKnownBits(V, DemandedElts, Known, Depth, Q);
316006f32e7eSjoerg 
316106f32e7eSjoerg   // If we know that the sign bit is either zero or one, determine the number of
316206f32e7eSjoerg   // identical bits in the top of the input value.
316306f32e7eSjoerg   return std::max(FirstAnswer, Known.countMinSignBits());
316406f32e7eSjoerg }
316506f32e7eSjoerg 
316606f32e7eSjoerg /// This function computes the integer multiple of Base that equals V.
316706f32e7eSjoerg /// If successful, it returns true and returns the multiple in
316806f32e7eSjoerg /// Multiple. If unsuccessful, it returns false. It looks
316906f32e7eSjoerg /// through SExt instructions only if LookThroughSExt is true.
ComputeMultiple(Value * V,unsigned Base,Value * & Multiple,bool LookThroughSExt,unsigned Depth)317006f32e7eSjoerg bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
317106f32e7eSjoerg                            bool LookThroughSExt, unsigned Depth) {
317206f32e7eSjoerg   assert(V && "No Value?");
3173*da58b97aSjoerg   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
317406f32e7eSjoerg   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
317506f32e7eSjoerg 
317606f32e7eSjoerg   Type *T = V->getType();
317706f32e7eSjoerg 
317806f32e7eSjoerg   ConstantInt *CI = dyn_cast<ConstantInt>(V);
317906f32e7eSjoerg 
318006f32e7eSjoerg   if (Base == 0)
318106f32e7eSjoerg     return false;
318206f32e7eSjoerg 
318306f32e7eSjoerg   if (Base == 1) {
318406f32e7eSjoerg     Multiple = V;
318506f32e7eSjoerg     return true;
318606f32e7eSjoerg   }
318706f32e7eSjoerg 
318806f32e7eSjoerg   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
318906f32e7eSjoerg   Constant *BaseVal = ConstantInt::get(T, Base);
319006f32e7eSjoerg   if (CO && CO == BaseVal) {
319106f32e7eSjoerg     // Multiple is 1.
319206f32e7eSjoerg     Multiple = ConstantInt::get(T, 1);
319306f32e7eSjoerg     return true;
319406f32e7eSjoerg   }
319506f32e7eSjoerg 
319606f32e7eSjoerg   if (CI && CI->getZExtValue() % Base == 0) {
319706f32e7eSjoerg     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
319806f32e7eSjoerg     return true;
319906f32e7eSjoerg   }
320006f32e7eSjoerg 
3201*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth) return false;
320206f32e7eSjoerg 
320306f32e7eSjoerg   Operator *I = dyn_cast<Operator>(V);
320406f32e7eSjoerg   if (!I) return false;
320506f32e7eSjoerg 
320606f32e7eSjoerg   switch (I->getOpcode()) {
320706f32e7eSjoerg   default: break;
320806f32e7eSjoerg   case Instruction::SExt:
320906f32e7eSjoerg     if (!LookThroughSExt) return false;
321006f32e7eSjoerg     // otherwise fall through to ZExt
321106f32e7eSjoerg     LLVM_FALLTHROUGH;
321206f32e7eSjoerg   case Instruction::ZExt:
321306f32e7eSjoerg     return ComputeMultiple(I->getOperand(0), Base, Multiple,
321406f32e7eSjoerg                            LookThroughSExt, Depth+1);
321506f32e7eSjoerg   case Instruction::Shl:
321606f32e7eSjoerg   case Instruction::Mul: {
321706f32e7eSjoerg     Value *Op0 = I->getOperand(0);
321806f32e7eSjoerg     Value *Op1 = I->getOperand(1);
321906f32e7eSjoerg 
322006f32e7eSjoerg     if (I->getOpcode() == Instruction::Shl) {
322106f32e7eSjoerg       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
322206f32e7eSjoerg       if (!Op1CI) return false;
322306f32e7eSjoerg       // Turn Op0 << Op1 into Op0 * 2^Op1
322406f32e7eSjoerg       APInt Op1Int = Op1CI->getValue();
322506f32e7eSjoerg       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
322606f32e7eSjoerg       APInt API(Op1Int.getBitWidth(), 0);
322706f32e7eSjoerg       API.setBit(BitToSet);
322806f32e7eSjoerg       Op1 = ConstantInt::get(V->getContext(), API);
322906f32e7eSjoerg     }
323006f32e7eSjoerg 
323106f32e7eSjoerg     Value *Mul0 = nullptr;
323206f32e7eSjoerg     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
323306f32e7eSjoerg       if (Constant *Op1C = dyn_cast<Constant>(Op1))
323406f32e7eSjoerg         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
3235*da58b97aSjoerg           if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() <
3236*da58b97aSjoerg               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
323706f32e7eSjoerg             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
3238*da58b97aSjoerg           if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() >
3239*da58b97aSjoerg               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
324006f32e7eSjoerg             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
324106f32e7eSjoerg 
324206f32e7eSjoerg           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
324306f32e7eSjoerg           Multiple = ConstantExpr::getMul(MulC, Op1C);
324406f32e7eSjoerg           return true;
324506f32e7eSjoerg         }
324606f32e7eSjoerg 
324706f32e7eSjoerg       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
324806f32e7eSjoerg         if (Mul0CI->getValue() == 1) {
324906f32e7eSjoerg           // V == Base * Op1, so return Op1
325006f32e7eSjoerg           Multiple = Op1;
325106f32e7eSjoerg           return true;
325206f32e7eSjoerg         }
325306f32e7eSjoerg     }
325406f32e7eSjoerg 
325506f32e7eSjoerg     Value *Mul1 = nullptr;
325606f32e7eSjoerg     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
325706f32e7eSjoerg       if (Constant *Op0C = dyn_cast<Constant>(Op0))
325806f32e7eSjoerg         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
3259*da58b97aSjoerg           if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() <
3260*da58b97aSjoerg               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
326106f32e7eSjoerg             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
3262*da58b97aSjoerg           if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() >
3263*da58b97aSjoerg               MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
326406f32e7eSjoerg             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
326506f32e7eSjoerg 
326606f32e7eSjoerg           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
326706f32e7eSjoerg           Multiple = ConstantExpr::getMul(MulC, Op0C);
326806f32e7eSjoerg           return true;
326906f32e7eSjoerg         }
327006f32e7eSjoerg 
327106f32e7eSjoerg       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
327206f32e7eSjoerg         if (Mul1CI->getValue() == 1) {
327306f32e7eSjoerg           // V == Base * Op0, so return Op0
327406f32e7eSjoerg           Multiple = Op0;
327506f32e7eSjoerg           return true;
327606f32e7eSjoerg         }
327706f32e7eSjoerg     }
327806f32e7eSjoerg   }
327906f32e7eSjoerg   }
328006f32e7eSjoerg 
328106f32e7eSjoerg   // We could not determine if V is a multiple of Base.
328206f32e7eSjoerg   return false;
328306f32e7eSjoerg }
328406f32e7eSjoerg 
getIntrinsicForCallSite(const CallBase & CB,const TargetLibraryInfo * TLI)3285*da58b97aSjoerg Intrinsic::ID llvm::getIntrinsicForCallSite(const CallBase &CB,
328606f32e7eSjoerg                                             const TargetLibraryInfo *TLI) {
3287*da58b97aSjoerg   const Function *F = CB.getCalledFunction();
328806f32e7eSjoerg   if (!F)
328906f32e7eSjoerg     return Intrinsic::not_intrinsic;
329006f32e7eSjoerg 
329106f32e7eSjoerg   if (F->isIntrinsic())
329206f32e7eSjoerg     return F->getIntrinsicID();
329306f32e7eSjoerg 
3294*da58b97aSjoerg   // We are going to infer semantics of a library function based on mapping it
3295*da58b97aSjoerg   // to an LLVM intrinsic. Check that the library function is available from
3296*da58b97aSjoerg   // this callbase and in this environment.
329706f32e7eSjoerg   LibFunc Func;
3298*da58b97aSjoerg   if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) ||
3299*da58b97aSjoerg       !CB.onlyReadsMemory())
330006f32e7eSjoerg     return Intrinsic::not_intrinsic;
330106f32e7eSjoerg 
330206f32e7eSjoerg   switch (Func) {
330306f32e7eSjoerg   default:
330406f32e7eSjoerg     break;
330506f32e7eSjoerg   case LibFunc_sin:
330606f32e7eSjoerg   case LibFunc_sinf:
330706f32e7eSjoerg   case LibFunc_sinl:
330806f32e7eSjoerg     return Intrinsic::sin;
330906f32e7eSjoerg   case LibFunc_cos:
331006f32e7eSjoerg   case LibFunc_cosf:
331106f32e7eSjoerg   case LibFunc_cosl:
331206f32e7eSjoerg     return Intrinsic::cos;
331306f32e7eSjoerg   case LibFunc_exp:
331406f32e7eSjoerg   case LibFunc_expf:
331506f32e7eSjoerg   case LibFunc_expl:
331606f32e7eSjoerg     return Intrinsic::exp;
331706f32e7eSjoerg   case LibFunc_exp2:
331806f32e7eSjoerg   case LibFunc_exp2f:
331906f32e7eSjoerg   case LibFunc_exp2l:
332006f32e7eSjoerg     return Intrinsic::exp2;
332106f32e7eSjoerg   case LibFunc_log:
332206f32e7eSjoerg   case LibFunc_logf:
332306f32e7eSjoerg   case LibFunc_logl:
332406f32e7eSjoerg     return Intrinsic::log;
332506f32e7eSjoerg   case LibFunc_log10:
332606f32e7eSjoerg   case LibFunc_log10f:
332706f32e7eSjoerg   case LibFunc_log10l:
332806f32e7eSjoerg     return Intrinsic::log10;
332906f32e7eSjoerg   case LibFunc_log2:
333006f32e7eSjoerg   case LibFunc_log2f:
333106f32e7eSjoerg   case LibFunc_log2l:
333206f32e7eSjoerg     return Intrinsic::log2;
333306f32e7eSjoerg   case LibFunc_fabs:
333406f32e7eSjoerg   case LibFunc_fabsf:
333506f32e7eSjoerg   case LibFunc_fabsl:
333606f32e7eSjoerg     return Intrinsic::fabs;
333706f32e7eSjoerg   case LibFunc_fmin:
333806f32e7eSjoerg   case LibFunc_fminf:
333906f32e7eSjoerg   case LibFunc_fminl:
334006f32e7eSjoerg     return Intrinsic::minnum;
334106f32e7eSjoerg   case LibFunc_fmax:
334206f32e7eSjoerg   case LibFunc_fmaxf:
334306f32e7eSjoerg   case LibFunc_fmaxl:
334406f32e7eSjoerg     return Intrinsic::maxnum;
334506f32e7eSjoerg   case LibFunc_copysign:
334606f32e7eSjoerg   case LibFunc_copysignf:
334706f32e7eSjoerg   case LibFunc_copysignl:
334806f32e7eSjoerg     return Intrinsic::copysign;
334906f32e7eSjoerg   case LibFunc_floor:
335006f32e7eSjoerg   case LibFunc_floorf:
335106f32e7eSjoerg   case LibFunc_floorl:
335206f32e7eSjoerg     return Intrinsic::floor;
335306f32e7eSjoerg   case LibFunc_ceil:
335406f32e7eSjoerg   case LibFunc_ceilf:
335506f32e7eSjoerg   case LibFunc_ceill:
335606f32e7eSjoerg     return Intrinsic::ceil;
335706f32e7eSjoerg   case LibFunc_trunc:
335806f32e7eSjoerg   case LibFunc_truncf:
335906f32e7eSjoerg   case LibFunc_truncl:
336006f32e7eSjoerg     return Intrinsic::trunc;
336106f32e7eSjoerg   case LibFunc_rint:
336206f32e7eSjoerg   case LibFunc_rintf:
336306f32e7eSjoerg   case LibFunc_rintl:
336406f32e7eSjoerg     return Intrinsic::rint;
336506f32e7eSjoerg   case LibFunc_nearbyint:
336606f32e7eSjoerg   case LibFunc_nearbyintf:
336706f32e7eSjoerg   case LibFunc_nearbyintl:
336806f32e7eSjoerg     return Intrinsic::nearbyint;
336906f32e7eSjoerg   case LibFunc_round:
337006f32e7eSjoerg   case LibFunc_roundf:
337106f32e7eSjoerg   case LibFunc_roundl:
337206f32e7eSjoerg     return Intrinsic::round;
3373*da58b97aSjoerg   case LibFunc_roundeven:
3374*da58b97aSjoerg   case LibFunc_roundevenf:
3375*da58b97aSjoerg   case LibFunc_roundevenl:
3376*da58b97aSjoerg     return Intrinsic::roundeven;
337706f32e7eSjoerg   case LibFunc_pow:
337806f32e7eSjoerg   case LibFunc_powf:
337906f32e7eSjoerg   case LibFunc_powl:
338006f32e7eSjoerg     return Intrinsic::pow;
338106f32e7eSjoerg   case LibFunc_sqrt:
338206f32e7eSjoerg   case LibFunc_sqrtf:
338306f32e7eSjoerg   case LibFunc_sqrtl:
338406f32e7eSjoerg     return Intrinsic::sqrt;
338506f32e7eSjoerg   }
338606f32e7eSjoerg 
338706f32e7eSjoerg   return Intrinsic::not_intrinsic;
338806f32e7eSjoerg }
338906f32e7eSjoerg 
339006f32e7eSjoerg /// Return true if we can prove that the specified FP value is never equal to
339106f32e7eSjoerg /// -0.0.
3392*da58b97aSjoerg /// NOTE: Do not check 'nsz' here because that fast-math-flag does not guarantee
3393*da58b97aSjoerg ///       that a value is not -0.0. It only guarantees that -0.0 may be treated
3394*da58b97aSjoerg ///       the same as +0.0 in floating-point ops.
339506f32e7eSjoerg ///
339606f32e7eSjoerg /// NOTE: this function will need to be revisited when we support non-default
339706f32e7eSjoerg /// rounding modes!
CannotBeNegativeZero(const Value * V,const TargetLibraryInfo * TLI,unsigned Depth)339806f32e7eSjoerg bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
339906f32e7eSjoerg                                 unsigned Depth) {
340006f32e7eSjoerg   if (auto *CFP = dyn_cast<ConstantFP>(V))
340106f32e7eSjoerg     return !CFP->getValueAPF().isNegZero();
340206f32e7eSjoerg 
3403*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
340406f32e7eSjoerg     return false;
340506f32e7eSjoerg 
340606f32e7eSjoerg   auto *Op = dyn_cast<Operator>(V);
340706f32e7eSjoerg   if (!Op)
340806f32e7eSjoerg     return false;
340906f32e7eSjoerg 
341006f32e7eSjoerg   // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
341106f32e7eSjoerg   if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
341206f32e7eSjoerg     return true;
341306f32e7eSjoerg 
341406f32e7eSjoerg   // sitofp and uitofp turn into +0.0 for zero.
341506f32e7eSjoerg   if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
341606f32e7eSjoerg     return true;
341706f32e7eSjoerg 
341806f32e7eSjoerg   if (auto *Call = dyn_cast<CallInst>(Op)) {
3419*da58b97aSjoerg     Intrinsic::ID IID = getIntrinsicForCallSite(*Call, TLI);
342006f32e7eSjoerg     switch (IID) {
342106f32e7eSjoerg     default:
342206f32e7eSjoerg       break;
342306f32e7eSjoerg     // sqrt(-0.0) = -0.0, no other negative results are possible.
342406f32e7eSjoerg     case Intrinsic::sqrt:
342506f32e7eSjoerg     case Intrinsic::canonicalize:
342606f32e7eSjoerg       return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
342706f32e7eSjoerg     // fabs(x) != -0.0
342806f32e7eSjoerg     case Intrinsic::fabs:
342906f32e7eSjoerg       return true;
343006f32e7eSjoerg     }
343106f32e7eSjoerg   }
343206f32e7eSjoerg 
343306f32e7eSjoerg   return false;
343406f32e7eSjoerg }
343506f32e7eSjoerg 
343606f32e7eSjoerg /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
343706f32e7eSjoerg /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
343806f32e7eSjoerg /// bit despite comparing equal.
cannotBeOrderedLessThanZeroImpl(const Value * V,const TargetLibraryInfo * TLI,bool SignBitOnly,unsigned Depth)343906f32e7eSjoerg static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
344006f32e7eSjoerg                                             const TargetLibraryInfo *TLI,
344106f32e7eSjoerg                                             bool SignBitOnly,
344206f32e7eSjoerg                                             unsigned Depth) {
344306f32e7eSjoerg   // TODO: This function does not do the right thing when SignBitOnly is true
344406f32e7eSjoerg   // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
344506f32e7eSjoerg   // which flips the sign bits of NaNs.  See
344606f32e7eSjoerg   // https://llvm.org/bugs/show_bug.cgi?id=31702.
344706f32e7eSjoerg 
344806f32e7eSjoerg   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
344906f32e7eSjoerg     return !CFP->getValueAPF().isNegative() ||
345006f32e7eSjoerg            (!SignBitOnly && CFP->getValueAPF().isZero());
345106f32e7eSjoerg   }
345206f32e7eSjoerg 
345306f32e7eSjoerg   // Handle vector of constants.
345406f32e7eSjoerg   if (auto *CV = dyn_cast<Constant>(V)) {
3455*da58b97aSjoerg     if (auto *CVFVTy = dyn_cast<FixedVectorType>(CV->getType())) {
3456*da58b97aSjoerg       unsigned NumElts = CVFVTy->getNumElements();
345706f32e7eSjoerg       for (unsigned i = 0; i != NumElts; ++i) {
345806f32e7eSjoerg         auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
345906f32e7eSjoerg         if (!CFP)
346006f32e7eSjoerg           return false;
346106f32e7eSjoerg         if (CFP->getValueAPF().isNegative() &&
346206f32e7eSjoerg             (SignBitOnly || !CFP->getValueAPF().isZero()))
346306f32e7eSjoerg           return false;
346406f32e7eSjoerg       }
346506f32e7eSjoerg 
346606f32e7eSjoerg       // All non-negative ConstantFPs.
346706f32e7eSjoerg       return true;
346806f32e7eSjoerg     }
346906f32e7eSjoerg   }
347006f32e7eSjoerg 
3471*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
3472*da58b97aSjoerg     return false;
347306f32e7eSjoerg 
347406f32e7eSjoerg   const Operator *I = dyn_cast<Operator>(V);
347506f32e7eSjoerg   if (!I)
347606f32e7eSjoerg     return false;
347706f32e7eSjoerg 
347806f32e7eSjoerg   switch (I->getOpcode()) {
347906f32e7eSjoerg   default:
348006f32e7eSjoerg     break;
348106f32e7eSjoerg   // Unsigned integers are always nonnegative.
348206f32e7eSjoerg   case Instruction::UIToFP:
348306f32e7eSjoerg     return true;
348406f32e7eSjoerg   case Instruction::FMul:
3485*da58b97aSjoerg   case Instruction::FDiv:
3486*da58b97aSjoerg     // X * X is always non-negative or a NaN.
3487*da58b97aSjoerg     // X / X is always exactly 1.0 or a NaN.
348806f32e7eSjoerg     if (I->getOperand(0) == I->getOperand(1) &&
348906f32e7eSjoerg         (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
349006f32e7eSjoerg       return true;
349106f32e7eSjoerg 
349206f32e7eSjoerg     LLVM_FALLTHROUGH;
349306f32e7eSjoerg   case Instruction::FAdd:
349406f32e7eSjoerg   case Instruction::FRem:
349506f32e7eSjoerg     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
349606f32e7eSjoerg                                            Depth + 1) &&
349706f32e7eSjoerg            cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
349806f32e7eSjoerg                                            Depth + 1);
349906f32e7eSjoerg   case Instruction::Select:
350006f32e7eSjoerg     return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
350106f32e7eSjoerg                                            Depth + 1) &&
350206f32e7eSjoerg            cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
350306f32e7eSjoerg                                            Depth + 1);
350406f32e7eSjoerg   case Instruction::FPExt:
350506f32e7eSjoerg   case Instruction::FPTrunc:
350606f32e7eSjoerg     // Widening/narrowing never change sign.
350706f32e7eSjoerg     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
350806f32e7eSjoerg                                            Depth + 1);
350906f32e7eSjoerg   case Instruction::ExtractElement:
351006f32e7eSjoerg     // Look through extract element. At the moment we keep this simple and skip
351106f32e7eSjoerg     // tracking the specific element. But at least we might find information
351206f32e7eSjoerg     // valid for all elements of the vector.
351306f32e7eSjoerg     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
351406f32e7eSjoerg                                            Depth + 1);
351506f32e7eSjoerg   case Instruction::Call:
351606f32e7eSjoerg     const auto *CI = cast<CallInst>(I);
3517*da58b97aSjoerg     Intrinsic::ID IID = getIntrinsicForCallSite(*CI, TLI);
351806f32e7eSjoerg     switch (IID) {
351906f32e7eSjoerg     default:
352006f32e7eSjoerg       break;
3521*da58b97aSjoerg     case Intrinsic::maxnum: {
3522*da58b97aSjoerg       Value *V0 = I->getOperand(0), *V1 = I->getOperand(1);
3523*da58b97aSjoerg       auto isPositiveNum = [&](Value *V) {
3524*da58b97aSjoerg         if (SignBitOnly) {
3525*da58b97aSjoerg           // With SignBitOnly, this is tricky because the result of
3526*da58b97aSjoerg           // maxnum(+0.0, -0.0) is unspecified. Just check if the operand is
3527*da58b97aSjoerg           // a constant strictly greater than 0.0.
3528*da58b97aSjoerg           const APFloat *C;
3529*da58b97aSjoerg           return match(V, m_APFloat(C)) &&
3530*da58b97aSjoerg                  *C > APFloat::getZero(C->getSemantics());
3531*da58b97aSjoerg         }
3532*da58b97aSjoerg 
3533*da58b97aSjoerg         // -0.0 compares equal to 0.0, so if this operand is at least -0.0,
3534*da58b97aSjoerg         // maxnum can't be ordered-less-than-zero.
3535*da58b97aSjoerg         return isKnownNeverNaN(V, TLI) &&
3536*da58b97aSjoerg                cannotBeOrderedLessThanZeroImpl(V, TLI, false, Depth + 1);
3537*da58b97aSjoerg       };
3538*da58b97aSjoerg 
3539*da58b97aSjoerg       // TODO: This could be improved. We could also check that neither operand
3540*da58b97aSjoerg       //       has its sign bit set (and at least 1 is not-NAN?).
3541*da58b97aSjoerg       return isPositiveNum(V0) || isPositiveNum(V1);
3542*da58b97aSjoerg     }
354306f32e7eSjoerg 
354406f32e7eSjoerg     case Intrinsic::maximum:
354506f32e7eSjoerg       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
354606f32e7eSjoerg                                              Depth + 1) ||
354706f32e7eSjoerg              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
354806f32e7eSjoerg                                              Depth + 1);
354906f32e7eSjoerg     case Intrinsic::minnum:
355006f32e7eSjoerg     case Intrinsic::minimum:
355106f32e7eSjoerg       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
355206f32e7eSjoerg                                              Depth + 1) &&
355306f32e7eSjoerg              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
355406f32e7eSjoerg                                              Depth + 1);
355506f32e7eSjoerg     case Intrinsic::exp:
355606f32e7eSjoerg     case Intrinsic::exp2:
355706f32e7eSjoerg     case Intrinsic::fabs:
355806f32e7eSjoerg       return true;
355906f32e7eSjoerg 
356006f32e7eSjoerg     case Intrinsic::sqrt:
356106f32e7eSjoerg       // sqrt(x) is always >= -0 or NaN.  Moreover, sqrt(x) == -0 iff x == -0.
356206f32e7eSjoerg       if (!SignBitOnly)
356306f32e7eSjoerg         return true;
356406f32e7eSjoerg       return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
356506f32e7eSjoerg                                  CannotBeNegativeZero(CI->getOperand(0), TLI));
356606f32e7eSjoerg 
356706f32e7eSjoerg     case Intrinsic::powi:
356806f32e7eSjoerg       if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
356906f32e7eSjoerg         // powi(x,n) is non-negative if n is even.
357006f32e7eSjoerg         if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
357106f32e7eSjoerg           return true;
357206f32e7eSjoerg       }
357306f32e7eSjoerg       // TODO: This is not correct.  Given that exp is an integer, here are the
357406f32e7eSjoerg       // ways that pow can return a negative value:
357506f32e7eSjoerg       //
357606f32e7eSjoerg       //   pow(x, exp)    --> negative if exp is odd and x is negative.
357706f32e7eSjoerg       //   pow(-0, exp)   --> -inf if exp is negative odd.
357806f32e7eSjoerg       //   pow(-0, exp)   --> -0 if exp is positive odd.
357906f32e7eSjoerg       //   pow(-inf, exp) --> -0 if exp is negative odd.
358006f32e7eSjoerg       //   pow(-inf, exp) --> -inf if exp is positive odd.
358106f32e7eSjoerg       //
358206f32e7eSjoerg       // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
358306f32e7eSjoerg       // but we must return false if x == -0.  Unfortunately we do not currently
358406f32e7eSjoerg       // have a way of expressing this constraint.  See details in
358506f32e7eSjoerg       // https://llvm.org/bugs/show_bug.cgi?id=31702.
358606f32e7eSjoerg       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
358706f32e7eSjoerg                                              Depth + 1);
358806f32e7eSjoerg 
358906f32e7eSjoerg     case Intrinsic::fma:
359006f32e7eSjoerg     case Intrinsic::fmuladd:
359106f32e7eSjoerg       // x*x+y is non-negative if y is non-negative.
359206f32e7eSjoerg       return I->getOperand(0) == I->getOperand(1) &&
359306f32e7eSjoerg              (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
359406f32e7eSjoerg              cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
359506f32e7eSjoerg                                              Depth + 1);
359606f32e7eSjoerg     }
359706f32e7eSjoerg     break;
359806f32e7eSjoerg   }
359906f32e7eSjoerg   return false;
360006f32e7eSjoerg }
360106f32e7eSjoerg 
CannotBeOrderedLessThanZero(const Value * V,const TargetLibraryInfo * TLI)360206f32e7eSjoerg bool llvm::CannotBeOrderedLessThanZero(const Value *V,
360306f32e7eSjoerg                                        const TargetLibraryInfo *TLI) {
360406f32e7eSjoerg   return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
360506f32e7eSjoerg }
360606f32e7eSjoerg 
SignBitMustBeZero(const Value * V,const TargetLibraryInfo * TLI)360706f32e7eSjoerg bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
360806f32e7eSjoerg   return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
360906f32e7eSjoerg }
361006f32e7eSjoerg 
isKnownNeverInfinity(const Value * V,const TargetLibraryInfo * TLI,unsigned Depth)3611*da58b97aSjoerg bool llvm::isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI,
3612*da58b97aSjoerg                                 unsigned Depth) {
3613*da58b97aSjoerg   assert(V->getType()->isFPOrFPVectorTy() && "Querying for Inf on non-FP type");
3614*da58b97aSjoerg 
3615*da58b97aSjoerg   // If we're told that infinities won't happen, assume they won't.
3616*da58b97aSjoerg   if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3617*da58b97aSjoerg     if (FPMathOp->hasNoInfs())
3618*da58b97aSjoerg       return true;
3619*da58b97aSjoerg 
3620*da58b97aSjoerg   // Handle scalar constants.
3621*da58b97aSjoerg   if (auto *CFP = dyn_cast<ConstantFP>(V))
3622*da58b97aSjoerg     return !CFP->isInfinity();
3623*da58b97aSjoerg 
3624*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
3625*da58b97aSjoerg     return false;
3626*da58b97aSjoerg 
3627*da58b97aSjoerg   if (auto *Inst = dyn_cast<Instruction>(V)) {
3628*da58b97aSjoerg     switch (Inst->getOpcode()) {
3629*da58b97aSjoerg     case Instruction::Select: {
3630*da58b97aSjoerg       return isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1) &&
3631*da58b97aSjoerg              isKnownNeverInfinity(Inst->getOperand(2), TLI, Depth + 1);
3632*da58b97aSjoerg     }
3633*da58b97aSjoerg     case Instruction::SIToFP:
3634*da58b97aSjoerg     case Instruction::UIToFP: {
3635*da58b97aSjoerg       // Get width of largest magnitude integer (remove a bit if signed).
3636*da58b97aSjoerg       // This still works for a signed minimum value because the largest FP
3637*da58b97aSjoerg       // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
3638*da58b97aSjoerg       int IntSize = Inst->getOperand(0)->getType()->getScalarSizeInBits();
3639*da58b97aSjoerg       if (Inst->getOpcode() == Instruction::SIToFP)
3640*da58b97aSjoerg         --IntSize;
3641*da58b97aSjoerg 
3642*da58b97aSjoerg       // If the exponent of the largest finite FP value can hold the largest
3643*da58b97aSjoerg       // integer, the result of the cast must be finite.
3644*da58b97aSjoerg       Type *FPTy = Inst->getType()->getScalarType();
3645*da58b97aSjoerg       return ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize;
3646*da58b97aSjoerg     }
3647*da58b97aSjoerg     default:
3648*da58b97aSjoerg       break;
3649*da58b97aSjoerg     }
3650*da58b97aSjoerg   }
3651*da58b97aSjoerg 
3652*da58b97aSjoerg   // try to handle fixed width vector constants
3653*da58b97aSjoerg   auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3654*da58b97aSjoerg   if (VFVTy && isa<Constant>(V)) {
3655*da58b97aSjoerg     // For vectors, verify that each element is not infinity.
3656*da58b97aSjoerg     unsigned NumElts = VFVTy->getNumElements();
3657*da58b97aSjoerg     for (unsigned i = 0; i != NumElts; ++i) {
3658*da58b97aSjoerg       Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3659*da58b97aSjoerg       if (!Elt)
3660*da58b97aSjoerg         return false;
3661*da58b97aSjoerg       if (isa<UndefValue>(Elt))
3662*da58b97aSjoerg         continue;
3663*da58b97aSjoerg       auto *CElt = dyn_cast<ConstantFP>(Elt);
3664*da58b97aSjoerg       if (!CElt || CElt->isInfinity())
3665*da58b97aSjoerg         return false;
3666*da58b97aSjoerg     }
3667*da58b97aSjoerg     // All elements were confirmed non-infinity or undefined.
3668*da58b97aSjoerg     return true;
3669*da58b97aSjoerg   }
3670*da58b97aSjoerg 
3671*da58b97aSjoerg   // was not able to prove that V never contains infinity
3672*da58b97aSjoerg   return false;
3673*da58b97aSjoerg }
3674*da58b97aSjoerg 
isKnownNeverNaN(const Value * V,const TargetLibraryInfo * TLI,unsigned Depth)367506f32e7eSjoerg bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
367606f32e7eSjoerg                            unsigned Depth) {
367706f32e7eSjoerg   assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
367806f32e7eSjoerg 
367906f32e7eSjoerg   // If we're told that NaNs won't happen, assume they won't.
368006f32e7eSjoerg   if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
368106f32e7eSjoerg     if (FPMathOp->hasNoNaNs())
368206f32e7eSjoerg       return true;
368306f32e7eSjoerg 
368406f32e7eSjoerg   // Handle scalar constants.
368506f32e7eSjoerg   if (auto *CFP = dyn_cast<ConstantFP>(V))
368606f32e7eSjoerg     return !CFP->isNaN();
368706f32e7eSjoerg 
3688*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
368906f32e7eSjoerg     return false;
369006f32e7eSjoerg 
369106f32e7eSjoerg   if (auto *Inst = dyn_cast<Instruction>(V)) {
369206f32e7eSjoerg     switch (Inst->getOpcode()) {
369306f32e7eSjoerg     case Instruction::FAdd:
369406f32e7eSjoerg     case Instruction::FSub:
3695*da58b97aSjoerg       // Adding positive and negative infinity produces NaN.
3696*da58b97aSjoerg       return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3697*da58b97aSjoerg              isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3698*da58b97aSjoerg              (isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) ||
3699*da58b97aSjoerg               isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1));
3700*da58b97aSjoerg 
3701*da58b97aSjoerg     case Instruction::FMul:
3702*da58b97aSjoerg       // Zero multiplied with infinity produces NaN.
3703*da58b97aSjoerg       // FIXME: If neither side can be zero fmul never produces NaN.
3704*da58b97aSjoerg       return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3705*da58b97aSjoerg              isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) &&
3706*da58b97aSjoerg              isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3707*da58b97aSjoerg              isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1);
3708*da58b97aSjoerg 
370906f32e7eSjoerg     case Instruction::FDiv:
3710*da58b97aSjoerg     case Instruction::FRem:
3711*da58b97aSjoerg       // FIXME: Only 0/0, Inf/Inf, Inf REM x and x REM 0 produce NaN.
371206f32e7eSjoerg       return false;
3713*da58b97aSjoerg 
371406f32e7eSjoerg     case Instruction::Select: {
371506f32e7eSjoerg       return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
371606f32e7eSjoerg              isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
371706f32e7eSjoerg     }
371806f32e7eSjoerg     case Instruction::SIToFP:
371906f32e7eSjoerg     case Instruction::UIToFP:
372006f32e7eSjoerg       return true;
372106f32e7eSjoerg     case Instruction::FPTrunc:
372206f32e7eSjoerg     case Instruction::FPExt:
372306f32e7eSjoerg       return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
372406f32e7eSjoerg     default:
372506f32e7eSjoerg       break;
372606f32e7eSjoerg     }
372706f32e7eSjoerg   }
372806f32e7eSjoerg 
372906f32e7eSjoerg   if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
373006f32e7eSjoerg     switch (II->getIntrinsicID()) {
373106f32e7eSjoerg     case Intrinsic::canonicalize:
373206f32e7eSjoerg     case Intrinsic::fabs:
373306f32e7eSjoerg     case Intrinsic::copysign:
373406f32e7eSjoerg     case Intrinsic::exp:
373506f32e7eSjoerg     case Intrinsic::exp2:
373606f32e7eSjoerg     case Intrinsic::floor:
373706f32e7eSjoerg     case Intrinsic::ceil:
373806f32e7eSjoerg     case Intrinsic::trunc:
373906f32e7eSjoerg     case Intrinsic::rint:
374006f32e7eSjoerg     case Intrinsic::nearbyint:
374106f32e7eSjoerg     case Intrinsic::round:
3742*da58b97aSjoerg     case Intrinsic::roundeven:
374306f32e7eSjoerg       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
374406f32e7eSjoerg     case Intrinsic::sqrt:
374506f32e7eSjoerg       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
374606f32e7eSjoerg              CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
374706f32e7eSjoerg     case Intrinsic::minnum:
374806f32e7eSjoerg     case Intrinsic::maxnum:
374906f32e7eSjoerg       // If either operand is not NaN, the result is not NaN.
375006f32e7eSjoerg       return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
375106f32e7eSjoerg              isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
375206f32e7eSjoerg     default:
375306f32e7eSjoerg       return false;
375406f32e7eSjoerg     }
375506f32e7eSjoerg   }
375606f32e7eSjoerg 
3757*da58b97aSjoerg   // Try to handle fixed width vector constants
3758*da58b97aSjoerg   auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3759*da58b97aSjoerg   if (VFVTy && isa<Constant>(V)) {
376006f32e7eSjoerg     // For vectors, verify that each element is not NaN.
3761*da58b97aSjoerg     unsigned NumElts = VFVTy->getNumElements();
376206f32e7eSjoerg     for (unsigned i = 0; i != NumElts; ++i) {
376306f32e7eSjoerg       Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
376406f32e7eSjoerg       if (!Elt)
376506f32e7eSjoerg         return false;
376606f32e7eSjoerg       if (isa<UndefValue>(Elt))
376706f32e7eSjoerg         continue;
376806f32e7eSjoerg       auto *CElt = dyn_cast<ConstantFP>(Elt);
376906f32e7eSjoerg       if (!CElt || CElt->isNaN())
377006f32e7eSjoerg         return false;
377106f32e7eSjoerg     }
377206f32e7eSjoerg     // All elements were confirmed not-NaN or undefined.
377306f32e7eSjoerg     return true;
377406f32e7eSjoerg   }
377506f32e7eSjoerg 
3776*da58b97aSjoerg   // Was not able to prove that V never contains NaN
3777*da58b97aSjoerg   return false;
3778*da58b97aSjoerg }
3779*da58b97aSjoerg 
isBytewiseValue(Value * V,const DataLayout & DL)378006f32e7eSjoerg Value *llvm::isBytewiseValue(Value *V, const DataLayout &DL) {
378106f32e7eSjoerg 
378206f32e7eSjoerg   // All byte-wide stores are splatable, even of arbitrary variables.
378306f32e7eSjoerg   if (V->getType()->isIntegerTy(8))
378406f32e7eSjoerg     return V;
378506f32e7eSjoerg 
378606f32e7eSjoerg   LLVMContext &Ctx = V->getContext();
378706f32e7eSjoerg 
378806f32e7eSjoerg   // Undef don't care.
378906f32e7eSjoerg   auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
379006f32e7eSjoerg   if (isa<UndefValue>(V))
379106f32e7eSjoerg     return UndefInt8;
379206f32e7eSjoerg 
3793*da58b97aSjoerg   // Return Undef for zero-sized type.
3794*da58b97aSjoerg   if (!DL.getTypeStoreSize(V->getType()).isNonZero())
379506f32e7eSjoerg     return UndefInt8;
379606f32e7eSjoerg 
379706f32e7eSjoerg   Constant *C = dyn_cast<Constant>(V);
379806f32e7eSjoerg   if (!C) {
379906f32e7eSjoerg     // Conceptually, we could handle things like:
380006f32e7eSjoerg     //   %a = zext i8 %X to i16
380106f32e7eSjoerg     //   %b = shl i16 %a, 8
380206f32e7eSjoerg     //   %c = or i16 %a, %b
380306f32e7eSjoerg     // but until there is an example that actually needs this, it doesn't seem
380406f32e7eSjoerg     // worth worrying about.
380506f32e7eSjoerg     return nullptr;
380606f32e7eSjoerg   }
380706f32e7eSjoerg 
380806f32e7eSjoerg   // Handle 'null' ConstantArrayZero etc.
380906f32e7eSjoerg   if (C->isNullValue())
381006f32e7eSjoerg     return Constant::getNullValue(Type::getInt8Ty(Ctx));
381106f32e7eSjoerg 
381206f32e7eSjoerg   // Constant floating-point values can be handled as integer values if the
381306f32e7eSjoerg   // corresponding integer value is "byteable".  An important case is 0.0.
381406f32e7eSjoerg   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
381506f32e7eSjoerg     Type *Ty = nullptr;
381606f32e7eSjoerg     if (CFP->getType()->isHalfTy())
381706f32e7eSjoerg       Ty = Type::getInt16Ty(Ctx);
381806f32e7eSjoerg     else if (CFP->getType()->isFloatTy())
381906f32e7eSjoerg       Ty = Type::getInt32Ty(Ctx);
382006f32e7eSjoerg     else if (CFP->getType()->isDoubleTy())
382106f32e7eSjoerg       Ty = Type::getInt64Ty(Ctx);
382206f32e7eSjoerg     // Don't handle long double formats, which have strange constraints.
382306f32e7eSjoerg     return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL)
382406f32e7eSjoerg               : nullptr;
382506f32e7eSjoerg   }
382606f32e7eSjoerg 
382706f32e7eSjoerg   // We can handle constant integers that are multiple of 8 bits.
382806f32e7eSjoerg   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
382906f32e7eSjoerg     if (CI->getBitWidth() % 8 == 0) {
383006f32e7eSjoerg       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
383106f32e7eSjoerg       if (!CI->getValue().isSplat(8))
383206f32e7eSjoerg         return nullptr;
383306f32e7eSjoerg       return ConstantInt::get(Ctx, CI->getValue().trunc(8));
383406f32e7eSjoerg     }
383506f32e7eSjoerg   }
383606f32e7eSjoerg 
383706f32e7eSjoerg   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
383806f32e7eSjoerg     if (CE->getOpcode() == Instruction::IntToPtr) {
3839*da58b97aSjoerg       if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
3840*da58b97aSjoerg         unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
384106f32e7eSjoerg         return isBytewiseValue(
384206f32e7eSjoerg             ConstantExpr::getIntegerCast(CE->getOperand(0),
3843*da58b97aSjoerg                                          Type::getIntNTy(Ctx, BitWidth), false),
384406f32e7eSjoerg             DL);
384506f32e7eSjoerg       }
384606f32e7eSjoerg     }
3847*da58b97aSjoerg   }
384806f32e7eSjoerg 
384906f32e7eSjoerg   auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
385006f32e7eSjoerg     if (LHS == RHS)
385106f32e7eSjoerg       return LHS;
385206f32e7eSjoerg     if (!LHS || !RHS)
385306f32e7eSjoerg       return nullptr;
385406f32e7eSjoerg     if (LHS == UndefInt8)
385506f32e7eSjoerg       return RHS;
385606f32e7eSjoerg     if (RHS == UndefInt8)
385706f32e7eSjoerg       return LHS;
385806f32e7eSjoerg     return nullptr;
385906f32e7eSjoerg   };
386006f32e7eSjoerg 
386106f32e7eSjoerg   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
386206f32e7eSjoerg     Value *Val = UndefInt8;
386306f32e7eSjoerg     for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
386406f32e7eSjoerg       if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
386506f32e7eSjoerg         return nullptr;
386606f32e7eSjoerg     return Val;
386706f32e7eSjoerg   }
386806f32e7eSjoerg 
386906f32e7eSjoerg   if (isa<ConstantAggregate>(C)) {
387006f32e7eSjoerg     Value *Val = UndefInt8;
387106f32e7eSjoerg     for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
387206f32e7eSjoerg       if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL))))
387306f32e7eSjoerg         return nullptr;
387406f32e7eSjoerg     return Val;
387506f32e7eSjoerg   }
387606f32e7eSjoerg 
387706f32e7eSjoerg   // Don't try to handle the handful of other constants.
387806f32e7eSjoerg   return nullptr;
387906f32e7eSjoerg }
388006f32e7eSjoerg 
388106f32e7eSjoerg // This is the recursive version of BuildSubAggregate. It takes a few different
388206f32e7eSjoerg // arguments. Idxs is the index within the nested struct From that we are
388306f32e7eSjoerg // looking at now (which is of type IndexedType). IdxSkip is the number of
388406f32e7eSjoerg // indices from Idxs that should be left out when inserting into the resulting
388506f32e7eSjoerg // struct. To is the result struct built so far, new insertvalue instructions
388606f32e7eSjoerg // build on that.
BuildSubAggregate(Value * From,Value * To,Type * IndexedType,SmallVectorImpl<unsigned> & Idxs,unsigned IdxSkip,Instruction * InsertBefore)388706f32e7eSjoerg static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
388806f32e7eSjoerg                                 SmallVectorImpl<unsigned> &Idxs,
388906f32e7eSjoerg                                 unsigned IdxSkip,
389006f32e7eSjoerg                                 Instruction *InsertBefore) {
389106f32e7eSjoerg   StructType *STy = dyn_cast<StructType>(IndexedType);
389206f32e7eSjoerg   if (STy) {
389306f32e7eSjoerg     // Save the original To argument so we can modify it
389406f32e7eSjoerg     Value *OrigTo = To;
389506f32e7eSjoerg     // General case, the type indexed by Idxs is a struct
389606f32e7eSjoerg     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
389706f32e7eSjoerg       // Process each struct element recursively
389806f32e7eSjoerg       Idxs.push_back(i);
389906f32e7eSjoerg       Value *PrevTo = To;
390006f32e7eSjoerg       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
390106f32e7eSjoerg                              InsertBefore);
390206f32e7eSjoerg       Idxs.pop_back();
390306f32e7eSjoerg       if (!To) {
390406f32e7eSjoerg         // Couldn't find any inserted value for this index? Cleanup
390506f32e7eSjoerg         while (PrevTo != OrigTo) {
390606f32e7eSjoerg           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
390706f32e7eSjoerg           PrevTo = Del->getAggregateOperand();
390806f32e7eSjoerg           Del->eraseFromParent();
390906f32e7eSjoerg         }
391006f32e7eSjoerg         // Stop processing elements
391106f32e7eSjoerg         break;
391206f32e7eSjoerg       }
391306f32e7eSjoerg     }
391406f32e7eSjoerg     // If we successfully found a value for each of our subaggregates
391506f32e7eSjoerg     if (To)
391606f32e7eSjoerg       return To;
391706f32e7eSjoerg   }
391806f32e7eSjoerg   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
391906f32e7eSjoerg   // the struct's elements had a value that was inserted directly. In the latter
392006f32e7eSjoerg   // case, perhaps we can't determine each of the subelements individually, but
392106f32e7eSjoerg   // we might be able to find the complete struct somewhere.
392206f32e7eSjoerg 
392306f32e7eSjoerg   // Find the value that is at that particular spot
392406f32e7eSjoerg   Value *V = FindInsertedValue(From, Idxs);
392506f32e7eSjoerg 
392606f32e7eSjoerg   if (!V)
392706f32e7eSjoerg     return nullptr;
392806f32e7eSjoerg 
392906f32e7eSjoerg   // Insert the value in the new (sub) aggregate
393006f32e7eSjoerg   return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
393106f32e7eSjoerg                                  "tmp", InsertBefore);
393206f32e7eSjoerg }
393306f32e7eSjoerg 
393406f32e7eSjoerg // This helper takes a nested struct and extracts a part of it (which is again a
393506f32e7eSjoerg // struct) into a new value. For example, given the struct:
393606f32e7eSjoerg // { a, { b, { c, d }, e } }
393706f32e7eSjoerg // and the indices "1, 1" this returns
393806f32e7eSjoerg // { c, d }.
393906f32e7eSjoerg //
394006f32e7eSjoerg // It does this by inserting an insertvalue for each element in the resulting
394106f32e7eSjoerg // struct, as opposed to just inserting a single struct. This will only work if
394206f32e7eSjoerg // each of the elements of the substruct are known (ie, inserted into From by an
394306f32e7eSjoerg // insertvalue instruction somewhere).
394406f32e7eSjoerg //
394506f32e7eSjoerg // All inserted insertvalue instructions are inserted before InsertBefore
BuildSubAggregate(Value * From,ArrayRef<unsigned> idx_range,Instruction * InsertBefore)394606f32e7eSjoerg static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
394706f32e7eSjoerg                                 Instruction *InsertBefore) {
394806f32e7eSjoerg   assert(InsertBefore && "Must have someplace to insert!");
394906f32e7eSjoerg   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
395006f32e7eSjoerg                                                              idx_range);
395106f32e7eSjoerg   Value *To = UndefValue::get(IndexedType);
395206f32e7eSjoerg   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
395306f32e7eSjoerg   unsigned IdxSkip = Idxs.size();
395406f32e7eSjoerg 
395506f32e7eSjoerg   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
395606f32e7eSjoerg }
395706f32e7eSjoerg 
395806f32e7eSjoerg /// Given an aggregate and a sequence of indices, see if the scalar value
395906f32e7eSjoerg /// indexed is already around as a register, for example if it was inserted
396006f32e7eSjoerg /// directly into the aggregate.
396106f32e7eSjoerg ///
396206f32e7eSjoerg /// If InsertBefore is not null, this function will duplicate (modified)
396306f32e7eSjoerg /// insertvalues when a part of a nested struct is extracted.
FindInsertedValue(Value * V,ArrayRef<unsigned> idx_range,Instruction * InsertBefore)396406f32e7eSjoerg Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
396506f32e7eSjoerg                                Instruction *InsertBefore) {
396606f32e7eSjoerg   // Nothing to index? Just return V then (this is useful at the end of our
396706f32e7eSjoerg   // recursion).
396806f32e7eSjoerg   if (idx_range.empty())
396906f32e7eSjoerg     return V;
397006f32e7eSjoerg   // We have indices, so V should have an indexable type.
397106f32e7eSjoerg   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
397206f32e7eSjoerg          "Not looking at a struct or array?");
397306f32e7eSjoerg   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
397406f32e7eSjoerg          "Invalid indices for type?");
397506f32e7eSjoerg 
397606f32e7eSjoerg   if (Constant *C = dyn_cast<Constant>(V)) {
397706f32e7eSjoerg     C = C->getAggregateElement(idx_range[0]);
397806f32e7eSjoerg     if (!C) return nullptr;
397906f32e7eSjoerg     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
398006f32e7eSjoerg   }
398106f32e7eSjoerg 
398206f32e7eSjoerg   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
398306f32e7eSjoerg     // Loop the indices for the insertvalue instruction in parallel with the
398406f32e7eSjoerg     // requested indices
398506f32e7eSjoerg     const unsigned *req_idx = idx_range.begin();
398606f32e7eSjoerg     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
398706f32e7eSjoerg          i != e; ++i, ++req_idx) {
398806f32e7eSjoerg       if (req_idx == idx_range.end()) {
398906f32e7eSjoerg         // We can't handle this without inserting insertvalues
399006f32e7eSjoerg         if (!InsertBefore)
399106f32e7eSjoerg           return nullptr;
399206f32e7eSjoerg 
399306f32e7eSjoerg         // The requested index identifies a part of a nested aggregate. Handle
399406f32e7eSjoerg         // this specially. For example,
399506f32e7eSjoerg         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
399606f32e7eSjoerg         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
399706f32e7eSjoerg         // %C = extractvalue {i32, { i32, i32 } } %B, 1
399806f32e7eSjoerg         // This can be changed into
399906f32e7eSjoerg         // %A = insertvalue {i32, i32 } undef, i32 10, 0
400006f32e7eSjoerg         // %C = insertvalue {i32, i32 } %A, i32 11, 1
400106f32e7eSjoerg         // which allows the unused 0,0 element from the nested struct to be
400206f32e7eSjoerg         // removed.
400306f32e7eSjoerg         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
400406f32e7eSjoerg                                  InsertBefore);
400506f32e7eSjoerg       }
400606f32e7eSjoerg 
400706f32e7eSjoerg       // This insert value inserts something else than what we are looking for.
400806f32e7eSjoerg       // See if the (aggregate) value inserted into has the value we are
400906f32e7eSjoerg       // looking for, then.
401006f32e7eSjoerg       if (*req_idx != *i)
401106f32e7eSjoerg         return FindInsertedValue(I->getAggregateOperand(), idx_range,
401206f32e7eSjoerg                                  InsertBefore);
401306f32e7eSjoerg     }
401406f32e7eSjoerg     // If we end up here, the indices of the insertvalue match with those
401506f32e7eSjoerg     // requested (though possibly only partially). Now we recursively look at
401606f32e7eSjoerg     // the inserted value, passing any remaining indices.
401706f32e7eSjoerg     return FindInsertedValue(I->getInsertedValueOperand(),
401806f32e7eSjoerg                              makeArrayRef(req_idx, idx_range.end()),
401906f32e7eSjoerg                              InsertBefore);
402006f32e7eSjoerg   }
402106f32e7eSjoerg 
402206f32e7eSjoerg   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
402306f32e7eSjoerg     // If we're extracting a value from an aggregate that was extracted from
402406f32e7eSjoerg     // something else, we can extract from that something else directly instead.
402506f32e7eSjoerg     // However, we will need to chain I's indices with the requested indices.
402606f32e7eSjoerg 
402706f32e7eSjoerg     // Calculate the number of indices required
402806f32e7eSjoerg     unsigned size = I->getNumIndices() + idx_range.size();
402906f32e7eSjoerg     // Allocate some space to put the new indices in
403006f32e7eSjoerg     SmallVector<unsigned, 5> Idxs;
403106f32e7eSjoerg     Idxs.reserve(size);
403206f32e7eSjoerg     // Add indices from the extract value instruction
403306f32e7eSjoerg     Idxs.append(I->idx_begin(), I->idx_end());
403406f32e7eSjoerg 
403506f32e7eSjoerg     // Add requested indices
403606f32e7eSjoerg     Idxs.append(idx_range.begin(), idx_range.end());
403706f32e7eSjoerg 
403806f32e7eSjoerg     assert(Idxs.size() == size
403906f32e7eSjoerg            && "Number of indices added not correct?");
404006f32e7eSjoerg 
404106f32e7eSjoerg     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
404206f32e7eSjoerg   }
404306f32e7eSjoerg   // Otherwise, we don't know (such as, extracting from a function return value
404406f32e7eSjoerg   // or load instruction)
404506f32e7eSjoerg   return nullptr;
404606f32e7eSjoerg }
404706f32e7eSjoerg 
isGEPBasedOnPointerToString(const GEPOperator * GEP,unsigned CharSize)404806f32e7eSjoerg bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
404906f32e7eSjoerg                                        unsigned CharSize) {
405006f32e7eSjoerg   // Make sure the GEP has exactly three arguments.
405106f32e7eSjoerg   if (GEP->getNumOperands() != 3)
405206f32e7eSjoerg     return false;
405306f32e7eSjoerg 
405406f32e7eSjoerg   // Make sure the index-ee is a pointer to array of \p CharSize integers.
405506f32e7eSjoerg   // CharSize.
405606f32e7eSjoerg   ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
405706f32e7eSjoerg   if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
405806f32e7eSjoerg     return false;
405906f32e7eSjoerg 
406006f32e7eSjoerg   // Check to make sure that the first operand of the GEP is an integer and
406106f32e7eSjoerg   // has value 0 so that we are sure we're indexing into the initializer.
406206f32e7eSjoerg   const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
406306f32e7eSjoerg   if (!FirstIdx || !FirstIdx->isZero())
406406f32e7eSjoerg     return false;
406506f32e7eSjoerg 
406606f32e7eSjoerg   return true;
406706f32e7eSjoerg }
406806f32e7eSjoerg 
getConstantDataArrayInfo(const Value * V,ConstantDataArraySlice & Slice,unsigned ElementSize,uint64_t Offset)406906f32e7eSjoerg bool llvm::getConstantDataArrayInfo(const Value *V,
407006f32e7eSjoerg                                     ConstantDataArraySlice &Slice,
407106f32e7eSjoerg                                     unsigned ElementSize, uint64_t Offset) {
407206f32e7eSjoerg   assert(V);
407306f32e7eSjoerg 
407406f32e7eSjoerg   // Look through bitcast instructions and geps.
407506f32e7eSjoerg   V = V->stripPointerCasts();
407606f32e7eSjoerg 
407706f32e7eSjoerg   // If the value is a GEP instruction or constant expression, treat it as an
407806f32e7eSjoerg   // offset.
407906f32e7eSjoerg   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
408006f32e7eSjoerg     // The GEP operator should be based on a pointer to string constant, and is
408106f32e7eSjoerg     // indexing into the string constant.
408206f32e7eSjoerg     if (!isGEPBasedOnPointerToString(GEP, ElementSize))
408306f32e7eSjoerg       return false;
408406f32e7eSjoerg 
408506f32e7eSjoerg     // If the second index isn't a ConstantInt, then this is a variable index
408606f32e7eSjoerg     // into the array.  If this occurs, we can't say anything meaningful about
408706f32e7eSjoerg     // the string.
408806f32e7eSjoerg     uint64_t StartIdx = 0;
408906f32e7eSjoerg     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
409006f32e7eSjoerg       StartIdx = CI->getZExtValue();
409106f32e7eSjoerg     else
409206f32e7eSjoerg       return false;
409306f32e7eSjoerg     return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
409406f32e7eSjoerg                                     StartIdx + Offset);
409506f32e7eSjoerg   }
409606f32e7eSjoerg 
409706f32e7eSjoerg   // The GEP instruction, constant or instruction, must reference a global
409806f32e7eSjoerg   // variable that is a constant and is initialized. The referenced constant
409906f32e7eSjoerg   // initializer is the array that we'll use for optimization.
410006f32e7eSjoerg   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
410106f32e7eSjoerg   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
410206f32e7eSjoerg     return false;
410306f32e7eSjoerg 
410406f32e7eSjoerg   const ConstantDataArray *Array;
410506f32e7eSjoerg   ArrayType *ArrayTy;
410606f32e7eSjoerg   if (GV->getInitializer()->isNullValue()) {
410706f32e7eSjoerg     Type *GVTy = GV->getValueType();
410806f32e7eSjoerg     if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
410906f32e7eSjoerg       // A zeroinitializer for the array; there is no ConstantDataArray.
411006f32e7eSjoerg       Array = nullptr;
411106f32e7eSjoerg     } else {
411206f32e7eSjoerg       const DataLayout &DL = GV->getParent()->getDataLayout();
4113*da58b97aSjoerg       uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedSize();
411406f32e7eSjoerg       uint64_t Length = SizeInBytes / (ElementSize / 8);
411506f32e7eSjoerg       if (Length <= Offset)
411606f32e7eSjoerg         return false;
411706f32e7eSjoerg 
411806f32e7eSjoerg       Slice.Array = nullptr;
411906f32e7eSjoerg       Slice.Offset = 0;
412006f32e7eSjoerg       Slice.Length = Length - Offset;
412106f32e7eSjoerg       return true;
412206f32e7eSjoerg     }
412306f32e7eSjoerg   } else {
412406f32e7eSjoerg     // This must be a ConstantDataArray.
412506f32e7eSjoerg     Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
412606f32e7eSjoerg     if (!Array)
412706f32e7eSjoerg       return false;
412806f32e7eSjoerg     ArrayTy = Array->getType();
412906f32e7eSjoerg   }
413006f32e7eSjoerg   if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
413106f32e7eSjoerg     return false;
413206f32e7eSjoerg 
413306f32e7eSjoerg   uint64_t NumElts = ArrayTy->getArrayNumElements();
413406f32e7eSjoerg   if (Offset > NumElts)
413506f32e7eSjoerg     return false;
413606f32e7eSjoerg 
413706f32e7eSjoerg   Slice.Array = Array;
413806f32e7eSjoerg   Slice.Offset = Offset;
413906f32e7eSjoerg   Slice.Length = NumElts - Offset;
414006f32e7eSjoerg   return true;
414106f32e7eSjoerg }
414206f32e7eSjoerg 
414306f32e7eSjoerg /// This function computes the length of a null-terminated C string pointed to
414406f32e7eSjoerg /// by V. If successful, it returns true and returns the string in Str.
414506f32e7eSjoerg /// If unsuccessful, it returns false.
getConstantStringInfo(const Value * V,StringRef & Str,uint64_t Offset,bool TrimAtNul)414606f32e7eSjoerg bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
414706f32e7eSjoerg                                  uint64_t Offset, bool TrimAtNul) {
414806f32e7eSjoerg   ConstantDataArraySlice Slice;
414906f32e7eSjoerg   if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
415006f32e7eSjoerg     return false;
415106f32e7eSjoerg 
415206f32e7eSjoerg   if (Slice.Array == nullptr) {
415306f32e7eSjoerg     if (TrimAtNul) {
415406f32e7eSjoerg       Str = StringRef();
415506f32e7eSjoerg       return true;
415606f32e7eSjoerg     }
415706f32e7eSjoerg     if (Slice.Length == 1) {
415806f32e7eSjoerg       Str = StringRef("", 1);
415906f32e7eSjoerg       return true;
416006f32e7eSjoerg     }
416106f32e7eSjoerg     // We cannot instantiate a StringRef as we do not have an appropriate string
416206f32e7eSjoerg     // of 0s at hand.
416306f32e7eSjoerg     return false;
416406f32e7eSjoerg   }
416506f32e7eSjoerg 
416606f32e7eSjoerg   // Start out with the entire array in the StringRef.
416706f32e7eSjoerg   Str = Slice.Array->getAsString();
416806f32e7eSjoerg   // Skip over 'offset' bytes.
416906f32e7eSjoerg   Str = Str.substr(Slice.Offset);
417006f32e7eSjoerg 
417106f32e7eSjoerg   if (TrimAtNul) {
417206f32e7eSjoerg     // Trim off the \0 and anything after it.  If the array is not nul
417306f32e7eSjoerg     // terminated, we just return the whole end of string.  The client may know
417406f32e7eSjoerg     // some other way that the string is length-bound.
417506f32e7eSjoerg     Str = Str.substr(0, Str.find('\0'));
417606f32e7eSjoerg   }
417706f32e7eSjoerg   return true;
417806f32e7eSjoerg }
417906f32e7eSjoerg 
418006f32e7eSjoerg // These next two are very similar to the above, but also look through PHI
418106f32e7eSjoerg // nodes.
418206f32e7eSjoerg // TODO: See if we can integrate these two together.
418306f32e7eSjoerg 
418406f32e7eSjoerg /// If we can compute the length of the string pointed to by
418506f32e7eSjoerg /// the specified pointer, return 'len+1'.  If we can't, return 0.
GetStringLengthH(const Value * V,SmallPtrSetImpl<const PHINode * > & PHIs,unsigned CharSize)418606f32e7eSjoerg static uint64_t GetStringLengthH(const Value *V,
418706f32e7eSjoerg                                  SmallPtrSetImpl<const PHINode*> &PHIs,
418806f32e7eSjoerg                                  unsigned CharSize) {
418906f32e7eSjoerg   // Look through noop bitcast instructions.
419006f32e7eSjoerg   V = V->stripPointerCasts();
419106f32e7eSjoerg 
419206f32e7eSjoerg   // If this is a PHI node, there are two cases: either we have already seen it
419306f32e7eSjoerg   // or we haven't.
419406f32e7eSjoerg   if (const PHINode *PN = dyn_cast<PHINode>(V)) {
419506f32e7eSjoerg     if (!PHIs.insert(PN).second)
419606f32e7eSjoerg       return ~0ULL;  // already in the set.
419706f32e7eSjoerg 
419806f32e7eSjoerg     // If it was new, see if all the input strings are the same length.
419906f32e7eSjoerg     uint64_t LenSoFar = ~0ULL;
420006f32e7eSjoerg     for (Value *IncValue : PN->incoming_values()) {
420106f32e7eSjoerg       uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
420206f32e7eSjoerg       if (Len == 0) return 0; // Unknown length -> unknown.
420306f32e7eSjoerg 
420406f32e7eSjoerg       if (Len == ~0ULL) continue;
420506f32e7eSjoerg 
420606f32e7eSjoerg       if (Len != LenSoFar && LenSoFar != ~0ULL)
420706f32e7eSjoerg         return 0;    // Disagree -> unknown.
420806f32e7eSjoerg       LenSoFar = Len;
420906f32e7eSjoerg     }
421006f32e7eSjoerg 
421106f32e7eSjoerg     // Success, all agree.
421206f32e7eSjoerg     return LenSoFar;
421306f32e7eSjoerg   }
421406f32e7eSjoerg 
421506f32e7eSjoerg   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
421606f32e7eSjoerg   if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
421706f32e7eSjoerg     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
421806f32e7eSjoerg     if (Len1 == 0) return 0;
421906f32e7eSjoerg     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
422006f32e7eSjoerg     if (Len2 == 0) return 0;
422106f32e7eSjoerg     if (Len1 == ~0ULL) return Len2;
422206f32e7eSjoerg     if (Len2 == ~0ULL) return Len1;
422306f32e7eSjoerg     if (Len1 != Len2) return 0;
422406f32e7eSjoerg     return Len1;
422506f32e7eSjoerg   }
422606f32e7eSjoerg 
422706f32e7eSjoerg   // Otherwise, see if we can read the string.
422806f32e7eSjoerg   ConstantDataArraySlice Slice;
422906f32e7eSjoerg   if (!getConstantDataArrayInfo(V, Slice, CharSize))
423006f32e7eSjoerg     return 0;
423106f32e7eSjoerg 
423206f32e7eSjoerg   if (Slice.Array == nullptr)
423306f32e7eSjoerg     return 1;
423406f32e7eSjoerg 
423506f32e7eSjoerg   // Search for nul characters
423606f32e7eSjoerg   unsigned NullIndex = 0;
423706f32e7eSjoerg   for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
423806f32e7eSjoerg     if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
423906f32e7eSjoerg       break;
424006f32e7eSjoerg   }
424106f32e7eSjoerg 
424206f32e7eSjoerg   return NullIndex + 1;
424306f32e7eSjoerg }
424406f32e7eSjoerg 
424506f32e7eSjoerg /// If we can compute the length of the string pointed to by
424606f32e7eSjoerg /// the specified pointer, return 'len+1'.  If we can't, return 0.
GetStringLength(const Value * V,unsigned CharSize)424706f32e7eSjoerg uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
424806f32e7eSjoerg   if (!V->getType()->isPointerTy())
424906f32e7eSjoerg     return 0;
425006f32e7eSjoerg 
425106f32e7eSjoerg   SmallPtrSet<const PHINode*, 32> PHIs;
425206f32e7eSjoerg   uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
425306f32e7eSjoerg   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
425406f32e7eSjoerg   // an empty string as a length.
425506f32e7eSjoerg   return Len == ~0ULL ? 1 : Len;
425606f32e7eSjoerg }
425706f32e7eSjoerg 
425806f32e7eSjoerg const Value *
getArgumentAliasingToReturnedPointer(const CallBase * Call,bool MustPreserveNullness)425906f32e7eSjoerg llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call,
426006f32e7eSjoerg                                            bool MustPreserveNullness) {
426106f32e7eSjoerg   assert(Call &&
426206f32e7eSjoerg          "getArgumentAliasingToReturnedPointer only works on nonnull calls");
426306f32e7eSjoerg   if (const Value *RV = Call->getReturnedArgOperand())
426406f32e7eSjoerg     return RV;
426506f32e7eSjoerg   // This can be used only as a aliasing property.
426606f32e7eSjoerg   if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
426706f32e7eSjoerg           Call, MustPreserveNullness))
426806f32e7eSjoerg     return Call->getArgOperand(0);
426906f32e7eSjoerg   return nullptr;
427006f32e7eSjoerg }
427106f32e7eSjoerg 
isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase * Call,bool MustPreserveNullness)427206f32e7eSjoerg bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
427306f32e7eSjoerg     const CallBase *Call, bool MustPreserveNullness) {
4274*da58b97aSjoerg   switch (Call->getIntrinsicID()) {
4275*da58b97aSjoerg   case Intrinsic::launder_invariant_group:
4276*da58b97aSjoerg   case Intrinsic::strip_invariant_group:
4277*da58b97aSjoerg   case Intrinsic::aarch64_irg:
4278*da58b97aSjoerg   case Intrinsic::aarch64_tagp:
4279*da58b97aSjoerg     return true;
4280*da58b97aSjoerg   case Intrinsic::ptrmask:
4281*da58b97aSjoerg     return !MustPreserveNullness;
4282*da58b97aSjoerg   default:
4283*da58b97aSjoerg     return false;
4284*da58b97aSjoerg   }
428506f32e7eSjoerg }
428606f32e7eSjoerg 
428706f32e7eSjoerg /// \p PN defines a loop-variant pointer to an object.  Check if the
428806f32e7eSjoerg /// previous iteration of the loop was referring to the same object as \p PN.
isSameUnderlyingObjectInLoop(const PHINode * PN,const LoopInfo * LI)428906f32e7eSjoerg static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
429006f32e7eSjoerg                                          const LoopInfo *LI) {
429106f32e7eSjoerg   // Find the loop-defined value.
429206f32e7eSjoerg   Loop *L = LI->getLoopFor(PN->getParent());
429306f32e7eSjoerg   if (PN->getNumIncomingValues() != 2)
429406f32e7eSjoerg     return true;
429506f32e7eSjoerg 
429606f32e7eSjoerg   // Find the value from previous iteration.
429706f32e7eSjoerg   auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
429806f32e7eSjoerg   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
429906f32e7eSjoerg     PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
430006f32e7eSjoerg   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
430106f32e7eSjoerg     return true;
430206f32e7eSjoerg 
430306f32e7eSjoerg   // If a new pointer is loaded in the loop, the pointer references a different
430406f32e7eSjoerg   // object in every iteration.  E.g.:
430506f32e7eSjoerg   //    for (i)
430606f32e7eSjoerg   //       int *p = a[i];
430706f32e7eSjoerg   //       ...
430806f32e7eSjoerg   if (auto *Load = dyn_cast<LoadInst>(PrevValue))
430906f32e7eSjoerg     if (!L->isLoopInvariant(Load->getPointerOperand()))
431006f32e7eSjoerg       return false;
431106f32e7eSjoerg   return true;
431206f32e7eSjoerg }
431306f32e7eSjoerg 
getUnderlyingObject(const Value * V,unsigned MaxLookup)4314*da58b97aSjoerg const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
431506f32e7eSjoerg   if (!V->getType()->isPointerTy())
431606f32e7eSjoerg     return V;
431706f32e7eSjoerg   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
4318*da58b97aSjoerg     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
431906f32e7eSjoerg       V = GEP->getPointerOperand();
432006f32e7eSjoerg     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
432106f32e7eSjoerg                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
432206f32e7eSjoerg       V = cast<Operator>(V)->getOperand(0);
4323*da58b97aSjoerg       if (!V->getType()->isPointerTy())
4324*da58b97aSjoerg         return V;
4325*da58b97aSjoerg     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
432606f32e7eSjoerg       if (GA->isInterposable())
432706f32e7eSjoerg         return V;
432806f32e7eSjoerg       V = GA->getAliasee();
432906f32e7eSjoerg     } else {
4330*da58b97aSjoerg       if (auto *PHI = dyn_cast<PHINode>(V)) {
4331*da58b97aSjoerg         // Look through single-arg phi nodes created by LCSSA.
4332*da58b97aSjoerg         if (PHI->getNumIncomingValues() == 1) {
4333*da58b97aSjoerg           V = PHI->getIncomingValue(0);
4334*da58b97aSjoerg           continue;
4335*da58b97aSjoerg         }
4336*da58b97aSjoerg       } else if (auto *Call = dyn_cast<CallBase>(V)) {
433706f32e7eSjoerg         // CaptureTracking can know about special capturing properties of some
433806f32e7eSjoerg         // intrinsics like launder.invariant.group, that can't be expressed with
433906f32e7eSjoerg         // the attributes, but have properties like returning aliasing pointer.
434006f32e7eSjoerg         // Because some analysis may assume that nocaptured pointer is not
434106f32e7eSjoerg         // returned from some special intrinsic (because function would have to
434206f32e7eSjoerg         // be marked with returns attribute), it is crucial to use this function
434306f32e7eSjoerg         // because it should be in sync with CaptureTracking. Not using it may
434406f32e7eSjoerg         // cause weird miscompilations where 2 aliasing pointers are assumed to
434506f32e7eSjoerg         // noalias.
434606f32e7eSjoerg         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
434706f32e7eSjoerg           V = RP;
434806f32e7eSjoerg           continue;
434906f32e7eSjoerg         }
435006f32e7eSjoerg       }
435106f32e7eSjoerg 
435206f32e7eSjoerg       return V;
435306f32e7eSjoerg     }
435406f32e7eSjoerg     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
435506f32e7eSjoerg   }
435606f32e7eSjoerg   return V;
435706f32e7eSjoerg }
435806f32e7eSjoerg 
getUnderlyingObjects(const Value * V,SmallVectorImpl<const Value * > & Objects,LoopInfo * LI,unsigned MaxLookup)4359*da58b97aSjoerg void llvm::getUnderlyingObjects(const Value *V,
436006f32e7eSjoerg                                 SmallVectorImpl<const Value *> &Objects,
4361*da58b97aSjoerg                                 LoopInfo *LI, unsigned MaxLookup) {
436206f32e7eSjoerg   SmallPtrSet<const Value *, 4> Visited;
436306f32e7eSjoerg   SmallVector<const Value *, 4> Worklist;
436406f32e7eSjoerg   Worklist.push_back(V);
436506f32e7eSjoerg   do {
436606f32e7eSjoerg     const Value *P = Worklist.pop_back_val();
4367*da58b97aSjoerg     P = getUnderlyingObject(P, MaxLookup);
436806f32e7eSjoerg 
436906f32e7eSjoerg     if (!Visited.insert(P).second)
437006f32e7eSjoerg       continue;
437106f32e7eSjoerg 
437206f32e7eSjoerg     if (auto *SI = dyn_cast<SelectInst>(P)) {
437306f32e7eSjoerg       Worklist.push_back(SI->getTrueValue());
437406f32e7eSjoerg       Worklist.push_back(SI->getFalseValue());
437506f32e7eSjoerg       continue;
437606f32e7eSjoerg     }
437706f32e7eSjoerg 
437806f32e7eSjoerg     if (auto *PN = dyn_cast<PHINode>(P)) {
437906f32e7eSjoerg       // If this PHI changes the underlying object in every iteration of the
438006f32e7eSjoerg       // loop, don't look through it.  Consider:
438106f32e7eSjoerg       //   int **A;
438206f32e7eSjoerg       //   for (i) {
438306f32e7eSjoerg       //     Prev = Curr;     // Prev = PHI (Prev_0, Curr)
438406f32e7eSjoerg       //     Curr = A[i];
438506f32e7eSjoerg       //     *Prev, *Curr;
438606f32e7eSjoerg       //
438706f32e7eSjoerg       // Prev is tracking Curr one iteration behind so they refer to different
438806f32e7eSjoerg       // underlying objects.
438906f32e7eSjoerg       if (!LI || !LI->isLoopHeader(PN->getParent()) ||
439006f32e7eSjoerg           isSameUnderlyingObjectInLoop(PN, LI))
4391*da58b97aSjoerg         append_range(Worklist, PN->incoming_values());
439206f32e7eSjoerg       continue;
439306f32e7eSjoerg     }
439406f32e7eSjoerg 
439506f32e7eSjoerg     Objects.push_back(P);
439606f32e7eSjoerg   } while (!Worklist.empty());
439706f32e7eSjoerg }
439806f32e7eSjoerg 
439906f32e7eSjoerg /// This is the function that does the work of looking through basic
440006f32e7eSjoerg /// ptrtoint+arithmetic+inttoptr sequences.
getUnderlyingObjectFromInt(const Value * V)440106f32e7eSjoerg static const Value *getUnderlyingObjectFromInt(const Value *V) {
440206f32e7eSjoerg   do {
440306f32e7eSjoerg     if (const Operator *U = dyn_cast<Operator>(V)) {
440406f32e7eSjoerg       // If we find a ptrtoint, we can transfer control back to the
440506f32e7eSjoerg       // regular getUnderlyingObjectFromInt.
440606f32e7eSjoerg       if (U->getOpcode() == Instruction::PtrToInt)
440706f32e7eSjoerg         return U->getOperand(0);
440806f32e7eSjoerg       // If we find an add of a constant, a multiplied value, or a phi, it's
440906f32e7eSjoerg       // likely that the other operand will lead us to the base
441006f32e7eSjoerg       // object. We don't have to worry about the case where the
441106f32e7eSjoerg       // object address is somehow being computed by the multiply,
441206f32e7eSjoerg       // because our callers only care when the result is an
441306f32e7eSjoerg       // identifiable object.
441406f32e7eSjoerg       if (U->getOpcode() != Instruction::Add ||
441506f32e7eSjoerg           (!isa<ConstantInt>(U->getOperand(1)) &&
441606f32e7eSjoerg            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
441706f32e7eSjoerg            !isa<PHINode>(U->getOperand(1))))
441806f32e7eSjoerg         return V;
441906f32e7eSjoerg       V = U->getOperand(0);
442006f32e7eSjoerg     } else {
442106f32e7eSjoerg       return V;
442206f32e7eSjoerg     }
442306f32e7eSjoerg     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
442406f32e7eSjoerg   } while (true);
442506f32e7eSjoerg }
442606f32e7eSjoerg 
4427*da58b97aSjoerg /// This is a wrapper around getUnderlyingObjects and adds support for basic
442806f32e7eSjoerg /// ptrtoint+arithmetic+inttoptr sequences.
4429*da58b97aSjoerg /// It returns false if unidentified object is found in getUnderlyingObjects.
getUnderlyingObjectsForCodeGen(const Value * V,SmallVectorImpl<Value * > & Objects)443006f32e7eSjoerg bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
4431*da58b97aSjoerg                                           SmallVectorImpl<Value *> &Objects) {
443206f32e7eSjoerg   SmallPtrSet<const Value *, 16> Visited;
443306f32e7eSjoerg   SmallVector<const Value *, 4> Working(1, V);
443406f32e7eSjoerg   do {
443506f32e7eSjoerg     V = Working.pop_back_val();
443606f32e7eSjoerg 
443706f32e7eSjoerg     SmallVector<const Value *, 4> Objs;
4438*da58b97aSjoerg     getUnderlyingObjects(V, Objs);
443906f32e7eSjoerg 
444006f32e7eSjoerg     for (const Value *V : Objs) {
444106f32e7eSjoerg       if (!Visited.insert(V).second)
444206f32e7eSjoerg         continue;
444306f32e7eSjoerg       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
444406f32e7eSjoerg         const Value *O =
444506f32e7eSjoerg           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
444606f32e7eSjoerg         if (O->getType()->isPointerTy()) {
444706f32e7eSjoerg           Working.push_back(O);
444806f32e7eSjoerg           continue;
444906f32e7eSjoerg         }
445006f32e7eSjoerg       }
4451*da58b97aSjoerg       // If getUnderlyingObjects fails to find an identifiable object,
445206f32e7eSjoerg       // getUnderlyingObjectsForCodeGen also fails for safety.
445306f32e7eSjoerg       if (!isIdentifiedObject(V)) {
445406f32e7eSjoerg         Objects.clear();
445506f32e7eSjoerg         return false;
445606f32e7eSjoerg       }
445706f32e7eSjoerg       Objects.push_back(const_cast<Value *>(V));
445806f32e7eSjoerg     }
445906f32e7eSjoerg   } while (!Working.empty());
446006f32e7eSjoerg   return true;
446106f32e7eSjoerg }
446206f32e7eSjoerg 
findAllocaForValue(Value * V,bool OffsetZero)4463*da58b97aSjoerg AllocaInst *llvm::findAllocaForValue(Value *V, bool OffsetZero) {
4464*da58b97aSjoerg   AllocaInst *Result = nullptr;
4465*da58b97aSjoerg   SmallPtrSet<Value *, 4> Visited;
4466*da58b97aSjoerg   SmallVector<Value *, 4> Worklist;
4467*da58b97aSjoerg 
4468*da58b97aSjoerg   auto AddWork = [&](Value *V) {
4469*da58b97aSjoerg     if (Visited.insert(V).second)
4470*da58b97aSjoerg       Worklist.push_back(V);
4471*da58b97aSjoerg   };
4472*da58b97aSjoerg 
4473*da58b97aSjoerg   AddWork(V);
4474*da58b97aSjoerg   do {
4475*da58b97aSjoerg     V = Worklist.pop_back_val();
4476*da58b97aSjoerg     assert(Visited.count(V));
4477*da58b97aSjoerg 
4478*da58b97aSjoerg     if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
4479*da58b97aSjoerg       if (Result && Result != AI)
4480*da58b97aSjoerg         return nullptr;
4481*da58b97aSjoerg       Result = AI;
4482*da58b97aSjoerg     } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
4483*da58b97aSjoerg       AddWork(CI->getOperand(0));
4484*da58b97aSjoerg     } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
4485*da58b97aSjoerg       for (Value *IncValue : PN->incoming_values())
4486*da58b97aSjoerg         AddWork(IncValue);
4487*da58b97aSjoerg     } else if (auto *SI = dyn_cast<SelectInst>(V)) {
4488*da58b97aSjoerg       AddWork(SI->getTrueValue());
4489*da58b97aSjoerg       AddWork(SI->getFalseValue());
4490*da58b97aSjoerg     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
4491*da58b97aSjoerg       if (OffsetZero && !GEP->hasAllZeroIndices())
4492*da58b97aSjoerg         return nullptr;
4493*da58b97aSjoerg       AddWork(GEP->getPointerOperand());
4494*da58b97aSjoerg     } else {
4495*da58b97aSjoerg       return nullptr;
4496*da58b97aSjoerg     }
4497*da58b97aSjoerg   } while (!Worklist.empty());
4498*da58b97aSjoerg 
4499*da58b97aSjoerg   return Result;
4500*da58b97aSjoerg }
4501*da58b97aSjoerg 
onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value * V,bool AllowLifetime,bool AllowDroppable)4502*da58b97aSjoerg static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4503*da58b97aSjoerg     const Value *V, bool AllowLifetime, bool AllowDroppable) {
450406f32e7eSjoerg   for (const User *U : V->users()) {
450506f32e7eSjoerg     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
4506*da58b97aSjoerg     if (!II)
4507*da58b97aSjoerg       return false;
450806f32e7eSjoerg 
4509*da58b97aSjoerg     if (AllowLifetime && II->isLifetimeStartOrEnd())
4510*da58b97aSjoerg       continue;
4511*da58b97aSjoerg 
4512*da58b97aSjoerg     if (AllowDroppable && II->isDroppable())
4513*da58b97aSjoerg       continue;
4514*da58b97aSjoerg 
451506f32e7eSjoerg     return false;
451606f32e7eSjoerg   }
451706f32e7eSjoerg   return true;
451806f32e7eSjoerg }
451906f32e7eSjoerg 
onlyUsedByLifetimeMarkers(const Value * V)4520*da58b97aSjoerg bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
4521*da58b97aSjoerg   return onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4522*da58b97aSjoerg       V, /* AllowLifetime */ true, /* AllowDroppable */ false);
4523*da58b97aSjoerg }
onlyUsedByLifetimeMarkersOrDroppableInsts(const Value * V)4524*da58b97aSjoerg bool llvm::onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V) {
4525*da58b97aSjoerg   return onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4526*da58b97aSjoerg       V, /* AllowLifetime */ true, /* AllowDroppable */ true);
4527*da58b97aSjoerg }
4528*da58b97aSjoerg 
mustSuppressSpeculation(const LoadInst & LI)452906f32e7eSjoerg bool llvm::mustSuppressSpeculation(const LoadInst &LI) {
453006f32e7eSjoerg   if (!LI.isUnordered())
453106f32e7eSjoerg     return true;
453206f32e7eSjoerg   const Function &F = *LI.getFunction();
453306f32e7eSjoerg   // Speculative load may create a race that did not exist in the source.
453406f32e7eSjoerg   return F.hasFnAttribute(Attribute::SanitizeThread) ||
453506f32e7eSjoerg     // Speculative load may load data from dirty regions.
453606f32e7eSjoerg     F.hasFnAttribute(Attribute::SanitizeAddress) ||
453706f32e7eSjoerg     F.hasFnAttribute(Attribute::SanitizeHWAddress);
453806f32e7eSjoerg }
453906f32e7eSjoerg 
454006f32e7eSjoerg 
isSafeToSpeculativelyExecute(const Value * V,const Instruction * CtxI,const DominatorTree * DT,const TargetLibraryInfo * TLI)454106f32e7eSjoerg bool llvm::isSafeToSpeculativelyExecute(const Value *V,
454206f32e7eSjoerg                                         const Instruction *CtxI,
4543*da58b97aSjoerg                                         const DominatorTree *DT,
4544*da58b97aSjoerg                                         const TargetLibraryInfo *TLI) {
454506f32e7eSjoerg   const Operator *Inst = dyn_cast<Operator>(V);
454606f32e7eSjoerg   if (!Inst)
454706f32e7eSjoerg     return false;
454806f32e7eSjoerg 
454906f32e7eSjoerg   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
455006f32e7eSjoerg     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
455106f32e7eSjoerg       if (C->canTrap())
455206f32e7eSjoerg         return false;
455306f32e7eSjoerg 
455406f32e7eSjoerg   switch (Inst->getOpcode()) {
455506f32e7eSjoerg   default:
455606f32e7eSjoerg     return true;
455706f32e7eSjoerg   case Instruction::UDiv:
455806f32e7eSjoerg   case Instruction::URem: {
455906f32e7eSjoerg     // x / y is undefined if y == 0.
456006f32e7eSjoerg     const APInt *V;
456106f32e7eSjoerg     if (match(Inst->getOperand(1), m_APInt(V)))
456206f32e7eSjoerg       return *V != 0;
456306f32e7eSjoerg     return false;
456406f32e7eSjoerg   }
456506f32e7eSjoerg   case Instruction::SDiv:
456606f32e7eSjoerg   case Instruction::SRem: {
456706f32e7eSjoerg     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
456806f32e7eSjoerg     const APInt *Numerator, *Denominator;
456906f32e7eSjoerg     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
457006f32e7eSjoerg       return false;
457106f32e7eSjoerg     // We cannot hoist this division if the denominator is 0.
457206f32e7eSjoerg     if (*Denominator == 0)
457306f32e7eSjoerg       return false;
457406f32e7eSjoerg     // It's safe to hoist if the denominator is not 0 or -1.
4575*da58b97aSjoerg     if (!Denominator->isAllOnesValue())
457606f32e7eSjoerg       return true;
457706f32e7eSjoerg     // At this point we know that the denominator is -1.  It is safe to hoist as
457806f32e7eSjoerg     // long we know that the numerator is not INT_MIN.
457906f32e7eSjoerg     if (match(Inst->getOperand(0), m_APInt(Numerator)))
458006f32e7eSjoerg       return !Numerator->isMinSignedValue();
458106f32e7eSjoerg     // The numerator *might* be MinSignedValue.
458206f32e7eSjoerg     return false;
458306f32e7eSjoerg   }
458406f32e7eSjoerg   case Instruction::Load: {
458506f32e7eSjoerg     const LoadInst *LI = cast<LoadInst>(Inst);
458606f32e7eSjoerg     if (mustSuppressSpeculation(*LI))
458706f32e7eSjoerg       return false;
458806f32e7eSjoerg     const DataLayout &DL = LI->getModule()->getDataLayout();
458906f32e7eSjoerg     return isDereferenceableAndAlignedPointer(
459006f32e7eSjoerg         LI->getPointerOperand(), LI->getType(), MaybeAlign(LI->getAlignment()),
4591*da58b97aSjoerg         DL, CtxI, DT, TLI);
459206f32e7eSjoerg   }
459306f32e7eSjoerg   case Instruction::Call: {
459406f32e7eSjoerg     auto *CI = cast<const CallInst>(Inst);
459506f32e7eSjoerg     const Function *Callee = CI->getCalledFunction();
459606f32e7eSjoerg 
459706f32e7eSjoerg     // The called function could have undefined behavior or side-effects, even
459806f32e7eSjoerg     // if marked readnone nounwind.
459906f32e7eSjoerg     return Callee && Callee->isSpeculatable();
460006f32e7eSjoerg   }
460106f32e7eSjoerg   case Instruction::VAArg:
460206f32e7eSjoerg   case Instruction::Alloca:
460306f32e7eSjoerg   case Instruction::Invoke:
460406f32e7eSjoerg   case Instruction::CallBr:
460506f32e7eSjoerg   case Instruction::PHI:
460606f32e7eSjoerg   case Instruction::Store:
460706f32e7eSjoerg   case Instruction::Ret:
460806f32e7eSjoerg   case Instruction::Br:
460906f32e7eSjoerg   case Instruction::IndirectBr:
461006f32e7eSjoerg   case Instruction::Switch:
461106f32e7eSjoerg   case Instruction::Unreachable:
461206f32e7eSjoerg   case Instruction::Fence:
461306f32e7eSjoerg   case Instruction::AtomicRMW:
461406f32e7eSjoerg   case Instruction::AtomicCmpXchg:
461506f32e7eSjoerg   case Instruction::LandingPad:
461606f32e7eSjoerg   case Instruction::Resume:
461706f32e7eSjoerg   case Instruction::CatchSwitch:
461806f32e7eSjoerg   case Instruction::CatchPad:
461906f32e7eSjoerg   case Instruction::CatchRet:
462006f32e7eSjoerg   case Instruction::CleanupPad:
462106f32e7eSjoerg   case Instruction::CleanupRet:
462206f32e7eSjoerg     return false; // Misc instructions which have effects
462306f32e7eSjoerg   }
462406f32e7eSjoerg }
462506f32e7eSjoerg 
mayBeMemoryDependent(const Instruction & I)462606f32e7eSjoerg bool llvm::mayBeMemoryDependent(const Instruction &I) {
462706f32e7eSjoerg   return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
462806f32e7eSjoerg }
462906f32e7eSjoerg 
463006f32e7eSjoerg /// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
mapOverflowResult(ConstantRange::OverflowResult OR)463106f32e7eSjoerg static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
463206f32e7eSjoerg   switch (OR) {
463306f32e7eSjoerg     case ConstantRange::OverflowResult::MayOverflow:
463406f32e7eSjoerg       return OverflowResult::MayOverflow;
463506f32e7eSjoerg     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
463606f32e7eSjoerg       return OverflowResult::AlwaysOverflowsLow;
463706f32e7eSjoerg     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
463806f32e7eSjoerg       return OverflowResult::AlwaysOverflowsHigh;
463906f32e7eSjoerg     case ConstantRange::OverflowResult::NeverOverflows:
464006f32e7eSjoerg       return OverflowResult::NeverOverflows;
464106f32e7eSjoerg   }
464206f32e7eSjoerg   llvm_unreachable("Unknown OverflowResult");
464306f32e7eSjoerg }
464406f32e7eSjoerg 
464506f32e7eSjoerg /// Combine constant ranges from computeConstantRange() and computeKnownBits().
computeConstantRangeIncludingKnownBits(const Value * V,bool ForSigned,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,OptimizationRemarkEmitter * ORE=nullptr,bool UseInstrInfo=true)464606f32e7eSjoerg static ConstantRange computeConstantRangeIncludingKnownBits(
464706f32e7eSjoerg     const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
464806f32e7eSjoerg     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
464906f32e7eSjoerg     OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
465006f32e7eSjoerg   KnownBits Known = computeKnownBits(
465106f32e7eSjoerg       V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
465206f32e7eSjoerg   ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
465306f32e7eSjoerg   ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
465406f32e7eSjoerg   ConstantRange::PreferredRangeType RangeType =
465506f32e7eSjoerg       ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
465606f32e7eSjoerg   return CR1.intersectWith(CR2, RangeType);
465706f32e7eSjoerg }
465806f32e7eSjoerg 
computeOverflowForUnsignedMul(const Value * LHS,const Value * RHS,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)465906f32e7eSjoerg OverflowResult llvm::computeOverflowForUnsignedMul(
466006f32e7eSjoerg     const Value *LHS, const Value *RHS, const DataLayout &DL,
466106f32e7eSjoerg     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
466206f32e7eSjoerg     bool UseInstrInfo) {
466306f32e7eSjoerg   KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
466406f32e7eSjoerg                                         nullptr, UseInstrInfo);
466506f32e7eSjoerg   KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
466606f32e7eSjoerg                                         nullptr, UseInstrInfo);
466706f32e7eSjoerg   ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
466806f32e7eSjoerg   ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
466906f32e7eSjoerg   return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
467006f32e7eSjoerg }
467106f32e7eSjoerg 
467206f32e7eSjoerg OverflowResult
computeOverflowForSignedMul(const Value * LHS,const Value * RHS,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)467306f32e7eSjoerg llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
467406f32e7eSjoerg                                   const DataLayout &DL, AssumptionCache *AC,
467506f32e7eSjoerg                                   const Instruction *CxtI,
467606f32e7eSjoerg                                   const DominatorTree *DT, bool UseInstrInfo) {
467706f32e7eSjoerg   // Multiplying n * m significant bits yields a result of n + m significant
467806f32e7eSjoerg   // bits. If the total number of significant bits does not exceed the
467906f32e7eSjoerg   // result bit width (minus 1), there is no overflow.
468006f32e7eSjoerg   // This means if we have enough leading sign bits in the operands
468106f32e7eSjoerg   // we can guarantee that the result does not overflow.
468206f32e7eSjoerg   // Ref: "Hacker's Delight" by Henry Warren
468306f32e7eSjoerg   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
468406f32e7eSjoerg 
468506f32e7eSjoerg   // Note that underestimating the number of sign bits gives a more
468606f32e7eSjoerg   // conservative answer.
468706f32e7eSjoerg   unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
468806f32e7eSjoerg                       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
468906f32e7eSjoerg 
469006f32e7eSjoerg   // First handle the easy case: if we have enough sign bits there's
469106f32e7eSjoerg   // definitely no overflow.
469206f32e7eSjoerg   if (SignBits > BitWidth + 1)
469306f32e7eSjoerg     return OverflowResult::NeverOverflows;
469406f32e7eSjoerg 
469506f32e7eSjoerg   // There are two ambiguous cases where there can be no overflow:
469606f32e7eSjoerg   //   SignBits == BitWidth + 1    and
469706f32e7eSjoerg   //   SignBits == BitWidth
469806f32e7eSjoerg   // The second case is difficult to check, therefore we only handle the
469906f32e7eSjoerg   // first case.
470006f32e7eSjoerg   if (SignBits == BitWidth + 1) {
470106f32e7eSjoerg     // It overflows only when both arguments are negative and the true
470206f32e7eSjoerg     // product is exactly the minimum negative number.
470306f32e7eSjoerg     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
470406f32e7eSjoerg     // For simplicity we just check if at least one side is not negative.
470506f32e7eSjoerg     KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
470606f32e7eSjoerg                                           nullptr, UseInstrInfo);
470706f32e7eSjoerg     KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
470806f32e7eSjoerg                                           nullptr, UseInstrInfo);
470906f32e7eSjoerg     if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
471006f32e7eSjoerg       return OverflowResult::NeverOverflows;
471106f32e7eSjoerg   }
471206f32e7eSjoerg   return OverflowResult::MayOverflow;
471306f32e7eSjoerg }
471406f32e7eSjoerg 
computeOverflowForUnsignedAdd(const Value * LHS,const Value * RHS,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT,bool UseInstrInfo)471506f32e7eSjoerg OverflowResult llvm::computeOverflowForUnsignedAdd(
471606f32e7eSjoerg     const Value *LHS, const Value *RHS, const DataLayout &DL,
471706f32e7eSjoerg     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
471806f32e7eSjoerg     bool UseInstrInfo) {
471906f32e7eSjoerg   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
472006f32e7eSjoerg       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
472106f32e7eSjoerg       nullptr, UseInstrInfo);
472206f32e7eSjoerg   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
472306f32e7eSjoerg       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
472406f32e7eSjoerg       nullptr, UseInstrInfo);
472506f32e7eSjoerg   return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
472606f32e7eSjoerg }
472706f32e7eSjoerg 
computeOverflowForSignedAdd(const Value * LHS,const Value * RHS,const AddOperator * Add,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT)472806f32e7eSjoerg static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
472906f32e7eSjoerg                                                   const Value *RHS,
473006f32e7eSjoerg                                                   const AddOperator *Add,
473106f32e7eSjoerg                                                   const DataLayout &DL,
473206f32e7eSjoerg                                                   AssumptionCache *AC,
473306f32e7eSjoerg                                                   const Instruction *CxtI,
473406f32e7eSjoerg                                                   const DominatorTree *DT) {
473506f32e7eSjoerg   if (Add && Add->hasNoSignedWrap()) {
473606f32e7eSjoerg     return OverflowResult::NeverOverflows;
473706f32e7eSjoerg   }
473806f32e7eSjoerg 
473906f32e7eSjoerg   // If LHS and RHS each have at least two sign bits, the addition will look
474006f32e7eSjoerg   // like
474106f32e7eSjoerg   //
474206f32e7eSjoerg   // XX..... +
474306f32e7eSjoerg   // YY.....
474406f32e7eSjoerg   //
474506f32e7eSjoerg   // If the carry into the most significant position is 0, X and Y can't both
474606f32e7eSjoerg   // be 1 and therefore the carry out of the addition is also 0.
474706f32e7eSjoerg   //
474806f32e7eSjoerg   // If the carry into the most significant position is 1, X and Y can't both
474906f32e7eSjoerg   // be 0 and therefore the carry out of the addition is also 1.
475006f32e7eSjoerg   //
475106f32e7eSjoerg   // Since the carry into the most significant position is always equal to
475206f32e7eSjoerg   // the carry out of the addition, there is no signed overflow.
475306f32e7eSjoerg   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
475406f32e7eSjoerg       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
475506f32e7eSjoerg     return OverflowResult::NeverOverflows;
475606f32e7eSjoerg 
475706f32e7eSjoerg   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
475806f32e7eSjoerg       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
475906f32e7eSjoerg   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
476006f32e7eSjoerg       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
476106f32e7eSjoerg   OverflowResult OR =
476206f32e7eSjoerg       mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
476306f32e7eSjoerg   if (OR != OverflowResult::MayOverflow)
476406f32e7eSjoerg     return OR;
476506f32e7eSjoerg 
476606f32e7eSjoerg   // The remaining code needs Add to be available. Early returns if not so.
476706f32e7eSjoerg   if (!Add)
476806f32e7eSjoerg     return OverflowResult::MayOverflow;
476906f32e7eSjoerg 
477006f32e7eSjoerg   // If the sign of Add is the same as at least one of the operands, this add
477106f32e7eSjoerg   // CANNOT overflow. If this can be determined from the known bits of the
477206f32e7eSjoerg   // operands the above signedAddMayOverflow() check will have already done so.
477306f32e7eSjoerg   // The only other way to improve on the known bits is from an assumption, so
477406f32e7eSjoerg   // call computeKnownBitsFromAssume() directly.
477506f32e7eSjoerg   bool LHSOrRHSKnownNonNegative =
477606f32e7eSjoerg       (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
477706f32e7eSjoerg   bool LHSOrRHSKnownNegative =
477806f32e7eSjoerg       (LHSRange.isAllNegative() || RHSRange.isAllNegative());
477906f32e7eSjoerg   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
478006f32e7eSjoerg     KnownBits AddKnown(LHSRange.getBitWidth());
478106f32e7eSjoerg     computeKnownBitsFromAssume(
478206f32e7eSjoerg         Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
478306f32e7eSjoerg     if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
478406f32e7eSjoerg         (AddKnown.isNegative() && LHSOrRHSKnownNegative))
478506f32e7eSjoerg       return OverflowResult::NeverOverflows;
478606f32e7eSjoerg   }
478706f32e7eSjoerg 
478806f32e7eSjoerg   return OverflowResult::MayOverflow;
478906f32e7eSjoerg }
479006f32e7eSjoerg 
computeOverflowForUnsignedSub(const Value * LHS,const Value * RHS,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT)479106f32e7eSjoerg OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
479206f32e7eSjoerg                                                    const Value *RHS,
479306f32e7eSjoerg                                                    const DataLayout &DL,
479406f32e7eSjoerg                                                    AssumptionCache *AC,
479506f32e7eSjoerg                                                    const Instruction *CxtI,
479606f32e7eSjoerg                                                    const DominatorTree *DT) {
4797*da58b97aSjoerg   // Checking for conditions implied by dominating conditions may be expensive.
4798*da58b97aSjoerg   // Limit it to usub_with_overflow calls for now.
4799*da58b97aSjoerg   if (match(CxtI,
4800*da58b97aSjoerg             m_Intrinsic<Intrinsic::usub_with_overflow>(m_Value(), m_Value())))
4801*da58b97aSjoerg     if (auto C =
4802*da58b97aSjoerg             isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, CxtI, DL)) {
4803*da58b97aSjoerg       if (*C)
4804*da58b97aSjoerg         return OverflowResult::NeverOverflows;
4805*da58b97aSjoerg       return OverflowResult::AlwaysOverflowsLow;
4806*da58b97aSjoerg     }
480706f32e7eSjoerg   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
480806f32e7eSjoerg       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
480906f32e7eSjoerg   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
481006f32e7eSjoerg       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
481106f32e7eSjoerg   return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
481206f32e7eSjoerg }
481306f32e7eSjoerg 
computeOverflowForSignedSub(const Value * LHS,const Value * RHS,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT)481406f32e7eSjoerg OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
481506f32e7eSjoerg                                                  const Value *RHS,
481606f32e7eSjoerg                                                  const DataLayout &DL,
481706f32e7eSjoerg                                                  AssumptionCache *AC,
481806f32e7eSjoerg                                                  const Instruction *CxtI,
481906f32e7eSjoerg                                                  const DominatorTree *DT) {
482006f32e7eSjoerg   // If LHS and RHS each have at least two sign bits, the subtraction
482106f32e7eSjoerg   // cannot overflow.
482206f32e7eSjoerg   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
482306f32e7eSjoerg       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
482406f32e7eSjoerg     return OverflowResult::NeverOverflows;
482506f32e7eSjoerg 
482606f32e7eSjoerg   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
482706f32e7eSjoerg       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
482806f32e7eSjoerg   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
482906f32e7eSjoerg       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
483006f32e7eSjoerg   return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
483106f32e7eSjoerg }
483206f32e7eSjoerg 
isOverflowIntrinsicNoWrap(const WithOverflowInst * WO,const DominatorTree & DT)483306f32e7eSjoerg bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
483406f32e7eSjoerg                                      const DominatorTree &DT) {
483506f32e7eSjoerg   SmallVector<const BranchInst *, 2> GuardingBranches;
483606f32e7eSjoerg   SmallVector<const ExtractValueInst *, 2> Results;
483706f32e7eSjoerg 
483806f32e7eSjoerg   for (const User *U : WO->users()) {
483906f32e7eSjoerg     if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
484006f32e7eSjoerg       assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
484106f32e7eSjoerg 
484206f32e7eSjoerg       if (EVI->getIndices()[0] == 0)
484306f32e7eSjoerg         Results.push_back(EVI);
484406f32e7eSjoerg       else {
484506f32e7eSjoerg         assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
484606f32e7eSjoerg 
484706f32e7eSjoerg         for (const auto *U : EVI->users())
484806f32e7eSjoerg           if (const auto *B = dyn_cast<BranchInst>(U)) {
484906f32e7eSjoerg             assert(B->isConditional() && "How else is it using an i1?");
485006f32e7eSjoerg             GuardingBranches.push_back(B);
485106f32e7eSjoerg           }
485206f32e7eSjoerg       }
485306f32e7eSjoerg     } else {
485406f32e7eSjoerg       // We are using the aggregate directly in a way we don't want to analyze
485506f32e7eSjoerg       // here (storing it to a global, say).
485606f32e7eSjoerg       return false;
485706f32e7eSjoerg     }
485806f32e7eSjoerg   }
485906f32e7eSjoerg 
486006f32e7eSjoerg   auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
486106f32e7eSjoerg     BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
486206f32e7eSjoerg     if (!NoWrapEdge.isSingleEdge())
486306f32e7eSjoerg       return false;
486406f32e7eSjoerg 
486506f32e7eSjoerg     // Check if all users of the add are provably no-wrap.
486606f32e7eSjoerg     for (const auto *Result : Results) {
486706f32e7eSjoerg       // If the extractvalue itself is not executed on overflow, the we don't
486806f32e7eSjoerg       // need to check each use separately, since domination is transitive.
486906f32e7eSjoerg       if (DT.dominates(NoWrapEdge, Result->getParent()))
487006f32e7eSjoerg         continue;
487106f32e7eSjoerg 
487206f32e7eSjoerg       for (auto &RU : Result->uses())
487306f32e7eSjoerg         if (!DT.dominates(NoWrapEdge, RU))
487406f32e7eSjoerg           return false;
487506f32e7eSjoerg     }
487606f32e7eSjoerg 
487706f32e7eSjoerg     return true;
487806f32e7eSjoerg   };
487906f32e7eSjoerg 
488006f32e7eSjoerg   return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
488106f32e7eSjoerg }
488206f32e7eSjoerg 
canCreateUndefOrPoison(const Operator * Op,bool PoisonOnly)4883*da58b97aSjoerg static bool canCreateUndefOrPoison(const Operator *Op, bool PoisonOnly) {
4884*da58b97aSjoerg   // See whether I has flags that may create poison
4885*da58b97aSjoerg   if (const auto *OvOp = dyn_cast<OverflowingBinaryOperator>(Op)) {
4886*da58b97aSjoerg     if (OvOp->hasNoSignedWrap() || OvOp->hasNoUnsignedWrap())
4887*da58b97aSjoerg       return true;
4888*da58b97aSjoerg   }
4889*da58b97aSjoerg   if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(Op))
4890*da58b97aSjoerg     if (ExactOp->isExact())
4891*da58b97aSjoerg       return true;
4892*da58b97aSjoerg   if (const auto *FP = dyn_cast<FPMathOperator>(Op)) {
4893*da58b97aSjoerg     auto FMF = FP->getFastMathFlags();
4894*da58b97aSjoerg     if (FMF.noNaNs() || FMF.noInfs())
4895*da58b97aSjoerg       return true;
4896*da58b97aSjoerg   }
4897*da58b97aSjoerg 
4898*da58b97aSjoerg   unsigned Opcode = Op->getOpcode();
4899*da58b97aSjoerg 
4900*da58b97aSjoerg   // Check whether opcode is a poison/undef-generating operation
4901*da58b97aSjoerg   switch (Opcode) {
4902*da58b97aSjoerg   case Instruction::Shl:
4903*da58b97aSjoerg   case Instruction::AShr:
4904*da58b97aSjoerg   case Instruction::LShr: {
4905*da58b97aSjoerg     // Shifts return poison if shiftwidth is larger than the bitwidth.
4906*da58b97aSjoerg     if (auto *C = dyn_cast<Constant>(Op->getOperand(1))) {
4907*da58b97aSjoerg       SmallVector<Constant *, 4> ShiftAmounts;
4908*da58b97aSjoerg       if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
4909*da58b97aSjoerg         unsigned NumElts = FVTy->getNumElements();
4910*da58b97aSjoerg         for (unsigned i = 0; i < NumElts; ++i)
4911*da58b97aSjoerg           ShiftAmounts.push_back(C->getAggregateElement(i));
4912*da58b97aSjoerg       } else if (isa<ScalableVectorType>(C->getType()))
4913*da58b97aSjoerg         return true; // Can't tell, just return true to be safe
4914*da58b97aSjoerg       else
4915*da58b97aSjoerg         ShiftAmounts.push_back(C);
4916*da58b97aSjoerg 
4917*da58b97aSjoerg       bool Safe = llvm::all_of(ShiftAmounts, [](Constant *C) {
4918*da58b97aSjoerg         auto *CI = dyn_cast_or_null<ConstantInt>(C);
4919*da58b97aSjoerg         return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
4920*da58b97aSjoerg       });
4921*da58b97aSjoerg       return !Safe;
4922*da58b97aSjoerg     }
4923*da58b97aSjoerg     return true;
4924*da58b97aSjoerg   }
4925*da58b97aSjoerg   case Instruction::FPToSI:
4926*da58b97aSjoerg   case Instruction::FPToUI:
4927*da58b97aSjoerg     // fptosi/ui yields poison if the resulting value does not fit in the
4928*da58b97aSjoerg     // destination type.
4929*da58b97aSjoerg     return true;
4930*da58b97aSjoerg   case Instruction::Call:
4931*da58b97aSjoerg     if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
4932*da58b97aSjoerg       switch (II->getIntrinsicID()) {
4933*da58b97aSjoerg       // TODO: Add more intrinsics.
4934*da58b97aSjoerg       case Intrinsic::ctpop:
4935*da58b97aSjoerg       case Intrinsic::sadd_with_overflow:
4936*da58b97aSjoerg       case Intrinsic::ssub_with_overflow:
4937*da58b97aSjoerg       case Intrinsic::smul_with_overflow:
4938*da58b97aSjoerg       case Intrinsic::uadd_with_overflow:
4939*da58b97aSjoerg       case Intrinsic::usub_with_overflow:
4940*da58b97aSjoerg       case Intrinsic::umul_with_overflow:
4941*da58b97aSjoerg         return false;
4942*da58b97aSjoerg       }
4943*da58b97aSjoerg     }
4944*da58b97aSjoerg     LLVM_FALLTHROUGH;
4945*da58b97aSjoerg   case Instruction::CallBr:
4946*da58b97aSjoerg   case Instruction::Invoke: {
4947*da58b97aSjoerg     const auto *CB = cast<CallBase>(Op);
4948*da58b97aSjoerg     return !CB->hasRetAttr(Attribute::NoUndef);
4949*da58b97aSjoerg   }
4950*da58b97aSjoerg   case Instruction::InsertElement:
4951*da58b97aSjoerg   case Instruction::ExtractElement: {
4952*da58b97aSjoerg     // If index exceeds the length of the vector, it returns poison
4953*da58b97aSjoerg     auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
4954*da58b97aSjoerg     unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
4955*da58b97aSjoerg     auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
4956*da58b97aSjoerg     if (!Idx || Idx->getValue().uge(VTy->getElementCount().getKnownMinValue()))
4957*da58b97aSjoerg       return true;
4958*da58b97aSjoerg     return false;
4959*da58b97aSjoerg   }
4960*da58b97aSjoerg   case Instruction::ShuffleVector: {
4961*da58b97aSjoerg     // shufflevector may return undef.
4962*da58b97aSjoerg     if (PoisonOnly)
4963*da58b97aSjoerg       return false;
4964*da58b97aSjoerg     ArrayRef<int> Mask = isa<ConstantExpr>(Op)
4965*da58b97aSjoerg                              ? cast<ConstantExpr>(Op)->getShuffleMask()
4966*da58b97aSjoerg                              : cast<ShuffleVectorInst>(Op)->getShuffleMask();
4967*da58b97aSjoerg     return is_contained(Mask, UndefMaskElem);
4968*da58b97aSjoerg   }
4969*da58b97aSjoerg   case Instruction::FNeg:
4970*da58b97aSjoerg   case Instruction::PHI:
4971*da58b97aSjoerg   case Instruction::Select:
4972*da58b97aSjoerg   case Instruction::URem:
4973*da58b97aSjoerg   case Instruction::SRem:
4974*da58b97aSjoerg   case Instruction::ExtractValue:
4975*da58b97aSjoerg   case Instruction::InsertValue:
4976*da58b97aSjoerg   case Instruction::Freeze:
4977*da58b97aSjoerg   case Instruction::ICmp:
4978*da58b97aSjoerg   case Instruction::FCmp:
4979*da58b97aSjoerg     return false;
4980*da58b97aSjoerg   case Instruction::GetElementPtr: {
4981*da58b97aSjoerg     const auto *GEP = cast<GEPOperator>(Op);
4982*da58b97aSjoerg     return GEP->isInBounds();
4983*da58b97aSjoerg   }
4984*da58b97aSjoerg   default: {
4985*da58b97aSjoerg     const auto *CE = dyn_cast<ConstantExpr>(Op);
4986*da58b97aSjoerg     if (isa<CastInst>(Op) || (CE && CE->isCast()))
4987*da58b97aSjoerg       return false;
4988*da58b97aSjoerg     else if (Instruction::isBinaryOp(Opcode))
4989*da58b97aSjoerg       return false;
4990*da58b97aSjoerg     // Be conservative and return true.
4991*da58b97aSjoerg     return true;
4992*da58b97aSjoerg   }
4993*da58b97aSjoerg   }
4994*da58b97aSjoerg }
4995*da58b97aSjoerg 
canCreateUndefOrPoison(const Operator * Op)4996*da58b97aSjoerg bool llvm::canCreateUndefOrPoison(const Operator *Op) {
4997*da58b97aSjoerg   return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/false);
4998*da58b97aSjoerg }
4999*da58b97aSjoerg 
canCreatePoison(const Operator * Op)5000*da58b97aSjoerg bool llvm::canCreatePoison(const Operator *Op) {
5001*da58b97aSjoerg   return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/true);
5002*da58b97aSjoerg }
5003*da58b97aSjoerg 
directlyImpliesPoison(const Value * ValAssumedPoison,const Value * V,unsigned Depth)5004*da58b97aSjoerg static bool directlyImpliesPoison(const Value *ValAssumedPoison,
5005*da58b97aSjoerg                                   const Value *V, unsigned Depth) {
5006*da58b97aSjoerg   if (ValAssumedPoison == V)
5007*da58b97aSjoerg     return true;
5008*da58b97aSjoerg 
5009*da58b97aSjoerg   const unsigned MaxDepth = 2;
5010*da58b97aSjoerg   if (Depth >= MaxDepth)
5011*da58b97aSjoerg     return false;
5012*da58b97aSjoerg 
5013*da58b97aSjoerg   if (const auto *I = dyn_cast<Instruction>(V)) {
5014*da58b97aSjoerg     if (propagatesPoison(cast<Operator>(I)))
5015*da58b97aSjoerg       return any_of(I->operands(), [=](const Value *Op) {
5016*da58b97aSjoerg         return directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
5017*da58b97aSjoerg       });
5018*da58b97aSjoerg 
5019*da58b97aSjoerg     // 'select ValAssumedPoison, _, _' is poison.
5020*da58b97aSjoerg     if (const auto *SI = dyn_cast<SelectInst>(I))
5021*da58b97aSjoerg       return directlyImpliesPoison(ValAssumedPoison, SI->getCondition(),
5022*da58b97aSjoerg                                    Depth + 1);
5023*da58b97aSjoerg     // V  = extractvalue V0, idx
5024*da58b97aSjoerg     // V2 = extractvalue V0, idx2
5025*da58b97aSjoerg     // V0's elements are all poison or not. (e.g., add_with_overflow)
5026*da58b97aSjoerg     const WithOverflowInst *II;
5027*da58b97aSjoerg     if (match(I, m_ExtractValue(m_WithOverflowInst(II))) &&
5028*da58b97aSjoerg         (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
5029*da58b97aSjoerg          llvm::is_contained(II->arg_operands(), ValAssumedPoison)))
5030*da58b97aSjoerg       return true;
5031*da58b97aSjoerg   }
5032*da58b97aSjoerg   return false;
5033*da58b97aSjoerg }
5034*da58b97aSjoerg 
impliesPoison(const Value * ValAssumedPoison,const Value * V,unsigned Depth)5035*da58b97aSjoerg static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
5036*da58b97aSjoerg                           unsigned Depth) {
5037*da58b97aSjoerg   if (isGuaranteedNotToBeUndefOrPoison(ValAssumedPoison))
5038*da58b97aSjoerg     return true;
5039*da58b97aSjoerg 
5040*da58b97aSjoerg   if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
5041*da58b97aSjoerg     return true;
5042*da58b97aSjoerg 
5043*da58b97aSjoerg   const unsigned MaxDepth = 2;
5044*da58b97aSjoerg   if (Depth >= MaxDepth)
5045*da58b97aSjoerg     return false;
5046*da58b97aSjoerg 
5047*da58b97aSjoerg   const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
5048*da58b97aSjoerg   if (I && !canCreatePoison(cast<Operator>(I))) {
5049*da58b97aSjoerg     return all_of(I->operands(), [=](const Value *Op) {
5050*da58b97aSjoerg       return impliesPoison(Op, V, Depth + 1);
5051*da58b97aSjoerg     });
5052*da58b97aSjoerg   }
5053*da58b97aSjoerg   return false;
5054*da58b97aSjoerg }
5055*da58b97aSjoerg 
impliesPoison(const Value * ValAssumedPoison,const Value * V)5056*da58b97aSjoerg bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
5057*da58b97aSjoerg   return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
5058*da58b97aSjoerg }
5059*da58b97aSjoerg 
5060*da58b97aSjoerg static bool programUndefinedIfUndefOrPoison(const Value *V,
5061*da58b97aSjoerg                                             bool PoisonOnly);
5062*da58b97aSjoerg 
isGuaranteedNotToBeUndefOrPoison(const Value * V,AssumptionCache * AC,const Instruction * CtxI,const DominatorTree * DT,unsigned Depth,bool PoisonOnly)5063*da58b97aSjoerg static bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
5064*da58b97aSjoerg                                              AssumptionCache *AC,
5065*da58b97aSjoerg                                              const Instruction *CtxI,
5066*da58b97aSjoerg                                              const DominatorTree *DT,
5067*da58b97aSjoerg                                              unsigned Depth, bool PoisonOnly) {
5068*da58b97aSjoerg   if (Depth >= MaxAnalysisRecursionDepth)
5069*da58b97aSjoerg     return false;
5070*da58b97aSjoerg 
5071*da58b97aSjoerg   if (isa<MetadataAsValue>(V))
5072*da58b97aSjoerg     return false;
5073*da58b97aSjoerg 
5074*da58b97aSjoerg   if (const auto *A = dyn_cast<Argument>(V)) {
5075*da58b97aSjoerg     if (A->hasAttribute(Attribute::NoUndef))
5076*da58b97aSjoerg       return true;
5077*da58b97aSjoerg   }
5078*da58b97aSjoerg 
5079*da58b97aSjoerg   if (auto *C = dyn_cast<Constant>(V)) {
5080*da58b97aSjoerg     if (isa<UndefValue>(C))
5081*da58b97aSjoerg       return PoisonOnly && !isa<PoisonValue>(C);
5082*da58b97aSjoerg 
5083*da58b97aSjoerg     if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(V) ||
5084*da58b97aSjoerg         isa<ConstantPointerNull>(C) || isa<Function>(C))
5085*da58b97aSjoerg       return true;
5086*da58b97aSjoerg 
5087*da58b97aSjoerg     if (C->getType()->isVectorTy() && !isa<ConstantExpr>(C))
5088*da58b97aSjoerg       return (PoisonOnly ? !C->containsPoisonElement()
5089*da58b97aSjoerg                          : !C->containsUndefOrPoisonElement()) &&
5090*da58b97aSjoerg              !C->containsConstantExpression();
5091*da58b97aSjoerg   }
5092*da58b97aSjoerg 
5093*da58b97aSjoerg   // Strip cast operations from a pointer value.
5094*da58b97aSjoerg   // Note that stripPointerCastsSameRepresentation can strip off getelementptr
5095*da58b97aSjoerg   // inbounds with zero offset. To guarantee that the result isn't poison, the
5096*da58b97aSjoerg   // stripped pointer is checked as it has to be pointing into an allocated
5097*da58b97aSjoerg   // object or be null `null` to ensure `inbounds` getelement pointers with a
5098*da58b97aSjoerg   // zero offset could not produce poison.
5099*da58b97aSjoerg   // It can strip off addrspacecast that do not change bit representation as
5100*da58b97aSjoerg   // well. We believe that such addrspacecast is equivalent to no-op.
5101*da58b97aSjoerg   auto *StrippedV = V->stripPointerCastsSameRepresentation();
5102*da58b97aSjoerg   if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
5103*da58b97aSjoerg       isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
5104*da58b97aSjoerg     return true;
5105*da58b97aSjoerg 
5106*da58b97aSjoerg   auto OpCheck = [&](const Value *V) {
5107*da58b97aSjoerg     return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1,
5108*da58b97aSjoerg                                             PoisonOnly);
5109*da58b97aSjoerg   };
5110*da58b97aSjoerg 
5111*da58b97aSjoerg   if (auto *Opr = dyn_cast<Operator>(V)) {
5112*da58b97aSjoerg     // If the value is a freeze instruction, then it can never
5113*da58b97aSjoerg     // be undef or poison.
5114*da58b97aSjoerg     if (isa<FreezeInst>(V))
5115*da58b97aSjoerg       return true;
5116*da58b97aSjoerg 
5117*da58b97aSjoerg     if (const auto *CB = dyn_cast<CallBase>(V)) {
5118*da58b97aSjoerg       if (CB->hasRetAttr(Attribute::NoUndef))
5119*da58b97aSjoerg         return true;
5120*da58b97aSjoerg     }
5121*da58b97aSjoerg 
5122*da58b97aSjoerg     if (const auto *PN = dyn_cast<PHINode>(V)) {
5123*da58b97aSjoerg       unsigned Num = PN->getNumIncomingValues();
5124*da58b97aSjoerg       bool IsWellDefined = true;
5125*da58b97aSjoerg       for (unsigned i = 0; i < Num; ++i) {
5126*da58b97aSjoerg         auto *TI = PN->getIncomingBlock(i)->getTerminator();
5127*da58b97aSjoerg         if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
5128*da58b97aSjoerg                                               DT, Depth + 1, PoisonOnly)) {
5129*da58b97aSjoerg           IsWellDefined = false;
5130*da58b97aSjoerg           break;
5131*da58b97aSjoerg         }
5132*da58b97aSjoerg       }
5133*da58b97aSjoerg       if (IsWellDefined)
5134*da58b97aSjoerg         return true;
5135*da58b97aSjoerg     } else if (!canCreateUndefOrPoison(Opr) && all_of(Opr->operands(), OpCheck))
5136*da58b97aSjoerg       return true;
5137*da58b97aSjoerg   }
5138*da58b97aSjoerg 
5139*da58b97aSjoerg   if (auto *I = dyn_cast<LoadInst>(V))
5140*da58b97aSjoerg     if (I->getMetadata(LLVMContext::MD_noundef))
5141*da58b97aSjoerg       return true;
5142*da58b97aSjoerg 
5143*da58b97aSjoerg   if (programUndefinedIfUndefOrPoison(V, PoisonOnly))
5144*da58b97aSjoerg     return true;
5145*da58b97aSjoerg 
5146*da58b97aSjoerg   // CxtI may be null or a cloned instruction.
5147*da58b97aSjoerg   if (!CtxI || !CtxI->getParent() || !DT)
5148*da58b97aSjoerg     return false;
5149*da58b97aSjoerg 
5150*da58b97aSjoerg   auto *DNode = DT->getNode(CtxI->getParent());
5151*da58b97aSjoerg   if (!DNode)
5152*da58b97aSjoerg     // Unreachable block
5153*da58b97aSjoerg     return false;
5154*da58b97aSjoerg 
5155*da58b97aSjoerg   // If V is used as a branch condition before reaching CtxI, V cannot be
5156*da58b97aSjoerg   // undef or poison.
5157*da58b97aSjoerg   //   br V, BB1, BB2
5158*da58b97aSjoerg   // BB1:
5159*da58b97aSjoerg   //   CtxI ; V cannot be undef or poison here
5160*da58b97aSjoerg   auto *Dominator = DNode->getIDom();
5161*da58b97aSjoerg   while (Dominator) {
5162*da58b97aSjoerg     auto *TI = Dominator->getBlock()->getTerminator();
5163*da58b97aSjoerg 
5164*da58b97aSjoerg     Value *Cond = nullptr;
5165*da58b97aSjoerg     if (auto BI = dyn_cast<BranchInst>(TI)) {
5166*da58b97aSjoerg       if (BI->isConditional())
5167*da58b97aSjoerg         Cond = BI->getCondition();
5168*da58b97aSjoerg     } else if (auto SI = dyn_cast<SwitchInst>(TI)) {
5169*da58b97aSjoerg       Cond = SI->getCondition();
5170*da58b97aSjoerg     }
5171*da58b97aSjoerg 
5172*da58b97aSjoerg     if (Cond) {
5173*da58b97aSjoerg       if (Cond == V)
5174*da58b97aSjoerg         return true;
5175*da58b97aSjoerg       else if (PoisonOnly && isa<Operator>(Cond)) {
5176*da58b97aSjoerg         // For poison, we can analyze further
5177*da58b97aSjoerg         auto *Opr = cast<Operator>(Cond);
5178*da58b97aSjoerg         if (propagatesPoison(Opr) && is_contained(Opr->operand_values(), V))
5179*da58b97aSjoerg           return true;
5180*da58b97aSjoerg       }
5181*da58b97aSjoerg     }
5182*da58b97aSjoerg 
5183*da58b97aSjoerg     Dominator = Dominator->getIDom();
5184*da58b97aSjoerg   }
5185*da58b97aSjoerg 
5186*da58b97aSjoerg   SmallVector<Attribute::AttrKind, 2> AttrKinds{Attribute::NoUndef};
5187*da58b97aSjoerg   if (getKnowledgeValidInContext(V, AttrKinds, CtxI, DT, AC))
5188*da58b97aSjoerg     return true;
5189*da58b97aSjoerg 
5190*da58b97aSjoerg   return false;
5191*da58b97aSjoerg }
5192*da58b97aSjoerg 
isGuaranteedNotToBeUndefOrPoison(const Value * V,AssumptionCache * AC,const Instruction * CtxI,const DominatorTree * DT,unsigned Depth)5193*da58b97aSjoerg bool llvm::isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC,
5194*da58b97aSjoerg                                             const Instruction *CtxI,
5195*da58b97aSjoerg                                             const DominatorTree *DT,
5196*da58b97aSjoerg                                             unsigned Depth) {
5197*da58b97aSjoerg   return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, false);
5198*da58b97aSjoerg }
5199*da58b97aSjoerg 
isGuaranteedNotToBePoison(const Value * V,AssumptionCache * AC,const Instruction * CtxI,const DominatorTree * DT,unsigned Depth)5200*da58b97aSjoerg bool llvm::isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC,
5201*da58b97aSjoerg                                      const Instruction *CtxI,
5202*da58b97aSjoerg                                      const DominatorTree *DT, unsigned Depth) {
5203*da58b97aSjoerg   return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, true);
5204*da58b97aSjoerg }
520506f32e7eSjoerg 
computeOverflowForSignedAdd(const AddOperator * Add,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT)520606f32e7eSjoerg OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
520706f32e7eSjoerg                                                  const DataLayout &DL,
520806f32e7eSjoerg                                                  AssumptionCache *AC,
520906f32e7eSjoerg                                                  const Instruction *CxtI,
521006f32e7eSjoerg                                                  const DominatorTree *DT) {
521106f32e7eSjoerg   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
521206f32e7eSjoerg                                        Add, DL, AC, CxtI, DT);
521306f32e7eSjoerg }
521406f32e7eSjoerg 
computeOverflowForSignedAdd(const Value * LHS,const Value * RHS,const DataLayout & DL,AssumptionCache * AC,const Instruction * CxtI,const DominatorTree * DT)521506f32e7eSjoerg OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
521606f32e7eSjoerg                                                  const Value *RHS,
521706f32e7eSjoerg                                                  const DataLayout &DL,
521806f32e7eSjoerg                                                  AssumptionCache *AC,
521906f32e7eSjoerg                                                  const Instruction *CxtI,
522006f32e7eSjoerg                                                  const DominatorTree *DT) {
522106f32e7eSjoerg   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
522206f32e7eSjoerg }
522306f32e7eSjoerg 
isGuaranteedToTransferExecutionToSuccessor(const Instruction * I)522406f32e7eSjoerg bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
522506f32e7eSjoerg   // Note: An atomic operation isn't guaranteed to return in a reasonable amount
522606f32e7eSjoerg   // of time because it's possible for another thread to interfere with it for an
522706f32e7eSjoerg   // arbitrary length of time, but programs aren't allowed to rely on that.
522806f32e7eSjoerg 
522906f32e7eSjoerg   // If there is no successor, then execution can't transfer to it.
523006f32e7eSjoerg   if (isa<ReturnInst>(I))
523106f32e7eSjoerg     return false;
523206f32e7eSjoerg   if (isa<UnreachableInst>(I))
523306f32e7eSjoerg     return false;
523406f32e7eSjoerg 
5235*da58b97aSjoerg   // An instruction that returns without throwing must transfer control flow
5236*da58b97aSjoerg   // to a successor.
5237*da58b97aSjoerg   return !I->mayThrow() && I->willReturn();
523806f32e7eSjoerg }
523906f32e7eSjoerg 
isGuaranteedToTransferExecutionToSuccessor(const BasicBlock * BB)524006f32e7eSjoerg bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
524106f32e7eSjoerg   // TODO: This is slightly conservative for invoke instruction since exiting
524206f32e7eSjoerg   // via an exception *is* normal control for them.
5243*da58b97aSjoerg   for (const Instruction &I : *BB)
5244*da58b97aSjoerg     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
524506f32e7eSjoerg       return false;
524606f32e7eSjoerg   return true;
524706f32e7eSjoerg }
524806f32e7eSjoerg 
isGuaranteedToExecuteForEveryIteration(const Instruction * I,const Loop * L)524906f32e7eSjoerg bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
525006f32e7eSjoerg                                                   const Loop *L) {
525106f32e7eSjoerg   // The loop header is guaranteed to be executed for every iteration.
525206f32e7eSjoerg   //
525306f32e7eSjoerg   // FIXME: Relax this constraint to cover all basic blocks that are
525406f32e7eSjoerg   // guaranteed to be executed at every iteration.
525506f32e7eSjoerg   if (I->getParent() != L->getHeader()) return false;
525606f32e7eSjoerg 
525706f32e7eSjoerg   for (const Instruction &LI : *L->getHeader()) {
525806f32e7eSjoerg     if (&LI == I) return true;
525906f32e7eSjoerg     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
526006f32e7eSjoerg   }
526106f32e7eSjoerg   llvm_unreachable("Instruction not contained in its own parent basic block.");
526206f32e7eSjoerg }
526306f32e7eSjoerg 
propagatesPoison(const Operator * I)5264*da58b97aSjoerg bool llvm::propagatesPoison(const Operator *I) {
526506f32e7eSjoerg   switch (I->getOpcode()) {
5266*da58b97aSjoerg   case Instruction::Freeze:
5267*da58b97aSjoerg   case Instruction::Select:
5268*da58b97aSjoerg   case Instruction::PHI:
5269*da58b97aSjoerg   case Instruction::Invoke:
5270*da58b97aSjoerg     return false;
5271*da58b97aSjoerg   case Instruction::Call:
5272*da58b97aSjoerg     if (auto *II = dyn_cast<IntrinsicInst>(I)) {
5273*da58b97aSjoerg       switch (II->getIntrinsicID()) {
5274*da58b97aSjoerg       // TODO: Add more intrinsics.
5275*da58b97aSjoerg       case Intrinsic::sadd_with_overflow:
5276*da58b97aSjoerg       case Intrinsic::ssub_with_overflow:
5277*da58b97aSjoerg       case Intrinsic::smul_with_overflow:
5278*da58b97aSjoerg       case Intrinsic::uadd_with_overflow:
5279*da58b97aSjoerg       case Intrinsic::usub_with_overflow:
5280*da58b97aSjoerg       case Intrinsic::umul_with_overflow:
5281*da58b97aSjoerg         // If an input is a vector containing a poison element, the
5282*da58b97aSjoerg         // two output vectors (calculated results, overflow bits)'
5283*da58b97aSjoerg         // corresponding lanes are poison.
528406f32e7eSjoerg         return true;
5285*da58b97aSjoerg       case Intrinsic::ctpop:
528606f32e7eSjoerg         return true;
5287*da58b97aSjoerg       }
5288*da58b97aSjoerg     }
5289*da58b97aSjoerg     return false;
529006f32e7eSjoerg   case Instruction::ICmp:
5291*da58b97aSjoerg   case Instruction::FCmp:
5292*da58b97aSjoerg   case Instruction::GetElementPtr:
5293*da58b97aSjoerg     return true;
5294*da58b97aSjoerg   default:
5295*da58b97aSjoerg     if (isa<BinaryOperator>(I) || isa<UnaryOperator>(I) || isa<CastInst>(I))
529606f32e7eSjoerg       return true;
529706f32e7eSjoerg 
5298*da58b97aSjoerg     // Be conservative and return false.
529906f32e7eSjoerg     return false;
530006f32e7eSjoerg   }
530106f32e7eSjoerg }
530206f32e7eSjoerg 
getGuaranteedWellDefinedOps(const Instruction * I,SmallPtrSetImpl<const Value * > & Operands)5303*da58b97aSjoerg void llvm::getGuaranteedWellDefinedOps(
5304*da58b97aSjoerg     const Instruction *I, SmallPtrSetImpl<const Value *> &Operands) {
530506f32e7eSjoerg   switch (I->getOpcode()) {
530606f32e7eSjoerg     case Instruction::Store:
5307*da58b97aSjoerg       Operands.insert(cast<StoreInst>(I)->getPointerOperand());
5308*da58b97aSjoerg       break;
530906f32e7eSjoerg 
531006f32e7eSjoerg     case Instruction::Load:
5311*da58b97aSjoerg       Operands.insert(cast<LoadInst>(I)->getPointerOperand());
5312*da58b97aSjoerg       break;
531306f32e7eSjoerg 
5314*da58b97aSjoerg     // Since dereferenceable attribute imply noundef, atomic operations
5315*da58b97aSjoerg     // also implicitly have noundef pointers too
531606f32e7eSjoerg     case Instruction::AtomicCmpXchg:
5317*da58b97aSjoerg       Operands.insert(cast<AtomicCmpXchgInst>(I)->getPointerOperand());
5318*da58b97aSjoerg       break;
531906f32e7eSjoerg 
532006f32e7eSjoerg     case Instruction::AtomicRMW:
5321*da58b97aSjoerg       Operands.insert(cast<AtomicRMWInst>(I)->getPointerOperand());
5322*da58b97aSjoerg       break;
532306f32e7eSjoerg 
5324*da58b97aSjoerg     case Instruction::Call:
5325*da58b97aSjoerg     case Instruction::Invoke: {
5326*da58b97aSjoerg       const CallBase *CB = cast<CallBase>(I);
5327*da58b97aSjoerg       if (CB->isIndirectCall())
5328*da58b97aSjoerg         Operands.insert(CB->getCalledOperand());
5329*da58b97aSjoerg       for (unsigned i = 0; i < CB->arg_size(); ++i) {
5330*da58b97aSjoerg         if (CB->paramHasAttr(i, Attribute::NoUndef) ||
5331*da58b97aSjoerg             CB->paramHasAttr(i, Attribute::Dereferenceable))
5332*da58b97aSjoerg           Operands.insert(CB->getArgOperand(i));
5333*da58b97aSjoerg       }
5334*da58b97aSjoerg       break;
5335*da58b97aSjoerg     }
5336*da58b97aSjoerg 
5337*da58b97aSjoerg     default:
5338*da58b97aSjoerg       break;
5339*da58b97aSjoerg   }
5340*da58b97aSjoerg }
5341*da58b97aSjoerg 
getGuaranteedNonPoisonOps(const Instruction * I,SmallPtrSetImpl<const Value * > & Operands)5342*da58b97aSjoerg void llvm::getGuaranteedNonPoisonOps(const Instruction *I,
5343*da58b97aSjoerg                                      SmallPtrSetImpl<const Value *> &Operands) {
5344*da58b97aSjoerg   getGuaranteedWellDefinedOps(I, Operands);
5345*da58b97aSjoerg   switch (I->getOpcode()) {
5346*da58b97aSjoerg   // Divisors of these operations are allowed to be partially undef.
534706f32e7eSjoerg   case Instruction::UDiv:
534806f32e7eSjoerg   case Instruction::SDiv:
534906f32e7eSjoerg   case Instruction::URem:
535006f32e7eSjoerg   case Instruction::SRem:
5351*da58b97aSjoerg     Operands.insert(I->getOperand(1));
5352*da58b97aSjoerg     break;
535306f32e7eSjoerg 
535406f32e7eSjoerg   default:
5355*da58b97aSjoerg     break;
535606f32e7eSjoerg   }
535706f32e7eSjoerg }
535806f32e7eSjoerg 
mustTriggerUB(const Instruction * I,const SmallSet<const Value *,16> & KnownPoison)535906f32e7eSjoerg bool llvm::mustTriggerUB(const Instruction *I,
536006f32e7eSjoerg                          const SmallSet<const Value *, 16>& KnownPoison) {
5361*da58b97aSjoerg   SmallPtrSet<const Value *, 4> NonPoisonOps;
5362*da58b97aSjoerg   getGuaranteedNonPoisonOps(I, NonPoisonOps);
5363*da58b97aSjoerg 
5364*da58b97aSjoerg   for (const auto *V : NonPoisonOps)
5365*da58b97aSjoerg     if (KnownPoison.count(V))
5366*da58b97aSjoerg       return true;
5367*da58b97aSjoerg 
5368*da58b97aSjoerg   return false;
536906f32e7eSjoerg }
537006f32e7eSjoerg 
programUndefinedIfUndefOrPoison(const Value * V,bool PoisonOnly)5371*da58b97aSjoerg static bool programUndefinedIfUndefOrPoison(const Value *V,
5372*da58b97aSjoerg                                             bool PoisonOnly) {
5373*da58b97aSjoerg   // We currently only look for uses of values within the same basic
537406f32e7eSjoerg   // block, as that makes it easier to guarantee that the uses will be
5375*da58b97aSjoerg   // executed given that Inst is executed.
537606f32e7eSjoerg   //
537706f32e7eSjoerg   // FIXME: Expand this to consider uses beyond the same basic block. To do
537806f32e7eSjoerg   // this, look out for the distinction between post-dominance and strong
537906f32e7eSjoerg   // post-dominance.
5380*da58b97aSjoerg   const BasicBlock *BB = nullptr;
5381*da58b97aSjoerg   BasicBlock::const_iterator Begin;
5382*da58b97aSjoerg   if (const auto *Inst = dyn_cast<Instruction>(V)) {
5383*da58b97aSjoerg     BB = Inst->getParent();
5384*da58b97aSjoerg     Begin = Inst->getIterator();
5385*da58b97aSjoerg     Begin++;
5386*da58b97aSjoerg   } else if (const auto *Arg = dyn_cast<Argument>(V)) {
5387*da58b97aSjoerg     BB = &Arg->getParent()->getEntryBlock();
5388*da58b97aSjoerg     Begin = BB->begin();
5389*da58b97aSjoerg   } else {
5390*da58b97aSjoerg     return false;
5391*da58b97aSjoerg   }
539206f32e7eSjoerg 
5393*da58b97aSjoerg   // Limit number of instructions we look at, to avoid scanning through large
5394*da58b97aSjoerg   // blocks. The current limit is chosen arbitrarily.
5395*da58b97aSjoerg   unsigned ScanLimit = 32;
5396*da58b97aSjoerg   BasicBlock::const_iterator End = BB->end();
5397*da58b97aSjoerg 
5398*da58b97aSjoerg   if (!PoisonOnly) {
5399*da58b97aSjoerg     // Since undef does not propagate eagerly, be conservative & just check
5400*da58b97aSjoerg     // whether a value is directly passed to an instruction that must take
5401*da58b97aSjoerg     // well-defined operands.
5402*da58b97aSjoerg 
5403*da58b97aSjoerg     for (auto &I : make_range(Begin, End)) {
5404*da58b97aSjoerg       if (isa<DbgInfoIntrinsic>(I))
5405*da58b97aSjoerg         continue;
5406*da58b97aSjoerg       if (--ScanLimit == 0)
5407*da58b97aSjoerg         break;
5408*da58b97aSjoerg 
5409*da58b97aSjoerg       SmallPtrSet<const Value *, 4> WellDefinedOps;
5410*da58b97aSjoerg       getGuaranteedWellDefinedOps(&I, WellDefinedOps);
5411*da58b97aSjoerg       if (WellDefinedOps.contains(V))
5412*da58b97aSjoerg         return true;
5413*da58b97aSjoerg 
5414*da58b97aSjoerg       if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5415*da58b97aSjoerg         break;
5416*da58b97aSjoerg     }
5417*da58b97aSjoerg     return false;
5418*da58b97aSjoerg   }
5419*da58b97aSjoerg 
5420*da58b97aSjoerg   // Set of instructions that we have proved will yield poison if Inst
542106f32e7eSjoerg   // does.
542206f32e7eSjoerg   SmallSet<const Value *, 16> YieldsPoison;
542306f32e7eSjoerg   SmallSet<const BasicBlock *, 4> Visited;
542406f32e7eSjoerg 
5425*da58b97aSjoerg   YieldsPoison.insert(V);
5426*da58b97aSjoerg   auto Propagate = [&](const User *User) {
5427*da58b97aSjoerg     if (propagatesPoison(cast<Operator>(User)))
5428*da58b97aSjoerg       YieldsPoison.insert(User);
5429*da58b97aSjoerg   };
5430*da58b97aSjoerg   for_each(V->users(), Propagate);
5431*da58b97aSjoerg   Visited.insert(BB);
543206f32e7eSjoerg 
5433*da58b97aSjoerg   while (true) {
543406f32e7eSjoerg     for (auto &I : make_range(Begin, End)) {
5435*da58b97aSjoerg       if (isa<DbgInfoIntrinsic>(I))
5436*da58b97aSjoerg         continue;
5437*da58b97aSjoerg       if (--ScanLimit == 0)
5438*da58b97aSjoerg         return false;
543906f32e7eSjoerg       if (mustTriggerUB(&I, YieldsPoison))
544006f32e7eSjoerg         return true;
544106f32e7eSjoerg       if (!isGuaranteedToTransferExecutionToSuccessor(&I))
544206f32e7eSjoerg         return false;
544306f32e7eSjoerg 
544406f32e7eSjoerg       // Mark poison that propagates from I through uses of I.
5445*da58b97aSjoerg       if (YieldsPoison.count(&I))
5446*da58b97aSjoerg         for_each(I.users(), Propagate);
544706f32e7eSjoerg     }
544806f32e7eSjoerg 
5449*da58b97aSjoerg     BB = BB->getSingleSuccessor();
5450*da58b97aSjoerg     if (!BB || !Visited.insert(BB).second)
5451*da58b97aSjoerg       break;
5452*da58b97aSjoerg 
545306f32e7eSjoerg     Begin = BB->getFirstNonPHI()->getIterator();
545406f32e7eSjoerg     End = BB->end();
545506f32e7eSjoerg   }
545606f32e7eSjoerg   return false;
545706f32e7eSjoerg }
545806f32e7eSjoerg 
programUndefinedIfUndefOrPoison(const Instruction * Inst)5459*da58b97aSjoerg bool llvm::programUndefinedIfUndefOrPoison(const Instruction *Inst) {
5460*da58b97aSjoerg   return ::programUndefinedIfUndefOrPoison(Inst, false);
5461*da58b97aSjoerg }
5462*da58b97aSjoerg 
programUndefinedIfPoison(const Instruction * Inst)5463*da58b97aSjoerg bool llvm::programUndefinedIfPoison(const Instruction *Inst) {
5464*da58b97aSjoerg   return ::programUndefinedIfUndefOrPoison(Inst, true);
5465*da58b97aSjoerg }
5466*da58b97aSjoerg 
isKnownNonNaN(const Value * V,FastMathFlags FMF)546706f32e7eSjoerg static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
546806f32e7eSjoerg   if (FMF.noNaNs())
546906f32e7eSjoerg     return true;
547006f32e7eSjoerg 
547106f32e7eSjoerg   if (auto *C = dyn_cast<ConstantFP>(V))
547206f32e7eSjoerg     return !C->isNaN();
547306f32e7eSjoerg 
547406f32e7eSjoerg   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
547506f32e7eSjoerg     if (!C->getElementType()->isFloatingPointTy())
547606f32e7eSjoerg       return false;
547706f32e7eSjoerg     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
547806f32e7eSjoerg       if (C->getElementAsAPFloat(I).isNaN())
547906f32e7eSjoerg         return false;
548006f32e7eSjoerg     }
548106f32e7eSjoerg     return true;
548206f32e7eSjoerg   }
548306f32e7eSjoerg 
5484*da58b97aSjoerg   if (isa<ConstantAggregateZero>(V))
5485*da58b97aSjoerg     return true;
5486*da58b97aSjoerg 
548706f32e7eSjoerg   return false;
548806f32e7eSjoerg }
548906f32e7eSjoerg 
isKnownNonZero(const Value * V)549006f32e7eSjoerg static bool isKnownNonZero(const Value *V) {
549106f32e7eSjoerg   if (auto *C = dyn_cast<ConstantFP>(V))
549206f32e7eSjoerg     return !C->isZero();
549306f32e7eSjoerg 
549406f32e7eSjoerg   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
549506f32e7eSjoerg     if (!C->getElementType()->isFloatingPointTy())
549606f32e7eSjoerg       return false;
549706f32e7eSjoerg     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
549806f32e7eSjoerg       if (C->getElementAsAPFloat(I).isZero())
549906f32e7eSjoerg         return false;
550006f32e7eSjoerg     }
550106f32e7eSjoerg     return true;
550206f32e7eSjoerg   }
550306f32e7eSjoerg 
550406f32e7eSjoerg   return false;
550506f32e7eSjoerg }
550606f32e7eSjoerg 
550706f32e7eSjoerg /// Match clamp pattern for float types without care about NaNs or signed zeros.
550806f32e7eSjoerg /// Given non-min/max outer cmp/select from the clamp pattern this
550906f32e7eSjoerg /// function recognizes if it can be substitued by a "canonical" min/max
551006f32e7eSjoerg /// pattern.
matchFastFloatClamp(CmpInst::Predicate Pred,Value * CmpLHS,Value * CmpRHS,Value * TrueVal,Value * FalseVal,Value * & LHS,Value * & RHS)551106f32e7eSjoerg static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
551206f32e7eSjoerg                                                Value *CmpLHS, Value *CmpRHS,
551306f32e7eSjoerg                                                Value *TrueVal, Value *FalseVal,
551406f32e7eSjoerg                                                Value *&LHS, Value *&RHS) {
551506f32e7eSjoerg   // Try to match
551606f32e7eSjoerg   //   X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
551706f32e7eSjoerg   //   X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
551806f32e7eSjoerg   // and return description of the outer Max/Min.
551906f32e7eSjoerg 
552006f32e7eSjoerg   // First, check if select has inverse order:
552106f32e7eSjoerg   if (CmpRHS == FalseVal) {
552206f32e7eSjoerg     std::swap(TrueVal, FalseVal);
552306f32e7eSjoerg     Pred = CmpInst::getInversePredicate(Pred);
552406f32e7eSjoerg   }
552506f32e7eSjoerg 
552606f32e7eSjoerg   // Assume success now. If there's no match, callers should not use these anyway.
552706f32e7eSjoerg   LHS = TrueVal;
552806f32e7eSjoerg   RHS = FalseVal;
552906f32e7eSjoerg 
553006f32e7eSjoerg   const APFloat *FC1;
553106f32e7eSjoerg   if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
553206f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
553306f32e7eSjoerg 
553406f32e7eSjoerg   const APFloat *FC2;
553506f32e7eSjoerg   switch (Pred) {
553606f32e7eSjoerg   case CmpInst::FCMP_OLT:
553706f32e7eSjoerg   case CmpInst::FCMP_OLE:
553806f32e7eSjoerg   case CmpInst::FCMP_ULT:
553906f32e7eSjoerg   case CmpInst::FCMP_ULE:
554006f32e7eSjoerg     if (match(FalseVal,
554106f32e7eSjoerg               m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
554206f32e7eSjoerg                           m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
5543*da58b97aSjoerg         *FC1 < *FC2)
554406f32e7eSjoerg       return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
554506f32e7eSjoerg     break;
554606f32e7eSjoerg   case CmpInst::FCMP_OGT:
554706f32e7eSjoerg   case CmpInst::FCMP_OGE:
554806f32e7eSjoerg   case CmpInst::FCMP_UGT:
554906f32e7eSjoerg   case CmpInst::FCMP_UGE:
555006f32e7eSjoerg     if (match(FalseVal,
555106f32e7eSjoerg               m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
555206f32e7eSjoerg                           m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
5553*da58b97aSjoerg         *FC1 > *FC2)
555406f32e7eSjoerg       return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
555506f32e7eSjoerg     break;
555606f32e7eSjoerg   default:
555706f32e7eSjoerg     break;
555806f32e7eSjoerg   }
555906f32e7eSjoerg 
556006f32e7eSjoerg   return {SPF_UNKNOWN, SPNB_NA, false};
556106f32e7eSjoerg }
556206f32e7eSjoerg 
556306f32e7eSjoerg /// Recognize variations of:
556406f32e7eSjoerg ///   CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
matchClamp(CmpInst::Predicate Pred,Value * CmpLHS,Value * CmpRHS,Value * TrueVal,Value * FalseVal)556506f32e7eSjoerg static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
556606f32e7eSjoerg                                       Value *CmpLHS, Value *CmpRHS,
556706f32e7eSjoerg                                       Value *TrueVal, Value *FalseVal) {
556806f32e7eSjoerg   // Swap the select operands and predicate to match the patterns below.
556906f32e7eSjoerg   if (CmpRHS != TrueVal) {
557006f32e7eSjoerg     Pred = ICmpInst::getSwappedPredicate(Pred);
557106f32e7eSjoerg     std::swap(TrueVal, FalseVal);
557206f32e7eSjoerg   }
557306f32e7eSjoerg   const APInt *C1;
557406f32e7eSjoerg   if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
557506f32e7eSjoerg     const APInt *C2;
557606f32e7eSjoerg     // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
557706f32e7eSjoerg     if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
557806f32e7eSjoerg         C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
557906f32e7eSjoerg       return {SPF_SMAX, SPNB_NA, false};
558006f32e7eSjoerg 
558106f32e7eSjoerg     // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
558206f32e7eSjoerg     if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
558306f32e7eSjoerg         C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
558406f32e7eSjoerg       return {SPF_SMIN, SPNB_NA, false};
558506f32e7eSjoerg 
558606f32e7eSjoerg     // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
558706f32e7eSjoerg     if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
558806f32e7eSjoerg         C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
558906f32e7eSjoerg       return {SPF_UMAX, SPNB_NA, false};
559006f32e7eSjoerg 
559106f32e7eSjoerg     // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
559206f32e7eSjoerg     if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
559306f32e7eSjoerg         C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
559406f32e7eSjoerg       return {SPF_UMIN, SPNB_NA, false};
559506f32e7eSjoerg   }
559606f32e7eSjoerg   return {SPF_UNKNOWN, SPNB_NA, false};
559706f32e7eSjoerg }
559806f32e7eSjoerg 
559906f32e7eSjoerg /// Recognize variations of:
560006f32e7eSjoerg ///   a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
matchMinMaxOfMinMax(CmpInst::Predicate Pred,Value * CmpLHS,Value * CmpRHS,Value * TVal,Value * FVal,unsigned Depth)560106f32e7eSjoerg static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
560206f32e7eSjoerg                                                Value *CmpLHS, Value *CmpRHS,
560306f32e7eSjoerg                                                Value *TVal, Value *FVal,
560406f32e7eSjoerg                                                unsigned Depth) {
560506f32e7eSjoerg   // TODO: Allow FP min/max with nnan/nsz.
560606f32e7eSjoerg   assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
560706f32e7eSjoerg 
560806f32e7eSjoerg   Value *A = nullptr, *B = nullptr;
560906f32e7eSjoerg   SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
561006f32e7eSjoerg   if (!SelectPatternResult::isMinOrMax(L.Flavor))
561106f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
561206f32e7eSjoerg 
561306f32e7eSjoerg   Value *C = nullptr, *D = nullptr;
561406f32e7eSjoerg   SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
561506f32e7eSjoerg   if (L.Flavor != R.Flavor)
561606f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
561706f32e7eSjoerg 
561806f32e7eSjoerg   // We have something like: x Pred y ? min(a, b) : min(c, d).
561906f32e7eSjoerg   // Try to match the compare to the min/max operations of the select operands.
562006f32e7eSjoerg   // First, make sure we have the right compare predicate.
562106f32e7eSjoerg   switch (L.Flavor) {
562206f32e7eSjoerg   case SPF_SMIN:
562306f32e7eSjoerg     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
562406f32e7eSjoerg       Pred = ICmpInst::getSwappedPredicate(Pred);
562506f32e7eSjoerg       std::swap(CmpLHS, CmpRHS);
562606f32e7eSjoerg     }
562706f32e7eSjoerg     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
562806f32e7eSjoerg       break;
562906f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
563006f32e7eSjoerg   case SPF_SMAX:
563106f32e7eSjoerg     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
563206f32e7eSjoerg       Pred = ICmpInst::getSwappedPredicate(Pred);
563306f32e7eSjoerg       std::swap(CmpLHS, CmpRHS);
563406f32e7eSjoerg     }
563506f32e7eSjoerg     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
563606f32e7eSjoerg       break;
563706f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
563806f32e7eSjoerg   case SPF_UMIN:
563906f32e7eSjoerg     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
564006f32e7eSjoerg       Pred = ICmpInst::getSwappedPredicate(Pred);
564106f32e7eSjoerg       std::swap(CmpLHS, CmpRHS);
564206f32e7eSjoerg     }
564306f32e7eSjoerg     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
564406f32e7eSjoerg       break;
564506f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
564606f32e7eSjoerg   case SPF_UMAX:
564706f32e7eSjoerg     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
564806f32e7eSjoerg       Pred = ICmpInst::getSwappedPredicate(Pred);
564906f32e7eSjoerg       std::swap(CmpLHS, CmpRHS);
565006f32e7eSjoerg     }
565106f32e7eSjoerg     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
565206f32e7eSjoerg       break;
565306f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
565406f32e7eSjoerg   default:
565506f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
565606f32e7eSjoerg   }
565706f32e7eSjoerg 
565806f32e7eSjoerg   // If there is a common operand in the already matched min/max and the other
565906f32e7eSjoerg   // min/max operands match the compare operands (either directly or inverted),
566006f32e7eSjoerg   // then this is min/max of the same flavor.
566106f32e7eSjoerg 
566206f32e7eSjoerg   // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
566306f32e7eSjoerg   // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
566406f32e7eSjoerg   if (D == B) {
566506f32e7eSjoerg     if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
566606f32e7eSjoerg                                          match(A, m_Not(m_Specific(CmpRHS)))))
566706f32e7eSjoerg       return {L.Flavor, SPNB_NA, false};
566806f32e7eSjoerg   }
566906f32e7eSjoerg   // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
567006f32e7eSjoerg   // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
567106f32e7eSjoerg   if (C == B) {
567206f32e7eSjoerg     if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
567306f32e7eSjoerg                                          match(A, m_Not(m_Specific(CmpRHS)))))
567406f32e7eSjoerg       return {L.Flavor, SPNB_NA, false};
567506f32e7eSjoerg   }
567606f32e7eSjoerg   // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
567706f32e7eSjoerg   // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
567806f32e7eSjoerg   if (D == A) {
567906f32e7eSjoerg     if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
568006f32e7eSjoerg                                          match(B, m_Not(m_Specific(CmpRHS)))))
568106f32e7eSjoerg       return {L.Flavor, SPNB_NA, false};
568206f32e7eSjoerg   }
568306f32e7eSjoerg   // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
568406f32e7eSjoerg   // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
568506f32e7eSjoerg   if (C == A) {
568606f32e7eSjoerg     if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
568706f32e7eSjoerg                                          match(B, m_Not(m_Specific(CmpRHS)))))
568806f32e7eSjoerg       return {L.Flavor, SPNB_NA, false};
568906f32e7eSjoerg   }
569006f32e7eSjoerg 
569106f32e7eSjoerg   return {SPF_UNKNOWN, SPNB_NA, false};
569206f32e7eSjoerg }
569306f32e7eSjoerg 
5694*da58b97aSjoerg /// If the input value is the result of a 'not' op, constant integer, or vector
5695*da58b97aSjoerg /// splat of a constant integer, return the bitwise-not source value.
5696*da58b97aSjoerg /// TODO: This could be extended to handle non-splat vector integer constants.
getNotValue(Value * V)5697*da58b97aSjoerg static Value *getNotValue(Value *V) {
5698*da58b97aSjoerg   Value *NotV;
5699*da58b97aSjoerg   if (match(V, m_Not(m_Value(NotV))))
5700*da58b97aSjoerg     return NotV;
5701*da58b97aSjoerg 
5702*da58b97aSjoerg   const APInt *C;
5703*da58b97aSjoerg   if (match(V, m_APInt(C)))
5704*da58b97aSjoerg     return ConstantInt::get(V->getType(), ~(*C));
5705*da58b97aSjoerg 
5706*da58b97aSjoerg   return nullptr;
5707*da58b97aSjoerg }
5708*da58b97aSjoerg 
570906f32e7eSjoerg /// Match non-obvious integer minimum and maximum sequences.
matchMinMax(CmpInst::Predicate Pred,Value * CmpLHS,Value * CmpRHS,Value * TrueVal,Value * FalseVal,Value * & LHS,Value * & RHS,unsigned Depth)571006f32e7eSjoerg static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
571106f32e7eSjoerg                                        Value *CmpLHS, Value *CmpRHS,
571206f32e7eSjoerg                                        Value *TrueVal, Value *FalseVal,
571306f32e7eSjoerg                                        Value *&LHS, Value *&RHS,
571406f32e7eSjoerg                                        unsigned Depth) {
571506f32e7eSjoerg   // Assume success. If there's no match, callers should not use these anyway.
571606f32e7eSjoerg   LHS = TrueVal;
571706f32e7eSjoerg   RHS = FalseVal;
571806f32e7eSjoerg 
571906f32e7eSjoerg   SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
572006f32e7eSjoerg   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
572106f32e7eSjoerg     return SPR;
572206f32e7eSjoerg 
572306f32e7eSjoerg   SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
572406f32e7eSjoerg   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
572506f32e7eSjoerg     return SPR;
572606f32e7eSjoerg 
5727*da58b97aSjoerg   // Look through 'not' ops to find disguised min/max.
5728*da58b97aSjoerg   // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
5729*da58b97aSjoerg   // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
5730*da58b97aSjoerg   if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
5731*da58b97aSjoerg     switch (Pred) {
5732*da58b97aSjoerg     case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
5733*da58b97aSjoerg     case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
5734*da58b97aSjoerg     case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
5735*da58b97aSjoerg     case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
5736*da58b97aSjoerg     default: break;
5737*da58b97aSjoerg     }
5738*da58b97aSjoerg   }
5739*da58b97aSjoerg 
5740*da58b97aSjoerg   // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
5741*da58b97aSjoerg   // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
5742*da58b97aSjoerg   if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
5743*da58b97aSjoerg     switch (Pred) {
5744*da58b97aSjoerg     case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
5745*da58b97aSjoerg     case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
5746*da58b97aSjoerg     case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
5747*da58b97aSjoerg     case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
5748*da58b97aSjoerg     default: break;
5749*da58b97aSjoerg     }
5750*da58b97aSjoerg   }
5751*da58b97aSjoerg 
575206f32e7eSjoerg   if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
575306f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
575406f32e7eSjoerg 
575506f32e7eSjoerg   // Z = X -nsw Y
575606f32e7eSjoerg   // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
575706f32e7eSjoerg   // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
575806f32e7eSjoerg   if (match(TrueVal, m_Zero()) &&
575906f32e7eSjoerg       match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
576006f32e7eSjoerg     return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
576106f32e7eSjoerg 
576206f32e7eSjoerg   // Z = X -nsw Y
576306f32e7eSjoerg   // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
576406f32e7eSjoerg   // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
576506f32e7eSjoerg   if (match(FalseVal, m_Zero()) &&
576606f32e7eSjoerg       match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
576706f32e7eSjoerg     return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
576806f32e7eSjoerg 
576906f32e7eSjoerg   const APInt *C1;
577006f32e7eSjoerg   if (!match(CmpRHS, m_APInt(C1)))
577106f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
577206f32e7eSjoerg 
577306f32e7eSjoerg   // An unsigned min/max can be written with a signed compare.
577406f32e7eSjoerg   const APInt *C2;
577506f32e7eSjoerg   if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
577606f32e7eSjoerg       (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
577706f32e7eSjoerg     // Is the sign bit set?
577806f32e7eSjoerg     // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
577906f32e7eSjoerg     // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
578006f32e7eSjoerg     if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
578106f32e7eSjoerg         C2->isMaxSignedValue())
578206f32e7eSjoerg       return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
578306f32e7eSjoerg 
578406f32e7eSjoerg     // Is the sign bit clear?
578506f32e7eSjoerg     // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
578606f32e7eSjoerg     // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
578706f32e7eSjoerg     if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
578806f32e7eSjoerg         C2->isMinSignedValue())
578906f32e7eSjoerg       return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
579006f32e7eSjoerg   }
579106f32e7eSjoerg 
579206f32e7eSjoerg   return {SPF_UNKNOWN, SPNB_NA, false};
579306f32e7eSjoerg }
579406f32e7eSjoerg 
isKnownNegation(const Value * X,const Value * Y,bool NeedNSW)579506f32e7eSjoerg bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
579606f32e7eSjoerg   assert(X && Y && "Invalid operand");
579706f32e7eSjoerg 
579806f32e7eSjoerg   // X = sub (0, Y) || X = sub nsw (0, Y)
579906f32e7eSjoerg   if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
580006f32e7eSjoerg       (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
580106f32e7eSjoerg     return true;
580206f32e7eSjoerg 
580306f32e7eSjoerg   // Y = sub (0, X) || Y = sub nsw (0, X)
580406f32e7eSjoerg   if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
580506f32e7eSjoerg       (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
580606f32e7eSjoerg     return true;
580706f32e7eSjoerg 
580806f32e7eSjoerg   // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
580906f32e7eSjoerg   Value *A, *B;
581006f32e7eSjoerg   return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
581106f32e7eSjoerg                         match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
581206f32e7eSjoerg          (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
581306f32e7eSjoerg                        match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
581406f32e7eSjoerg }
581506f32e7eSjoerg 
matchSelectPattern(CmpInst::Predicate Pred,FastMathFlags FMF,Value * CmpLHS,Value * CmpRHS,Value * TrueVal,Value * FalseVal,Value * & LHS,Value * & RHS,unsigned Depth)581606f32e7eSjoerg static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
581706f32e7eSjoerg                                               FastMathFlags FMF,
581806f32e7eSjoerg                                               Value *CmpLHS, Value *CmpRHS,
581906f32e7eSjoerg                                               Value *TrueVal, Value *FalseVal,
582006f32e7eSjoerg                                               Value *&LHS, Value *&RHS,
582106f32e7eSjoerg                                               unsigned Depth) {
582206f32e7eSjoerg   if (CmpInst::isFPPredicate(Pred)) {
582306f32e7eSjoerg     // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
582406f32e7eSjoerg     // 0.0 operand, set the compare's 0.0 operands to that same value for the
582506f32e7eSjoerg     // purpose of identifying min/max. Disregard vector constants with undefined
582606f32e7eSjoerg     // elements because those can not be back-propagated for analysis.
582706f32e7eSjoerg     Value *OutputZeroVal = nullptr;
582806f32e7eSjoerg     if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
5829*da58b97aSjoerg         !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
583006f32e7eSjoerg       OutputZeroVal = TrueVal;
583106f32e7eSjoerg     else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
5832*da58b97aSjoerg              !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
583306f32e7eSjoerg       OutputZeroVal = FalseVal;
583406f32e7eSjoerg 
583506f32e7eSjoerg     if (OutputZeroVal) {
583606f32e7eSjoerg       if (match(CmpLHS, m_AnyZeroFP()))
583706f32e7eSjoerg         CmpLHS = OutputZeroVal;
583806f32e7eSjoerg       if (match(CmpRHS, m_AnyZeroFP()))
583906f32e7eSjoerg         CmpRHS = OutputZeroVal;
584006f32e7eSjoerg     }
584106f32e7eSjoerg   }
584206f32e7eSjoerg 
584306f32e7eSjoerg   LHS = CmpLHS;
584406f32e7eSjoerg   RHS = CmpRHS;
584506f32e7eSjoerg 
584606f32e7eSjoerg   // Signed zero may return inconsistent results between implementations.
584706f32e7eSjoerg   //  (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
584806f32e7eSjoerg   //  minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
584906f32e7eSjoerg   // Therefore, we behave conservatively and only proceed if at least one of the
585006f32e7eSjoerg   // operands is known to not be zero or if we don't care about signed zero.
585106f32e7eSjoerg   switch (Pred) {
585206f32e7eSjoerg   default: break;
585306f32e7eSjoerg   // FIXME: Include OGT/OLT/UGT/ULT.
585406f32e7eSjoerg   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
585506f32e7eSjoerg   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
585606f32e7eSjoerg     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
585706f32e7eSjoerg         !isKnownNonZero(CmpRHS))
585806f32e7eSjoerg       return {SPF_UNKNOWN, SPNB_NA, false};
585906f32e7eSjoerg   }
586006f32e7eSjoerg 
586106f32e7eSjoerg   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
586206f32e7eSjoerg   bool Ordered = false;
586306f32e7eSjoerg 
586406f32e7eSjoerg   // When given one NaN and one non-NaN input:
586506f32e7eSjoerg   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
586606f32e7eSjoerg   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
586706f32e7eSjoerg   //     ordered comparison fails), which could be NaN or non-NaN.
586806f32e7eSjoerg   // so here we discover exactly what NaN behavior is required/accepted.
586906f32e7eSjoerg   if (CmpInst::isFPPredicate(Pred)) {
587006f32e7eSjoerg     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
587106f32e7eSjoerg     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
587206f32e7eSjoerg 
587306f32e7eSjoerg     if (LHSSafe && RHSSafe) {
587406f32e7eSjoerg       // Both operands are known non-NaN.
587506f32e7eSjoerg       NaNBehavior = SPNB_RETURNS_ANY;
587606f32e7eSjoerg     } else if (CmpInst::isOrdered(Pred)) {
587706f32e7eSjoerg       // An ordered comparison will return false when given a NaN, so it
587806f32e7eSjoerg       // returns the RHS.
587906f32e7eSjoerg       Ordered = true;
588006f32e7eSjoerg       if (LHSSafe)
588106f32e7eSjoerg         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
588206f32e7eSjoerg         NaNBehavior = SPNB_RETURNS_NAN;
588306f32e7eSjoerg       else if (RHSSafe)
588406f32e7eSjoerg         NaNBehavior = SPNB_RETURNS_OTHER;
588506f32e7eSjoerg       else
588606f32e7eSjoerg         // Completely unsafe.
588706f32e7eSjoerg         return {SPF_UNKNOWN, SPNB_NA, false};
588806f32e7eSjoerg     } else {
588906f32e7eSjoerg       Ordered = false;
589006f32e7eSjoerg       // An unordered comparison will return true when given a NaN, so it
589106f32e7eSjoerg       // returns the LHS.
589206f32e7eSjoerg       if (LHSSafe)
589306f32e7eSjoerg         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
589406f32e7eSjoerg         NaNBehavior = SPNB_RETURNS_OTHER;
589506f32e7eSjoerg       else if (RHSSafe)
589606f32e7eSjoerg         NaNBehavior = SPNB_RETURNS_NAN;
589706f32e7eSjoerg       else
589806f32e7eSjoerg         // Completely unsafe.
589906f32e7eSjoerg         return {SPF_UNKNOWN, SPNB_NA, false};
590006f32e7eSjoerg     }
590106f32e7eSjoerg   }
590206f32e7eSjoerg 
590306f32e7eSjoerg   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
590406f32e7eSjoerg     std::swap(CmpLHS, CmpRHS);
590506f32e7eSjoerg     Pred = CmpInst::getSwappedPredicate(Pred);
590606f32e7eSjoerg     if (NaNBehavior == SPNB_RETURNS_NAN)
590706f32e7eSjoerg       NaNBehavior = SPNB_RETURNS_OTHER;
590806f32e7eSjoerg     else if (NaNBehavior == SPNB_RETURNS_OTHER)
590906f32e7eSjoerg       NaNBehavior = SPNB_RETURNS_NAN;
591006f32e7eSjoerg     Ordered = !Ordered;
591106f32e7eSjoerg   }
591206f32e7eSjoerg 
591306f32e7eSjoerg   // ([if]cmp X, Y) ? X : Y
591406f32e7eSjoerg   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
591506f32e7eSjoerg     switch (Pred) {
591606f32e7eSjoerg     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
591706f32e7eSjoerg     case ICmpInst::ICMP_UGT:
591806f32e7eSjoerg     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
591906f32e7eSjoerg     case ICmpInst::ICMP_SGT:
592006f32e7eSjoerg     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
592106f32e7eSjoerg     case ICmpInst::ICMP_ULT:
592206f32e7eSjoerg     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
592306f32e7eSjoerg     case ICmpInst::ICMP_SLT:
592406f32e7eSjoerg     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
592506f32e7eSjoerg     case FCmpInst::FCMP_UGT:
592606f32e7eSjoerg     case FCmpInst::FCMP_UGE:
592706f32e7eSjoerg     case FCmpInst::FCMP_OGT:
592806f32e7eSjoerg     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
592906f32e7eSjoerg     case FCmpInst::FCMP_ULT:
593006f32e7eSjoerg     case FCmpInst::FCMP_ULE:
593106f32e7eSjoerg     case FCmpInst::FCMP_OLT:
593206f32e7eSjoerg     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
593306f32e7eSjoerg     }
593406f32e7eSjoerg   }
593506f32e7eSjoerg 
593606f32e7eSjoerg   if (isKnownNegation(TrueVal, FalseVal)) {
593706f32e7eSjoerg     // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
593806f32e7eSjoerg     // match against either LHS or sext(LHS).
593906f32e7eSjoerg     auto MaybeSExtCmpLHS =
594006f32e7eSjoerg         m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
594106f32e7eSjoerg     auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
594206f32e7eSjoerg     auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
594306f32e7eSjoerg     if (match(TrueVal, MaybeSExtCmpLHS)) {
594406f32e7eSjoerg       // Set the return values. If the compare uses the negated value (-X >s 0),
594506f32e7eSjoerg       // swap the return values because the negated value is always 'RHS'.
594606f32e7eSjoerg       LHS = TrueVal;
594706f32e7eSjoerg       RHS = FalseVal;
594806f32e7eSjoerg       if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
594906f32e7eSjoerg         std::swap(LHS, RHS);
595006f32e7eSjoerg 
595106f32e7eSjoerg       // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
595206f32e7eSjoerg       // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
595306f32e7eSjoerg       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
595406f32e7eSjoerg         return {SPF_ABS, SPNB_NA, false};
595506f32e7eSjoerg 
595606f32e7eSjoerg       // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
595706f32e7eSjoerg       if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
595806f32e7eSjoerg         return {SPF_ABS, SPNB_NA, false};
595906f32e7eSjoerg 
596006f32e7eSjoerg       // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
596106f32e7eSjoerg       // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
596206f32e7eSjoerg       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
596306f32e7eSjoerg         return {SPF_NABS, SPNB_NA, false};
596406f32e7eSjoerg     }
596506f32e7eSjoerg     else if (match(FalseVal, MaybeSExtCmpLHS)) {
596606f32e7eSjoerg       // Set the return values. If the compare uses the negated value (-X >s 0),
596706f32e7eSjoerg       // swap the return values because the negated value is always 'RHS'.
596806f32e7eSjoerg       LHS = FalseVal;
596906f32e7eSjoerg       RHS = TrueVal;
597006f32e7eSjoerg       if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
597106f32e7eSjoerg         std::swap(LHS, RHS);
597206f32e7eSjoerg 
597306f32e7eSjoerg       // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
597406f32e7eSjoerg       // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
597506f32e7eSjoerg       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
597606f32e7eSjoerg         return {SPF_NABS, SPNB_NA, false};
597706f32e7eSjoerg 
597806f32e7eSjoerg       // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
597906f32e7eSjoerg       // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
598006f32e7eSjoerg       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
598106f32e7eSjoerg         return {SPF_ABS, SPNB_NA, false};
598206f32e7eSjoerg     }
598306f32e7eSjoerg   }
598406f32e7eSjoerg 
598506f32e7eSjoerg   if (CmpInst::isIntPredicate(Pred))
598606f32e7eSjoerg     return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
598706f32e7eSjoerg 
598806f32e7eSjoerg   // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
598906f32e7eSjoerg   // may return either -0.0 or 0.0, so fcmp/select pair has stricter
599006f32e7eSjoerg   // semantics than minNum. Be conservative in such case.
599106f32e7eSjoerg   if (NaNBehavior != SPNB_RETURNS_ANY ||
599206f32e7eSjoerg       (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
599306f32e7eSjoerg        !isKnownNonZero(CmpRHS)))
599406f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
599506f32e7eSjoerg 
599606f32e7eSjoerg   return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
599706f32e7eSjoerg }
599806f32e7eSjoerg 
599906f32e7eSjoerg /// Helps to match a select pattern in case of a type mismatch.
600006f32e7eSjoerg ///
600106f32e7eSjoerg /// The function processes the case when type of true and false values of a
600206f32e7eSjoerg /// select instruction differs from type of the cmp instruction operands because
600306f32e7eSjoerg /// of a cast instruction. The function checks if it is legal to move the cast
600406f32e7eSjoerg /// operation after "select". If yes, it returns the new second value of
600506f32e7eSjoerg /// "select" (with the assumption that cast is moved):
600606f32e7eSjoerg /// 1. As operand of cast instruction when both values of "select" are same cast
600706f32e7eSjoerg /// instructions.
600806f32e7eSjoerg /// 2. As restored constant (by applying reverse cast operation) when the first
600906f32e7eSjoerg /// value of the "select" is a cast operation and the second value is a
601006f32e7eSjoerg /// constant.
601106f32e7eSjoerg /// NOTE: We return only the new second value because the first value could be
601206f32e7eSjoerg /// accessed as operand of cast instruction.
lookThroughCast(CmpInst * CmpI,Value * V1,Value * V2,Instruction::CastOps * CastOp)601306f32e7eSjoerg static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
601406f32e7eSjoerg                               Instruction::CastOps *CastOp) {
601506f32e7eSjoerg   auto *Cast1 = dyn_cast<CastInst>(V1);
601606f32e7eSjoerg   if (!Cast1)
601706f32e7eSjoerg     return nullptr;
601806f32e7eSjoerg 
601906f32e7eSjoerg   *CastOp = Cast1->getOpcode();
602006f32e7eSjoerg   Type *SrcTy = Cast1->getSrcTy();
602106f32e7eSjoerg   if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
602206f32e7eSjoerg     // If V1 and V2 are both the same cast from the same type, look through V1.
602306f32e7eSjoerg     if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
602406f32e7eSjoerg       return Cast2->getOperand(0);
602506f32e7eSjoerg     return nullptr;
602606f32e7eSjoerg   }
602706f32e7eSjoerg 
602806f32e7eSjoerg   auto *C = dyn_cast<Constant>(V2);
602906f32e7eSjoerg   if (!C)
603006f32e7eSjoerg     return nullptr;
603106f32e7eSjoerg 
603206f32e7eSjoerg   Constant *CastedTo = nullptr;
603306f32e7eSjoerg   switch (*CastOp) {
603406f32e7eSjoerg   case Instruction::ZExt:
603506f32e7eSjoerg     if (CmpI->isUnsigned())
603606f32e7eSjoerg       CastedTo = ConstantExpr::getTrunc(C, SrcTy);
603706f32e7eSjoerg     break;
603806f32e7eSjoerg   case Instruction::SExt:
603906f32e7eSjoerg     if (CmpI->isSigned())
604006f32e7eSjoerg       CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
604106f32e7eSjoerg     break;
604206f32e7eSjoerg   case Instruction::Trunc:
604306f32e7eSjoerg     Constant *CmpConst;
604406f32e7eSjoerg     if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
604506f32e7eSjoerg         CmpConst->getType() == SrcTy) {
604606f32e7eSjoerg       // Here we have the following case:
604706f32e7eSjoerg       //
604806f32e7eSjoerg       //   %cond = cmp iN %x, CmpConst
604906f32e7eSjoerg       //   %tr = trunc iN %x to iK
605006f32e7eSjoerg       //   %narrowsel = select i1 %cond, iK %t, iK C
605106f32e7eSjoerg       //
605206f32e7eSjoerg       // We can always move trunc after select operation:
605306f32e7eSjoerg       //
605406f32e7eSjoerg       //   %cond = cmp iN %x, CmpConst
605506f32e7eSjoerg       //   %widesel = select i1 %cond, iN %x, iN CmpConst
605606f32e7eSjoerg       //   %tr = trunc iN %widesel to iK
605706f32e7eSjoerg       //
605806f32e7eSjoerg       // Note that C could be extended in any way because we don't care about
605906f32e7eSjoerg       // upper bits after truncation. It can't be abs pattern, because it would
606006f32e7eSjoerg       // look like:
606106f32e7eSjoerg       //
606206f32e7eSjoerg       //   select i1 %cond, x, -x.
606306f32e7eSjoerg       //
606406f32e7eSjoerg       // So only min/max pattern could be matched. Such match requires widened C
606506f32e7eSjoerg       // == CmpConst. That is why set widened C = CmpConst, condition trunc
606606f32e7eSjoerg       // CmpConst == C is checked below.
606706f32e7eSjoerg       CastedTo = CmpConst;
606806f32e7eSjoerg     } else {
606906f32e7eSjoerg       CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
607006f32e7eSjoerg     }
607106f32e7eSjoerg     break;
607206f32e7eSjoerg   case Instruction::FPTrunc:
607306f32e7eSjoerg     CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
607406f32e7eSjoerg     break;
607506f32e7eSjoerg   case Instruction::FPExt:
607606f32e7eSjoerg     CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
607706f32e7eSjoerg     break;
607806f32e7eSjoerg   case Instruction::FPToUI:
607906f32e7eSjoerg     CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
608006f32e7eSjoerg     break;
608106f32e7eSjoerg   case Instruction::FPToSI:
608206f32e7eSjoerg     CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
608306f32e7eSjoerg     break;
608406f32e7eSjoerg   case Instruction::UIToFP:
608506f32e7eSjoerg     CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
608606f32e7eSjoerg     break;
608706f32e7eSjoerg   case Instruction::SIToFP:
608806f32e7eSjoerg     CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
608906f32e7eSjoerg     break;
609006f32e7eSjoerg   default:
609106f32e7eSjoerg     break;
609206f32e7eSjoerg   }
609306f32e7eSjoerg 
609406f32e7eSjoerg   if (!CastedTo)
609506f32e7eSjoerg     return nullptr;
609606f32e7eSjoerg 
609706f32e7eSjoerg   // Make sure the cast doesn't lose any information.
609806f32e7eSjoerg   Constant *CastedBack =
609906f32e7eSjoerg       ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
610006f32e7eSjoerg   if (CastedBack != C)
610106f32e7eSjoerg     return nullptr;
610206f32e7eSjoerg 
610306f32e7eSjoerg   return CastedTo;
610406f32e7eSjoerg }
610506f32e7eSjoerg 
matchSelectPattern(Value * V,Value * & LHS,Value * & RHS,Instruction::CastOps * CastOp,unsigned Depth)610606f32e7eSjoerg SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
610706f32e7eSjoerg                                              Instruction::CastOps *CastOp,
610806f32e7eSjoerg                                              unsigned Depth) {
6109*da58b97aSjoerg   if (Depth >= MaxAnalysisRecursionDepth)
611006f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
611106f32e7eSjoerg 
611206f32e7eSjoerg   SelectInst *SI = dyn_cast<SelectInst>(V);
611306f32e7eSjoerg   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
611406f32e7eSjoerg 
611506f32e7eSjoerg   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
611606f32e7eSjoerg   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
611706f32e7eSjoerg 
611806f32e7eSjoerg   Value *TrueVal = SI->getTrueValue();
611906f32e7eSjoerg   Value *FalseVal = SI->getFalseValue();
612006f32e7eSjoerg 
612106f32e7eSjoerg   return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
612206f32e7eSjoerg                                             CastOp, Depth);
612306f32e7eSjoerg }
612406f32e7eSjoerg 
matchDecomposedSelectPattern(CmpInst * CmpI,Value * TrueVal,Value * FalseVal,Value * & LHS,Value * & RHS,Instruction::CastOps * CastOp,unsigned Depth)612506f32e7eSjoerg SelectPatternResult llvm::matchDecomposedSelectPattern(
612606f32e7eSjoerg     CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
612706f32e7eSjoerg     Instruction::CastOps *CastOp, unsigned Depth) {
612806f32e7eSjoerg   CmpInst::Predicate Pred = CmpI->getPredicate();
612906f32e7eSjoerg   Value *CmpLHS = CmpI->getOperand(0);
613006f32e7eSjoerg   Value *CmpRHS = CmpI->getOperand(1);
613106f32e7eSjoerg   FastMathFlags FMF;
613206f32e7eSjoerg   if (isa<FPMathOperator>(CmpI))
613306f32e7eSjoerg     FMF = CmpI->getFastMathFlags();
613406f32e7eSjoerg 
613506f32e7eSjoerg   // Bail out early.
613606f32e7eSjoerg   if (CmpI->isEquality())
613706f32e7eSjoerg     return {SPF_UNKNOWN, SPNB_NA, false};
613806f32e7eSjoerg 
613906f32e7eSjoerg   // Deal with type mismatches.
614006f32e7eSjoerg   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
614106f32e7eSjoerg     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
614206f32e7eSjoerg       // If this is a potential fmin/fmax with a cast to integer, then ignore
614306f32e7eSjoerg       // -0.0 because there is no corresponding integer value.
614406f32e7eSjoerg       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
614506f32e7eSjoerg         FMF.setNoSignedZeros();
614606f32e7eSjoerg       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
614706f32e7eSjoerg                                   cast<CastInst>(TrueVal)->getOperand(0), C,
614806f32e7eSjoerg                                   LHS, RHS, Depth);
614906f32e7eSjoerg     }
615006f32e7eSjoerg     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
615106f32e7eSjoerg       // If this is a potential fmin/fmax with a cast to integer, then ignore
615206f32e7eSjoerg       // -0.0 because there is no corresponding integer value.
615306f32e7eSjoerg       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
615406f32e7eSjoerg         FMF.setNoSignedZeros();
615506f32e7eSjoerg       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
615606f32e7eSjoerg                                   C, cast<CastInst>(FalseVal)->getOperand(0),
615706f32e7eSjoerg                                   LHS, RHS, Depth);
615806f32e7eSjoerg     }
615906f32e7eSjoerg   }
616006f32e7eSjoerg   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
616106f32e7eSjoerg                               LHS, RHS, Depth);
616206f32e7eSjoerg }
616306f32e7eSjoerg 
getMinMaxPred(SelectPatternFlavor SPF,bool Ordered)616406f32e7eSjoerg CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
616506f32e7eSjoerg   if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
616606f32e7eSjoerg   if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
616706f32e7eSjoerg   if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
616806f32e7eSjoerg   if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
616906f32e7eSjoerg   if (SPF == SPF_FMINNUM)
617006f32e7eSjoerg     return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
617106f32e7eSjoerg   if (SPF == SPF_FMAXNUM)
617206f32e7eSjoerg     return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
617306f32e7eSjoerg   llvm_unreachable("unhandled!");
617406f32e7eSjoerg }
617506f32e7eSjoerg 
getInverseMinMaxFlavor(SelectPatternFlavor SPF)617606f32e7eSjoerg SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
617706f32e7eSjoerg   if (SPF == SPF_SMIN) return SPF_SMAX;
617806f32e7eSjoerg   if (SPF == SPF_UMIN) return SPF_UMAX;
617906f32e7eSjoerg   if (SPF == SPF_SMAX) return SPF_SMIN;
618006f32e7eSjoerg   if (SPF == SPF_UMAX) return SPF_UMIN;
618106f32e7eSjoerg   llvm_unreachable("unhandled!");
618206f32e7eSjoerg }
618306f32e7eSjoerg 
getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)6184*da58b97aSjoerg Intrinsic::ID llvm::getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID) {
6185*da58b97aSjoerg   switch (MinMaxID) {
6186*da58b97aSjoerg   case Intrinsic::smax: return Intrinsic::smin;
6187*da58b97aSjoerg   case Intrinsic::smin: return Intrinsic::smax;
6188*da58b97aSjoerg   case Intrinsic::umax: return Intrinsic::umin;
6189*da58b97aSjoerg   case Intrinsic::umin: return Intrinsic::umax;
6190*da58b97aSjoerg   default: llvm_unreachable("Unexpected intrinsic");
6191*da58b97aSjoerg   }
6192*da58b97aSjoerg }
6193*da58b97aSjoerg 
getInverseMinMaxPred(SelectPatternFlavor SPF)619406f32e7eSjoerg CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
619506f32e7eSjoerg   return getMinMaxPred(getInverseMinMaxFlavor(SPF));
619606f32e7eSjoerg }
619706f32e7eSjoerg 
6198*da58b97aSjoerg std::pair<Intrinsic::ID, bool>
canConvertToMinOrMaxIntrinsic(ArrayRef<Value * > VL)6199*da58b97aSjoerg llvm::canConvertToMinOrMaxIntrinsic(ArrayRef<Value *> VL) {
6200*da58b97aSjoerg   // Check if VL contains select instructions that can be folded into a min/max
6201*da58b97aSjoerg   // vector intrinsic and return the intrinsic if it is possible.
6202*da58b97aSjoerg   // TODO: Support floating point min/max.
6203*da58b97aSjoerg   bool AllCmpSingleUse = true;
6204*da58b97aSjoerg   SelectPatternResult SelectPattern;
6205*da58b97aSjoerg   SelectPattern.Flavor = SPF_UNKNOWN;
6206*da58b97aSjoerg   if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
6207*da58b97aSjoerg         Value *LHS, *RHS;
6208*da58b97aSjoerg         auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
6209*da58b97aSjoerg         if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor) ||
6210*da58b97aSjoerg             CurrentPattern.Flavor == SPF_FMINNUM ||
6211*da58b97aSjoerg             CurrentPattern.Flavor == SPF_FMAXNUM ||
6212*da58b97aSjoerg             !I->getType()->isIntOrIntVectorTy())
6213*da58b97aSjoerg           return false;
6214*da58b97aSjoerg         if (SelectPattern.Flavor != SPF_UNKNOWN &&
6215*da58b97aSjoerg             SelectPattern.Flavor != CurrentPattern.Flavor)
6216*da58b97aSjoerg           return false;
6217*da58b97aSjoerg         SelectPattern = CurrentPattern;
6218*da58b97aSjoerg         AllCmpSingleUse &=
6219*da58b97aSjoerg             match(I, m_Select(m_OneUse(m_Value()), m_Value(), m_Value()));
6220*da58b97aSjoerg         return true;
6221*da58b97aSjoerg       })) {
6222*da58b97aSjoerg     switch (SelectPattern.Flavor) {
6223*da58b97aSjoerg     case SPF_SMIN:
6224*da58b97aSjoerg       return {Intrinsic::smin, AllCmpSingleUse};
6225*da58b97aSjoerg     case SPF_UMIN:
6226*da58b97aSjoerg       return {Intrinsic::umin, AllCmpSingleUse};
6227*da58b97aSjoerg     case SPF_SMAX:
6228*da58b97aSjoerg       return {Intrinsic::smax, AllCmpSingleUse};
6229*da58b97aSjoerg     case SPF_UMAX:
6230*da58b97aSjoerg       return {Intrinsic::umax, AllCmpSingleUse};
6231*da58b97aSjoerg     default:
6232*da58b97aSjoerg       llvm_unreachable("unexpected select pattern flavor");
6233*da58b97aSjoerg     }
6234*da58b97aSjoerg   }
6235*da58b97aSjoerg   return {Intrinsic::not_intrinsic, false};
6236*da58b97aSjoerg }
6237*da58b97aSjoerg 
matchSimpleRecurrence(const PHINode * P,BinaryOperator * & BO,Value * & Start,Value * & Step)6238*da58b97aSjoerg bool llvm::matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO,
6239*da58b97aSjoerg                                  Value *&Start, Value *&Step) {
6240*da58b97aSjoerg   // Handle the case of a simple two-predecessor recurrence PHI.
6241*da58b97aSjoerg   // There's a lot more that could theoretically be done here, but
6242*da58b97aSjoerg   // this is sufficient to catch some interesting cases.
6243*da58b97aSjoerg   if (P->getNumIncomingValues() != 2)
6244*da58b97aSjoerg     return false;
6245*da58b97aSjoerg 
6246*da58b97aSjoerg   for (unsigned i = 0; i != 2; ++i) {
6247*da58b97aSjoerg     Value *L = P->getIncomingValue(i);
6248*da58b97aSjoerg     Value *R = P->getIncomingValue(!i);
6249*da58b97aSjoerg     Operator *LU = dyn_cast<Operator>(L);
6250*da58b97aSjoerg     if (!LU)
6251*da58b97aSjoerg       continue;
6252*da58b97aSjoerg     unsigned Opcode = LU->getOpcode();
6253*da58b97aSjoerg 
6254*da58b97aSjoerg     switch (Opcode) {
6255*da58b97aSjoerg     default:
6256*da58b97aSjoerg       continue;
6257*da58b97aSjoerg     // TODO: Expand list -- xor, div, gep, uaddo, etc..
6258*da58b97aSjoerg     case Instruction::LShr:
6259*da58b97aSjoerg     case Instruction::AShr:
6260*da58b97aSjoerg     case Instruction::Shl:
6261*da58b97aSjoerg     case Instruction::Add:
6262*da58b97aSjoerg     case Instruction::Sub:
6263*da58b97aSjoerg     case Instruction::And:
6264*da58b97aSjoerg     case Instruction::Or:
6265*da58b97aSjoerg     case Instruction::Mul: {
6266*da58b97aSjoerg       Value *LL = LU->getOperand(0);
6267*da58b97aSjoerg       Value *LR = LU->getOperand(1);
6268*da58b97aSjoerg       // Find a recurrence.
6269*da58b97aSjoerg       if (LL == P)
6270*da58b97aSjoerg         L = LR;
6271*da58b97aSjoerg       else if (LR == P)
6272*da58b97aSjoerg         L = LL;
6273*da58b97aSjoerg       else
6274*da58b97aSjoerg         continue; // Check for recurrence with L and R flipped.
6275*da58b97aSjoerg 
6276*da58b97aSjoerg       break; // Match!
6277*da58b97aSjoerg     }
6278*da58b97aSjoerg     };
6279*da58b97aSjoerg 
6280*da58b97aSjoerg     // We have matched a recurrence of the form:
6281*da58b97aSjoerg     //   %iv = [R, %entry], [%iv.next, %backedge]
6282*da58b97aSjoerg     //   %iv.next = binop %iv, L
6283*da58b97aSjoerg     // OR
6284*da58b97aSjoerg     //   %iv = [R, %entry], [%iv.next, %backedge]
6285*da58b97aSjoerg     //   %iv.next = binop L, %iv
6286*da58b97aSjoerg     BO = cast<BinaryOperator>(LU);
6287*da58b97aSjoerg     Start = R;
6288*da58b97aSjoerg     Step = L;
6289*da58b97aSjoerg     return true;
6290*da58b97aSjoerg   }
6291*da58b97aSjoerg   return false;
6292*da58b97aSjoerg }
6293*da58b97aSjoerg 
matchSimpleRecurrence(const BinaryOperator * I,PHINode * & P,Value * & Start,Value * & Step)6294*da58b97aSjoerg bool llvm::matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P,
6295*da58b97aSjoerg                                  Value *&Start, Value *&Step) {
6296*da58b97aSjoerg   BinaryOperator *BO = nullptr;
6297*da58b97aSjoerg   P = dyn_cast<PHINode>(I->getOperand(0));
6298*da58b97aSjoerg   if (!P)
6299*da58b97aSjoerg     P = dyn_cast<PHINode>(I->getOperand(1));
6300*da58b97aSjoerg   return P && matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
6301*da58b97aSjoerg }
6302*da58b97aSjoerg 
630306f32e7eSjoerg /// Return true if "icmp Pred LHS RHS" is always true.
isTruePredicate(CmpInst::Predicate Pred,const Value * LHS,const Value * RHS,const DataLayout & DL,unsigned Depth)630406f32e7eSjoerg static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
630506f32e7eSjoerg                             const Value *RHS, const DataLayout &DL,
630606f32e7eSjoerg                             unsigned Depth) {
630706f32e7eSjoerg   assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
630806f32e7eSjoerg   if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
630906f32e7eSjoerg     return true;
631006f32e7eSjoerg 
631106f32e7eSjoerg   switch (Pred) {
631206f32e7eSjoerg   default:
631306f32e7eSjoerg     return false;
631406f32e7eSjoerg 
631506f32e7eSjoerg   case CmpInst::ICMP_SLE: {
631606f32e7eSjoerg     const APInt *C;
631706f32e7eSjoerg 
631806f32e7eSjoerg     // LHS s<= LHS +_{nsw} C   if C >= 0
631906f32e7eSjoerg     if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
632006f32e7eSjoerg       return !C->isNegative();
632106f32e7eSjoerg     return false;
632206f32e7eSjoerg   }
632306f32e7eSjoerg 
632406f32e7eSjoerg   case CmpInst::ICMP_ULE: {
632506f32e7eSjoerg     const APInt *C;
632606f32e7eSjoerg 
632706f32e7eSjoerg     // LHS u<= LHS +_{nuw} C   for any C
632806f32e7eSjoerg     if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
632906f32e7eSjoerg       return true;
633006f32e7eSjoerg 
633106f32e7eSjoerg     // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
633206f32e7eSjoerg     auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
633306f32e7eSjoerg                                        const Value *&X,
633406f32e7eSjoerg                                        const APInt *&CA, const APInt *&CB) {
633506f32e7eSjoerg       if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
633606f32e7eSjoerg           match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
633706f32e7eSjoerg         return true;
633806f32e7eSjoerg 
633906f32e7eSjoerg       // If X & C == 0 then (X | C) == X +_{nuw} C
634006f32e7eSjoerg       if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
634106f32e7eSjoerg           match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
634206f32e7eSjoerg         KnownBits Known(CA->getBitWidth());
634306f32e7eSjoerg         computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
634406f32e7eSjoerg                          /*CxtI*/ nullptr, /*DT*/ nullptr);
634506f32e7eSjoerg         if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
634606f32e7eSjoerg           return true;
634706f32e7eSjoerg       }
634806f32e7eSjoerg 
634906f32e7eSjoerg       return false;
635006f32e7eSjoerg     };
635106f32e7eSjoerg 
635206f32e7eSjoerg     const Value *X;
635306f32e7eSjoerg     const APInt *CLHS, *CRHS;
635406f32e7eSjoerg     if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
635506f32e7eSjoerg       return CLHS->ule(*CRHS);
635606f32e7eSjoerg 
635706f32e7eSjoerg     return false;
635806f32e7eSjoerg   }
635906f32e7eSjoerg   }
636006f32e7eSjoerg }
636106f32e7eSjoerg 
636206f32e7eSjoerg /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
636306f32e7eSjoerg /// ALHS ARHS" is true.  Otherwise, return None.
636406f32e7eSjoerg static Optional<bool>
isImpliedCondOperands(CmpInst::Predicate Pred,const Value * ALHS,const Value * ARHS,const Value * BLHS,const Value * BRHS,const DataLayout & DL,unsigned Depth)636506f32e7eSjoerg isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
636606f32e7eSjoerg                       const Value *ARHS, const Value *BLHS, const Value *BRHS,
636706f32e7eSjoerg                       const DataLayout &DL, unsigned Depth) {
636806f32e7eSjoerg   switch (Pred) {
636906f32e7eSjoerg   default:
637006f32e7eSjoerg     return None;
637106f32e7eSjoerg 
637206f32e7eSjoerg   case CmpInst::ICMP_SLT:
637306f32e7eSjoerg   case CmpInst::ICMP_SLE:
637406f32e7eSjoerg     if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
637506f32e7eSjoerg         isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
637606f32e7eSjoerg       return true;
637706f32e7eSjoerg     return None;
637806f32e7eSjoerg 
637906f32e7eSjoerg   case CmpInst::ICMP_ULT:
638006f32e7eSjoerg   case CmpInst::ICMP_ULE:
638106f32e7eSjoerg     if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
638206f32e7eSjoerg         isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
638306f32e7eSjoerg       return true;
638406f32e7eSjoerg     return None;
638506f32e7eSjoerg   }
638606f32e7eSjoerg }
638706f32e7eSjoerg 
638806f32e7eSjoerg /// Return true if the operands of the two compares match.  IsSwappedOps is true
638906f32e7eSjoerg /// when the operands match, but are swapped.
isMatchingOps(const Value * ALHS,const Value * ARHS,const Value * BLHS,const Value * BRHS,bool & IsSwappedOps)639006f32e7eSjoerg static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
639106f32e7eSjoerg                           const Value *BLHS, const Value *BRHS,
639206f32e7eSjoerg                           bool &IsSwappedOps) {
639306f32e7eSjoerg 
639406f32e7eSjoerg   bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
639506f32e7eSjoerg   IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
639606f32e7eSjoerg   return IsMatchingOps || IsSwappedOps;
639706f32e7eSjoerg }
639806f32e7eSjoerg 
639906f32e7eSjoerg /// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
640006f32e7eSjoerg /// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
640106f32e7eSjoerg /// Otherwise, return None if we can't infer anything.
isImpliedCondMatchingOperands(CmpInst::Predicate APred,CmpInst::Predicate BPred,bool AreSwappedOps)640206f32e7eSjoerg static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
640306f32e7eSjoerg                                                     CmpInst::Predicate BPred,
640406f32e7eSjoerg                                                     bool AreSwappedOps) {
640506f32e7eSjoerg   // Canonicalize the predicate as if the operands were not commuted.
640606f32e7eSjoerg   if (AreSwappedOps)
640706f32e7eSjoerg     BPred = ICmpInst::getSwappedPredicate(BPred);
640806f32e7eSjoerg 
640906f32e7eSjoerg   if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
641006f32e7eSjoerg     return true;
641106f32e7eSjoerg   if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
641206f32e7eSjoerg     return false;
641306f32e7eSjoerg 
641406f32e7eSjoerg   return None;
641506f32e7eSjoerg }
641606f32e7eSjoerg 
641706f32e7eSjoerg /// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
641806f32e7eSjoerg /// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
641906f32e7eSjoerg /// Otherwise, return None if we can't infer anything.
642006f32e7eSjoerg static Optional<bool>
isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,const ConstantInt * C1,CmpInst::Predicate BPred,const ConstantInt * C2)642106f32e7eSjoerg isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
642206f32e7eSjoerg                                  const ConstantInt *C1,
642306f32e7eSjoerg                                  CmpInst::Predicate BPred,
642406f32e7eSjoerg                                  const ConstantInt *C2) {
642506f32e7eSjoerg   ConstantRange DomCR =
642606f32e7eSjoerg       ConstantRange::makeExactICmpRegion(APred, C1->getValue());
642706f32e7eSjoerg   ConstantRange CR =
642806f32e7eSjoerg       ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
642906f32e7eSjoerg   ConstantRange Intersection = DomCR.intersectWith(CR);
643006f32e7eSjoerg   ConstantRange Difference = DomCR.difference(CR);
643106f32e7eSjoerg   if (Intersection.isEmptySet())
643206f32e7eSjoerg     return false;
643306f32e7eSjoerg   if (Difference.isEmptySet())
643406f32e7eSjoerg     return true;
643506f32e7eSjoerg   return None;
643606f32e7eSjoerg }
643706f32e7eSjoerg 
643806f32e7eSjoerg /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
643906f32e7eSjoerg /// false.  Otherwise, return None if we can't infer anything.
isImpliedCondICmps(const ICmpInst * LHS,CmpInst::Predicate BPred,const Value * BLHS,const Value * BRHS,const DataLayout & DL,bool LHSIsTrue,unsigned Depth)644006f32e7eSjoerg static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
6441*da58b97aSjoerg                                          CmpInst::Predicate BPred,
6442*da58b97aSjoerg                                          const Value *BLHS, const Value *BRHS,
644306f32e7eSjoerg                                          const DataLayout &DL, bool LHSIsTrue,
644406f32e7eSjoerg                                          unsigned Depth) {
644506f32e7eSjoerg   Value *ALHS = LHS->getOperand(0);
644606f32e7eSjoerg   Value *ARHS = LHS->getOperand(1);
6447*da58b97aSjoerg 
644806f32e7eSjoerg   // The rest of the logic assumes the LHS condition is true.  If that's not the
644906f32e7eSjoerg   // case, invert the predicate to make it so.
6450*da58b97aSjoerg   CmpInst::Predicate APred =
645106f32e7eSjoerg       LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
645206f32e7eSjoerg 
645306f32e7eSjoerg   // Can we infer anything when the two compares have matching operands?
645406f32e7eSjoerg   bool AreSwappedOps;
645506f32e7eSjoerg   if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
645606f32e7eSjoerg     if (Optional<bool> Implication = isImpliedCondMatchingOperands(
645706f32e7eSjoerg             APred, BPred, AreSwappedOps))
645806f32e7eSjoerg       return Implication;
645906f32e7eSjoerg     // No amount of additional analysis will infer the second condition, so
646006f32e7eSjoerg     // early exit.
646106f32e7eSjoerg     return None;
646206f32e7eSjoerg   }
646306f32e7eSjoerg 
646406f32e7eSjoerg   // Can we infer anything when the LHS operands match and the RHS operands are
646506f32e7eSjoerg   // constants (not necessarily matching)?
646606f32e7eSjoerg   if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
646706f32e7eSjoerg     if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
646806f32e7eSjoerg             APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
646906f32e7eSjoerg       return Implication;
647006f32e7eSjoerg     // No amount of additional analysis will infer the second condition, so
647106f32e7eSjoerg     // early exit.
647206f32e7eSjoerg     return None;
647306f32e7eSjoerg   }
647406f32e7eSjoerg 
647506f32e7eSjoerg   if (APred == BPred)
647606f32e7eSjoerg     return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
647706f32e7eSjoerg   return None;
647806f32e7eSjoerg }
647906f32e7eSjoerg 
648006f32e7eSjoerg /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
648106f32e7eSjoerg /// false.  Otherwise, return None if we can't infer anything.  We expect the
6482*da58b97aSjoerg /// RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select' instruction.
6483*da58b97aSjoerg static Optional<bool>
isImpliedCondAndOr(const Instruction * LHS,CmpInst::Predicate RHSPred,const Value * RHSOp0,const Value * RHSOp1,const DataLayout & DL,bool LHSIsTrue,unsigned Depth)6484*da58b97aSjoerg isImpliedCondAndOr(const Instruction *LHS, CmpInst::Predicate RHSPred,
6485*da58b97aSjoerg                    const Value *RHSOp0, const Value *RHSOp1,
6486*da58b97aSjoerg                    const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
6487*da58b97aSjoerg   // The LHS must be an 'or', 'and', or a 'select' instruction.
648806f32e7eSjoerg   assert((LHS->getOpcode() == Instruction::And ||
6489*da58b97aSjoerg           LHS->getOpcode() == Instruction::Or ||
6490*da58b97aSjoerg           LHS->getOpcode() == Instruction::Select) &&
6491*da58b97aSjoerg          "Expected LHS to be 'and', 'or', or 'select'.");
649206f32e7eSjoerg 
6493*da58b97aSjoerg   assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
649406f32e7eSjoerg 
649506f32e7eSjoerg   // If the result of an 'or' is false, then we know both legs of the 'or' are
649606f32e7eSjoerg   // false.  Similarly, if the result of an 'and' is true, then we know both
649706f32e7eSjoerg   // legs of the 'and' are true.
6498*da58b97aSjoerg   const Value *ALHS, *ARHS;
6499*da58b97aSjoerg   if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
6500*da58b97aSjoerg       (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
650106f32e7eSjoerg     // FIXME: Make this non-recursion.
6502*da58b97aSjoerg     if (Optional<bool> Implication = isImpliedCondition(
6503*da58b97aSjoerg             ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
650406f32e7eSjoerg       return Implication;
6505*da58b97aSjoerg     if (Optional<bool> Implication = isImpliedCondition(
6506*da58b97aSjoerg             ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
650706f32e7eSjoerg       return Implication;
650806f32e7eSjoerg     return None;
650906f32e7eSjoerg   }
651006f32e7eSjoerg   return None;
651106f32e7eSjoerg }
651206f32e7eSjoerg 
6513*da58b97aSjoerg Optional<bool>
isImpliedCondition(const Value * LHS,CmpInst::Predicate RHSPred,const Value * RHSOp0,const Value * RHSOp1,const DataLayout & DL,bool LHSIsTrue,unsigned Depth)6514*da58b97aSjoerg llvm::isImpliedCondition(const Value *LHS, CmpInst::Predicate RHSPred,
6515*da58b97aSjoerg                          const Value *RHSOp0, const Value *RHSOp1,
6516*da58b97aSjoerg                          const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
651706f32e7eSjoerg   // Bail out when we hit the limit.
6518*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
651906f32e7eSjoerg     return None;
652006f32e7eSjoerg 
652106f32e7eSjoerg   // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
652206f32e7eSjoerg   // example.
6523*da58b97aSjoerg   if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
652406f32e7eSjoerg     return None;
652506f32e7eSjoerg 
652606f32e7eSjoerg   Type *OpTy = LHS->getType();
652706f32e7eSjoerg   assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
652806f32e7eSjoerg 
652906f32e7eSjoerg   // FIXME: Extending the code below to handle vectors.
653006f32e7eSjoerg   if (OpTy->isVectorTy())
653106f32e7eSjoerg     return None;
653206f32e7eSjoerg 
653306f32e7eSjoerg   assert(OpTy->isIntegerTy(1) && "implied by above");
653406f32e7eSjoerg 
653506f32e7eSjoerg   // Both LHS and RHS are icmps.
653606f32e7eSjoerg   const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
6537*da58b97aSjoerg   if (LHSCmp)
6538*da58b97aSjoerg     return isImpliedCondICmps(LHSCmp, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
6539*da58b97aSjoerg                               Depth);
6540*da58b97aSjoerg 
6541*da58b97aSjoerg   /// The LHS should be an 'or', 'and', or a 'select' instruction.  We expect
6542*da58b97aSjoerg   /// the RHS to be an icmp.
6543*da58b97aSjoerg   /// FIXME: Add support for and/or/select on the RHS.
6544*da58b97aSjoerg   if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
6545*da58b97aSjoerg     if ((LHSI->getOpcode() == Instruction::And ||
6546*da58b97aSjoerg          LHSI->getOpcode() == Instruction::Or ||
6547*da58b97aSjoerg          LHSI->getOpcode() == Instruction::Select))
6548*da58b97aSjoerg       return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
6549*da58b97aSjoerg                                 Depth);
6550*da58b97aSjoerg   }
6551*da58b97aSjoerg   return None;
6552*da58b97aSjoerg }
6553*da58b97aSjoerg 
isImpliedCondition(const Value * LHS,const Value * RHS,const DataLayout & DL,bool LHSIsTrue,unsigned Depth)6554*da58b97aSjoerg Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
6555*da58b97aSjoerg                                         const DataLayout &DL, bool LHSIsTrue,
6556*da58b97aSjoerg                                         unsigned Depth) {
6557*da58b97aSjoerg   // LHS ==> RHS by definition
6558*da58b97aSjoerg   if (LHS == RHS)
6559*da58b97aSjoerg     return LHSIsTrue;
6560*da58b97aSjoerg 
656106f32e7eSjoerg   const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
6562*da58b97aSjoerg   if (RHSCmp)
6563*da58b97aSjoerg     return isImpliedCondition(LHS, RHSCmp->getPredicate(),
6564*da58b97aSjoerg                               RHSCmp->getOperand(0), RHSCmp->getOperand(1), DL,
6565*da58b97aSjoerg                               LHSIsTrue, Depth);
656606f32e7eSjoerg   return None;
656706f32e7eSjoerg }
656806f32e7eSjoerg 
6569*da58b97aSjoerg // Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
6570*da58b97aSjoerg // condition dominating ContextI or nullptr, if no condition is found.
6571*da58b97aSjoerg static std::pair<Value *, bool>
getDomPredecessorCondition(const Instruction * ContextI)6572*da58b97aSjoerg getDomPredecessorCondition(const Instruction *ContextI) {
657306f32e7eSjoerg   if (!ContextI || !ContextI->getParent())
6574*da58b97aSjoerg     return {nullptr, false};
657506f32e7eSjoerg 
657606f32e7eSjoerg   // TODO: This is a poor/cheap way to determine dominance. Should we use a
657706f32e7eSjoerg   // dominator tree (eg, from a SimplifyQuery) instead?
657806f32e7eSjoerg   const BasicBlock *ContextBB = ContextI->getParent();
657906f32e7eSjoerg   const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
658006f32e7eSjoerg   if (!PredBB)
6581*da58b97aSjoerg     return {nullptr, false};
658206f32e7eSjoerg 
658306f32e7eSjoerg   // We need a conditional branch in the predecessor.
658406f32e7eSjoerg   Value *PredCond;
658506f32e7eSjoerg   BasicBlock *TrueBB, *FalseBB;
658606f32e7eSjoerg   if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
6587*da58b97aSjoerg     return {nullptr, false};
658806f32e7eSjoerg 
658906f32e7eSjoerg   // The branch should get simplified. Don't bother simplifying this condition.
659006f32e7eSjoerg   if (TrueBB == FalseBB)
6591*da58b97aSjoerg     return {nullptr, false};
659206f32e7eSjoerg 
659306f32e7eSjoerg   assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
659406f32e7eSjoerg          "Predecessor block does not point to successor?");
659506f32e7eSjoerg 
659606f32e7eSjoerg   // Is this condition implied by the predecessor condition?
6597*da58b97aSjoerg   return {PredCond, TrueBB == ContextBB};
6598*da58b97aSjoerg }
6599*da58b97aSjoerg 
isImpliedByDomCondition(const Value * Cond,const Instruction * ContextI,const DataLayout & DL)6600*da58b97aSjoerg Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
6601*da58b97aSjoerg                                              const Instruction *ContextI,
6602*da58b97aSjoerg                                              const DataLayout &DL) {
6603*da58b97aSjoerg   assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
6604*da58b97aSjoerg   auto PredCond = getDomPredecessorCondition(ContextI);
6605*da58b97aSjoerg   if (PredCond.first)
6606*da58b97aSjoerg     return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
6607*da58b97aSjoerg   return None;
6608*da58b97aSjoerg }
6609*da58b97aSjoerg 
isImpliedByDomCondition(CmpInst::Predicate Pred,const Value * LHS,const Value * RHS,const Instruction * ContextI,const DataLayout & DL)6610*da58b97aSjoerg Optional<bool> llvm::isImpliedByDomCondition(CmpInst::Predicate Pred,
6611*da58b97aSjoerg                                              const Value *LHS, const Value *RHS,
6612*da58b97aSjoerg                                              const Instruction *ContextI,
6613*da58b97aSjoerg                                              const DataLayout &DL) {
6614*da58b97aSjoerg   auto PredCond = getDomPredecessorCondition(ContextI);
6615*da58b97aSjoerg   if (PredCond.first)
6616*da58b97aSjoerg     return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
6617*da58b97aSjoerg                               PredCond.second);
6618*da58b97aSjoerg   return None;
661906f32e7eSjoerg }
662006f32e7eSjoerg 
setLimitsForBinOp(const BinaryOperator & BO,APInt & Lower,APInt & Upper,const InstrInfoQuery & IIQ)662106f32e7eSjoerg static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
662206f32e7eSjoerg                               APInt &Upper, const InstrInfoQuery &IIQ) {
662306f32e7eSjoerg   unsigned Width = Lower.getBitWidth();
662406f32e7eSjoerg   const APInt *C;
662506f32e7eSjoerg   switch (BO.getOpcode()) {
662606f32e7eSjoerg   case Instruction::Add:
662706f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
662806f32e7eSjoerg       // FIXME: If we have both nuw and nsw, we should reduce the range further.
662906f32e7eSjoerg       if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
663006f32e7eSjoerg         // 'add nuw x, C' produces [C, UINT_MAX].
663106f32e7eSjoerg         Lower = *C;
663206f32e7eSjoerg       } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
663306f32e7eSjoerg         if (C->isNegative()) {
663406f32e7eSjoerg           // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
663506f32e7eSjoerg           Lower = APInt::getSignedMinValue(Width);
663606f32e7eSjoerg           Upper = APInt::getSignedMaxValue(Width) + *C + 1;
663706f32e7eSjoerg         } else {
663806f32e7eSjoerg           // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
663906f32e7eSjoerg           Lower = APInt::getSignedMinValue(Width) + *C;
664006f32e7eSjoerg           Upper = APInt::getSignedMaxValue(Width) + 1;
664106f32e7eSjoerg         }
664206f32e7eSjoerg       }
664306f32e7eSjoerg     }
664406f32e7eSjoerg     break;
664506f32e7eSjoerg 
664606f32e7eSjoerg   case Instruction::And:
664706f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C)))
664806f32e7eSjoerg       // 'and x, C' produces [0, C].
664906f32e7eSjoerg       Upper = *C + 1;
665006f32e7eSjoerg     break;
665106f32e7eSjoerg 
665206f32e7eSjoerg   case Instruction::Or:
665306f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C)))
665406f32e7eSjoerg       // 'or x, C' produces [C, UINT_MAX].
665506f32e7eSjoerg       Lower = *C;
665606f32e7eSjoerg     break;
665706f32e7eSjoerg 
665806f32e7eSjoerg   case Instruction::AShr:
665906f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
666006f32e7eSjoerg       // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
666106f32e7eSjoerg       Lower = APInt::getSignedMinValue(Width).ashr(*C);
666206f32e7eSjoerg       Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
666306f32e7eSjoerg     } else if (match(BO.getOperand(0), m_APInt(C))) {
666406f32e7eSjoerg       unsigned ShiftAmount = Width - 1;
666506f32e7eSjoerg       if (!C->isNullValue() && IIQ.isExact(&BO))
666606f32e7eSjoerg         ShiftAmount = C->countTrailingZeros();
666706f32e7eSjoerg       if (C->isNegative()) {
666806f32e7eSjoerg         // 'ashr C, x' produces [C, C >> (Width-1)]
666906f32e7eSjoerg         Lower = *C;
667006f32e7eSjoerg         Upper = C->ashr(ShiftAmount) + 1;
667106f32e7eSjoerg       } else {
667206f32e7eSjoerg         // 'ashr C, x' produces [C >> (Width-1), C]
667306f32e7eSjoerg         Lower = C->ashr(ShiftAmount);
667406f32e7eSjoerg         Upper = *C + 1;
667506f32e7eSjoerg       }
667606f32e7eSjoerg     }
667706f32e7eSjoerg     break;
667806f32e7eSjoerg 
667906f32e7eSjoerg   case Instruction::LShr:
668006f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
668106f32e7eSjoerg       // 'lshr x, C' produces [0, UINT_MAX >> C].
668206f32e7eSjoerg       Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
668306f32e7eSjoerg     } else if (match(BO.getOperand(0), m_APInt(C))) {
668406f32e7eSjoerg       // 'lshr C, x' produces [C >> (Width-1), C].
668506f32e7eSjoerg       unsigned ShiftAmount = Width - 1;
668606f32e7eSjoerg       if (!C->isNullValue() && IIQ.isExact(&BO))
668706f32e7eSjoerg         ShiftAmount = C->countTrailingZeros();
668806f32e7eSjoerg       Lower = C->lshr(ShiftAmount);
668906f32e7eSjoerg       Upper = *C + 1;
669006f32e7eSjoerg     }
669106f32e7eSjoerg     break;
669206f32e7eSjoerg 
669306f32e7eSjoerg   case Instruction::Shl:
669406f32e7eSjoerg     if (match(BO.getOperand(0), m_APInt(C))) {
669506f32e7eSjoerg       if (IIQ.hasNoUnsignedWrap(&BO)) {
669606f32e7eSjoerg         // 'shl nuw C, x' produces [C, C << CLZ(C)]
669706f32e7eSjoerg         Lower = *C;
669806f32e7eSjoerg         Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
669906f32e7eSjoerg       } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
670006f32e7eSjoerg         if (C->isNegative()) {
670106f32e7eSjoerg           // 'shl nsw C, x' produces [C << CLO(C)-1, C]
670206f32e7eSjoerg           unsigned ShiftAmount = C->countLeadingOnes() - 1;
670306f32e7eSjoerg           Lower = C->shl(ShiftAmount);
670406f32e7eSjoerg           Upper = *C + 1;
670506f32e7eSjoerg         } else {
670606f32e7eSjoerg           // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
670706f32e7eSjoerg           unsigned ShiftAmount = C->countLeadingZeros() - 1;
670806f32e7eSjoerg           Lower = *C;
670906f32e7eSjoerg           Upper = C->shl(ShiftAmount) + 1;
671006f32e7eSjoerg         }
671106f32e7eSjoerg       }
671206f32e7eSjoerg     }
671306f32e7eSjoerg     break;
671406f32e7eSjoerg 
671506f32e7eSjoerg   case Instruction::SDiv:
671606f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C))) {
671706f32e7eSjoerg       APInt IntMin = APInt::getSignedMinValue(Width);
671806f32e7eSjoerg       APInt IntMax = APInt::getSignedMaxValue(Width);
671906f32e7eSjoerg       if (C->isAllOnesValue()) {
672006f32e7eSjoerg         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
672106f32e7eSjoerg         //    where C != -1 and C != 0 and C != 1
672206f32e7eSjoerg         Lower = IntMin + 1;
672306f32e7eSjoerg         Upper = IntMax + 1;
672406f32e7eSjoerg       } else if (C->countLeadingZeros() < Width - 1) {
672506f32e7eSjoerg         // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
672606f32e7eSjoerg         //    where C != -1 and C != 0 and C != 1
672706f32e7eSjoerg         Lower = IntMin.sdiv(*C);
672806f32e7eSjoerg         Upper = IntMax.sdiv(*C);
672906f32e7eSjoerg         if (Lower.sgt(Upper))
673006f32e7eSjoerg           std::swap(Lower, Upper);
673106f32e7eSjoerg         Upper = Upper + 1;
673206f32e7eSjoerg         assert(Upper != Lower && "Upper part of range has wrapped!");
673306f32e7eSjoerg       }
673406f32e7eSjoerg     } else if (match(BO.getOperand(0), m_APInt(C))) {
673506f32e7eSjoerg       if (C->isMinSignedValue()) {
673606f32e7eSjoerg         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
673706f32e7eSjoerg         Lower = *C;
673806f32e7eSjoerg         Upper = Lower.lshr(1) + 1;
673906f32e7eSjoerg       } else {
674006f32e7eSjoerg         // 'sdiv C, x' produces [-|C|, |C|].
674106f32e7eSjoerg         Upper = C->abs() + 1;
674206f32e7eSjoerg         Lower = (-Upper) + 1;
674306f32e7eSjoerg       }
674406f32e7eSjoerg     }
674506f32e7eSjoerg     break;
674606f32e7eSjoerg 
674706f32e7eSjoerg   case Instruction::UDiv:
674806f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
674906f32e7eSjoerg       // 'udiv x, C' produces [0, UINT_MAX / C].
675006f32e7eSjoerg       Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
675106f32e7eSjoerg     } else if (match(BO.getOperand(0), m_APInt(C))) {
675206f32e7eSjoerg       // 'udiv C, x' produces [0, C].
675306f32e7eSjoerg       Upper = *C + 1;
675406f32e7eSjoerg     }
675506f32e7eSjoerg     break;
675606f32e7eSjoerg 
675706f32e7eSjoerg   case Instruction::SRem:
675806f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C))) {
675906f32e7eSjoerg       // 'srem x, C' produces (-|C|, |C|).
676006f32e7eSjoerg       Upper = C->abs();
676106f32e7eSjoerg       Lower = (-Upper) + 1;
676206f32e7eSjoerg     }
676306f32e7eSjoerg     break;
676406f32e7eSjoerg 
676506f32e7eSjoerg   case Instruction::URem:
676606f32e7eSjoerg     if (match(BO.getOperand(1), m_APInt(C)))
676706f32e7eSjoerg       // 'urem x, C' produces [0, C).
676806f32e7eSjoerg       Upper = *C;
676906f32e7eSjoerg     break;
677006f32e7eSjoerg 
677106f32e7eSjoerg   default:
677206f32e7eSjoerg     break;
677306f32e7eSjoerg   }
677406f32e7eSjoerg }
677506f32e7eSjoerg 
setLimitsForIntrinsic(const IntrinsicInst & II,APInt & Lower,APInt & Upper)677606f32e7eSjoerg static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
677706f32e7eSjoerg                                   APInt &Upper) {
677806f32e7eSjoerg   unsigned Width = Lower.getBitWidth();
677906f32e7eSjoerg   const APInt *C;
678006f32e7eSjoerg   switch (II.getIntrinsicID()) {
6781*da58b97aSjoerg   case Intrinsic::ctpop:
6782*da58b97aSjoerg   case Intrinsic::ctlz:
6783*da58b97aSjoerg   case Intrinsic::cttz:
6784*da58b97aSjoerg     // Maximum of set/clear bits is the bit width.
6785*da58b97aSjoerg     assert(Lower == 0 && "Expected lower bound to be zero");
6786*da58b97aSjoerg     Upper = Width + 1;
6787*da58b97aSjoerg     break;
678806f32e7eSjoerg   case Intrinsic::uadd_sat:
678906f32e7eSjoerg     // uadd.sat(x, C) produces [C, UINT_MAX].
679006f32e7eSjoerg     if (match(II.getOperand(0), m_APInt(C)) ||
679106f32e7eSjoerg         match(II.getOperand(1), m_APInt(C)))
679206f32e7eSjoerg       Lower = *C;
679306f32e7eSjoerg     break;
679406f32e7eSjoerg   case Intrinsic::sadd_sat:
679506f32e7eSjoerg     if (match(II.getOperand(0), m_APInt(C)) ||
679606f32e7eSjoerg         match(II.getOperand(1), m_APInt(C))) {
679706f32e7eSjoerg       if (C->isNegative()) {
679806f32e7eSjoerg         // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
679906f32e7eSjoerg         Lower = APInt::getSignedMinValue(Width);
680006f32e7eSjoerg         Upper = APInt::getSignedMaxValue(Width) + *C + 1;
680106f32e7eSjoerg       } else {
680206f32e7eSjoerg         // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
680306f32e7eSjoerg         Lower = APInt::getSignedMinValue(Width) + *C;
680406f32e7eSjoerg         Upper = APInt::getSignedMaxValue(Width) + 1;
680506f32e7eSjoerg       }
680606f32e7eSjoerg     }
680706f32e7eSjoerg     break;
680806f32e7eSjoerg   case Intrinsic::usub_sat:
680906f32e7eSjoerg     // usub.sat(C, x) produces [0, C].
681006f32e7eSjoerg     if (match(II.getOperand(0), m_APInt(C)))
681106f32e7eSjoerg       Upper = *C + 1;
681206f32e7eSjoerg     // usub.sat(x, C) produces [0, UINT_MAX - C].
681306f32e7eSjoerg     else if (match(II.getOperand(1), m_APInt(C)))
681406f32e7eSjoerg       Upper = APInt::getMaxValue(Width) - *C + 1;
681506f32e7eSjoerg     break;
681606f32e7eSjoerg   case Intrinsic::ssub_sat:
681706f32e7eSjoerg     if (match(II.getOperand(0), m_APInt(C))) {
681806f32e7eSjoerg       if (C->isNegative()) {
681906f32e7eSjoerg         // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
682006f32e7eSjoerg         Lower = APInt::getSignedMinValue(Width);
682106f32e7eSjoerg         Upper = *C - APInt::getSignedMinValue(Width) + 1;
682206f32e7eSjoerg       } else {
682306f32e7eSjoerg         // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
682406f32e7eSjoerg         Lower = *C - APInt::getSignedMaxValue(Width);
682506f32e7eSjoerg         Upper = APInt::getSignedMaxValue(Width) + 1;
682606f32e7eSjoerg       }
682706f32e7eSjoerg     } else if (match(II.getOperand(1), m_APInt(C))) {
682806f32e7eSjoerg       if (C->isNegative()) {
682906f32e7eSjoerg         // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
683006f32e7eSjoerg         Lower = APInt::getSignedMinValue(Width) - *C;
683106f32e7eSjoerg         Upper = APInt::getSignedMaxValue(Width) + 1;
683206f32e7eSjoerg       } else {
683306f32e7eSjoerg         // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
683406f32e7eSjoerg         Lower = APInt::getSignedMinValue(Width);
683506f32e7eSjoerg         Upper = APInt::getSignedMaxValue(Width) - *C + 1;
683606f32e7eSjoerg       }
683706f32e7eSjoerg     }
683806f32e7eSjoerg     break;
6839*da58b97aSjoerg   case Intrinsic::umin:
6840*da58b97aSjoerg   case Intrinsic::umax:
6841*da58b97aSjoerg   case Intrinsic::smin:
6842*da58b97aSjoerg   case Intrinsic::smax:
6843*da58b97aSjoerg     if (!match(II.getOperand(0), m_APInt(C)) &&
6844*da58b97aSjoerg         !match(II.getOperand(1), m_APInt(C)))
6845*da58b97aSjoerg       break;
6846*da58b97aSjoerg 
6847*da58b97aSjoerg     switch (II.getIntrinsicID()) {
6848*da58b97aSjoerg     case Intrinsic::umin:
6849*da58b97aSjoerg       Upper = *C + 1;
6850*da58b97aSjoerg       break;
6851*da58b97aSjoerg     case Intrinsic::umax:
6852*da58b97aSjoerg       Lower = *C;
6853*da58b97aSjoerg       break;
6854*da58b97aSjoerg     case Intrinsic::smin:
6855*da58b97aSjoerg       Lower = APInt::getSignedMinValue(Width);
6856*da58b97aSjoerg       Upper = *C + 1;
6857*da58b97aSjoerg       break;
6858*da58b97aSjoerg     case Intrinsic::smax:
6859*da58b97aSjoerg       Lower = *C;
6860*da58b97aSjoerg       Upper = APInt::getSignedMaxValue(Width) + 1;
6861*da58b97aSjoerg       break;
6862*da58b97aSjoerg     default:
6863*da58b97aSjoerg       llvm_unreachable("Must be min/max intrinsic");
6864*da58b97aSjoerg     }
6865*da58b97aSjoerg     break;
6866*da58b97aSjoerg   case Intrinsic::abs:
6867*da58b97aSjoerg     // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
6868*da58b97aSjoerg     // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
6869*da58b97aSjoerg     if (match(II.getOperand(1), m_One()))
6870*da58b97aSjoerg       Upper = APInt::getSignedMaxValue(Width) + 1;
6871*da58b97aSjoerg     else
6872*da58b97aSjoerg       Upper = APInt::getSignedMinValue(Width) + 1;
6873*da58b97aSjoerg     break;
687406f32e7eSjoerg   default:
687506f32e7eSjoerg     break;
687606f32e7eSjoerg   }
687706f32e7eSjoerg }
687806f32e7eSjoerg 
setLimitsForSelectPattern(const SelectInst & SI,APInt & Lower,APInt & Upper,const InstrInfoQuery & IIQ)687906f32e7eSjoerg static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
688006f32e7eSjoerg                                       APInt &Upper, const InstrInfoQuery &IIQ) {
688106f32e7eSjoerg   const Value *LHS = nullptr, *RHS = nullptr;
688206f32e7eSjoerg   SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
688306f32e7eSjoerg   if (R.Flavor == SPF_UNKNOWN)
688406f32e7eSjoerg     return;
688506f32e7eSjoerg 
688606f32e7eSjoerg   unsigned BitWidth = SI.getType()->getScalarSizeInBits();
688706f32e7eSjoerg 
688806f32e7eSjoerg   if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
688906f32e7eSjoerg     // If the negation part of the abs (in RHS) has the NSW flag,
689006f32e7eSjoerg     // then the result of abs(X) is [0..SIGNED_MAX],
689106f32e7eSjoerg     // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
689206f32e7eSjoerg     Lower = APInt::getNullValue(BitWidth);
689306f32e7eSjoerg     if (match(RHS, m_Neg(m_Specific(LHS))) &&
689406f32e7eSjoerg         IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
689506f32e7eSjoerg       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
689606f32e7eSjoerg     else
689706f32e7eSjoerg       Upper = APInt::getSignedMinValue(BitWidth) + 1;
689806f32e7eSjoerg     return;
689906f32e7eSjoerg   }
690006f32e7eSjoerg 
690106f32e7eSjoerg   if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
690206f32e7eSjoerg     // The result of -abs(X) is <= 0.
690306f32e7eSjoerg     Lower = APInt::getSignedMinValue(BitWidth);
690406f32e7eSjoerg     Upper = APInt(BitWidth, 1);
690506f32e7eSjoerg     return;
690606f32e7eSjoerg   }
690706f32e7eSjoerg 
690806f32e7eSjoerg   const APInt *C;
690906f32e7eSjoerg   if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
691006f32e7eSjoerg     return;
691106f32e7eSjoerg 
691206f32e7eSjoerg   switch (R.Flavor) {
691306f32e7eSjoerg     case SPF_UMIN:
691406f32e7eSjoerg       Upper = *C + 1;
691506f32e7eSjoerg       break;
691606f32e7eSjoerg     case SPF_UMAX:
691706f32e7eSjoerg       Lower = *C;
691806f32e7eSjoerg       break;
691906f32e7eSjoerg     case SPF_SMIN:
692006f32e7eSjoerg       Lower = APInt::getSignedMinValue(BitWidth);
692106f32e7eSjoerg       Upper = *C + 1;
692206f32e7eSjoerg       break;
692306f32e7eSjoerg     case SPF_SMAX:
692406f32e7eSjoerg       Lower = *C;
692506f32e7eSjoerg       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
692606f32e7eSjoerg       break;
692706f32e7eSjoerg     default:
692806f32e7eSjoerg       break;
692906f32e7eSjoerg   }
693006f32e7eSjoerg }
693106f32e7eSjoerg 
computeConstantRange(const Value * V,bool UseInstrInfo,AssumptionCache * AC,const Instruction * CtxI,unsigned Depth)6932*da58b97aSjoerg ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo,
6933*da58b97aSjoerg                                          AssumptionCache *AC,
6934*da58b97aSjoerg                                          const Instruction *CtxI,
6935*da58b97aSjoerg                                          unsigned Depth) {
693606f32e7eSjoerg   assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
693706f32e7eSjoerg 
6938*da58b97aSjoerg   if (Depth == MaxAnalysisRecursionDepth)
6939*da58b97aSjoerg     return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
6940*da58b97aSjoerg 
694106f32e7eSjoerg   const APInt *C;
694206f32e7eSjoerg   if (match(V, m_APInt(C)))
694306f32e7eSjoerg     return ConstantRange(*C);
694406f32e7eSjoerg 
694506f32e7eSjoerg   InstrInfoQuery IIQ(UseInstrInfo);
694606f32e7eSjoerg   unsigned BitWidth = V->getType()->getScalarSizeInBits();
694706f32e7eSjoerg   APInt Lower = APInt(BitWidth, 0);
694806f32e7eSjoerg   APInt Upper = APInt(BitWidth, 0);
694906f32e7eSjoerg   if (auto *BO = dyn_cast<BinaryOperator>(V))
695006f32e7eSjoerg     setLimitsForBinOp(*BO, Lower, Upper, IIQ);
695106f32e7eSjoerg   else if (auto *II = dyn_cast<IntrinsicInst>(V))
695206f32e7eSjoerg     setLimitsForIntrinsic(*II, Lower, Upper);
695306f32e7eSjoerg   else if (auto *SI = dyn_cast<SelectInst>(V))
695406f32e7eSjoerg     setLimitsForSelectPattern(*SI, Lower, Upper, IIQ);
695506f32e7eSjoerg 
695606f32e7eSjoerg   ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper);
695706f32e7eSjoerg 
695806f32e7eSjoerg   if (auto *I = dyn_cast<Instruction>(V))
695906f32e7eSjoerg     if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
696006f32e7eSjoerg       CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
696106f32e7eSjoerg 
6962*da58b97aSjoerg   if (CtxI && AC) {
6963*da58b97aSjoerg     // Try to restrict the range based on information from assumptions.
6964*da58b97aSjoerg     for (auto &AssumeVH : AC->assumptionsFor(V)) {
6965*da58b97aSjoerg       if (!AssumeVH)
6966*da58b97aSjoerg         continue;
6967*da58b97aSjoerg       CallInst *I = cast<CallInst>(AssumeVH);
6968*da58b97aSjoerg       assert(I->getParent()->getParent() == CtxI->getParent()->getParent() &&
6969*da58b97aSjoerg              "Got assumption for the wrong function!");
6970*da58b97aSjoerg       assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
6971*da58b97aSjoerg              "must be an assume intrinsic");
6972*da58b97aSjoerg 
6973*da58b97aSjoerg       if (!isValidAssumeForContext(I, CtxI, nullptr))
6974*da58b97aSjoerg         continue;
6975*da58b97aSjoerg       Value *Arg = I->getArgOperand(0);
6976*da58b97aSjoerg       ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
6977*da58b97aSjoerg       // Currently we just use information from comparisons.
6978*da58b97aSjoerg       if (!Cmp || Cmp->getOperand(0) != V)
6979*da58b97aSjoerg         continue;
6980*da58b97aSjoerg       ConstantRange RHS = computeConstantRange(Cmp->getOperand(1), UseInstrInfo,
6981*da58b97aSjoerg                                                AC, I, Depth + 1);
6982*da58b97aSjoerg       CR = CR.intersectWith(
6983*da58b97aSjoerg           ConstantRange::makeSatisfyingICmpRegion(Cmp->getPredicate(), RHS));
6984*da58b97aSjoerg     }
6985*da58b97aSjoerg   }
6986*da58b97aSjoerg 
698706f32e7eSjoerg   return CR;
698806f32e7eSjoerg }
698906f32e7eSjoerg 
699006f32e7eSjoerg static Optional<int64_t>
getOffsetFromIndex(const GEPOperator * GEP,unsigned Idx,const DataLayout & DL)699106f32e7eSjoerg getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) {
699206f32e7eSjoerg   // Skip over the first indices.
699306f32e7eSjoerg   gep_type_iterator GTI = gep_type_begin(GEP);
699406f32e7eSjoerg   for (unsigned i = 1; i != Idx; ++i, ++GTI)
699506f32e7eSjoerg     /*skip along*/;
699606f32e7eSjoerg 
699706f32e7eSjoerg   // Compute the offset implied by the rest of the indices.
699806f32e7eSjoerg   int64_t Offset = 0;
699906f32e7eSjoerg   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
700006f32e7eSjoerg     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
700106f32e7eSjoerg     if (!OpC)
700206f32e7eSjoerg       return None;
700306f32e7eSjoerg     if (OpC->isZero())
700406f32e7eSjoerg       continue; // No offset.
700506f32e7eSjoerg 
700606f32e7eSjoerg     // Handle struct indices, which add their field offset to the pointer.
700706f32e7eSjoerg     if (StructType *STy = GTI.getStructTypeOrNull()) {
700806f32e7eSjoerg       Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
700906f32e7eSjoerg       continue;
701006f32e7eSjoerg     }
701106f32e7eSjoerg 
7012*da58b97aSjoerg     // Otherwise, we have a sequential type like an array or fixed-length
7013*da58b97aSjoerg     // vector. Multiply the index by the ElementSize.
7014*da58b97aSjoerg     TypeSize Size = DL.getTypeAllocSize(GTI.getIndexedType());
7015*da58b97aSjoerg     if (Size.isScalable())
7016*da58b97aSjoerg       return None;
7017*da58b97aSjoerg     Offset += Size.getFixedSize() * OpC->getSExtValue();
701806f32e7eSjoerg   }
701906f32e7eSjoerg 
702006f32e7eSjoerg   return Offset;
702106f32e7eSjoerg }
702206f32e7eSjoerg 
isPointerOffset(const Value * Ptr1,const Value * Ptr2,const DataLayout & DL)702306f32e7eSjoerg Optional<int64_t> llvm::isPointerOffset(const Value *Ptr1, const Value *Ptr2,
702406f32e7eSjoerg                                         const DataLayout &DL) {
702506f32e7eSjoerg   Ptr1 = Ptr1->stripPointerCasts();
702606f32e7eSjoerg   Ptr2 = Ptr2->stripPointerCasts();
702706f32e7eSjoerg 
702806f32e7eSjoerg   // Handle the trivial case first.
702906f32e7eSjoerg   if (Ptr1 == Ptr2) {
703006f32e7eSjoerg     return 0;
703106f32e7eSjoerg   }
703206f32e7eSjoerg 
703306f32e7eSjoerg   const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
703406f32e7eSjoerg   const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
703506f32e7eSjoerg 
703606f32e7eSjoerg   // If one pointer is a GEP see if the GEP is a constant offset from the base,
703706f32e7eSjoerg   // as in "P" and "gep P, 1".
703806f32e7eSjoerg   // Also do this iteratively to handle the the following case:
703906f32e7eSjoerg   //   Ptr_t1 = GEP Ptr1, c1
704006f32e7eSjoerg   //   Ptr_t2 = GEP Ptr_t1, c2
704106f32e7eSjoerg   //   Ptr2 = GEP Ptr_t2, c3
704206f32e7eSjoerg   // where we will return c1+c2+c3.
704306f32e7eSjoerg   // TODO: Handle the case when both Ptr1 and Ptr2 are GEPs of some common base
704406f32e7eSjoerg   // -- replace getOffsetFromBase with getOffsetAndBase, check that the bases
704506f32e7eSjoerg   // are the same, and return the difference between offsets.
704606f32e7eSjoerg   auto getOffsetFromBase = [&DL](const GEPOperator *GEP,
704706f32e7eSjoerg                                  const Value *Ptr) -> Optional<int64_t> {
704806f32e7eSjoerg     const GEPOperator *GEP_T = GEP;
704906f32e7eSjoerg     int64_t OffsetVal = 0;
705006f32e7eSjoerg     bool HasSameBase = false;
705106f32e7eSjoerg     while (GEP_T) {
705206f32e7eSjoerg       auto Offset = getOffsetFromIndex(GEP_T, 1, DL);
705306f32e7eSjoerg       if (!Offset)
705406f32e7eSjoerg         return None;
705506f32e7eSjoerg       OffsetVal += *Offset;
705606f32e7eSjoerg       auto Op0 = GEP_T->getOperand(0)->stripPointerCasts();
705706f32e7eSjoerg       if (Op0 == Ptr) {
705806f32e7eSjoerg         HasSameBase = true;
705906f32e7eSjoerg         break;
706006f32e7eSjoerg       }
706106f32e7eSjoerg       GEP_T = dyn_cast<GEPOperator>(Op0);
706206f32e7eSjoerg     }
706306f32e7eSjoerg     if (!HasSameBase)
706406f32e7eSjoerg       return None;
706506f32e7eSjoerg     return OffsetVal;
706606f32e7eSjoerg   };
706706f32e7eSjoerg 
706806f32e7eSjoerg   if (GEP1) {
706906f32e7eSjoerg     auto Offset = getOffsetFromBase(GEP1, Ptr2);
707006f32e7eSjoerg     if (Offset)
707106f32e7eSjoerg       return -*Offset;
707206f32e7eSjoerg   }
707306f32e7eSjoerg   if (GEP2) {
707406f32e7eSjoerg     auto Offset = getOffsetFromBase(GEP2, Ptr1);
707506f32e7eSjoerg     if (Offset)
707606f32e7eSjoerg       return Offset;
707706f32e7eSjoerg   }
707806f32e7eSjoerg 
707906f32e7eSjoerg   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
708006f32e7eSjoerg   // base.  After that base, they may have some number of common (and
708106f32e7eSjoerg   // potentially variable) indices.  After that they handle some constant
708206f32e7eSjoerg   // offset, which determines their offset from each other.  At this point, we
708306f32e7eSjoerg   // handle no other case.
708406f32e7eSjoerg   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
708506f32e7eSjoerg     return None;
708606f32e7eSjoerg 
708706f32e7eSjoerg   // Skip any common indices and track the GEP types.
708806f32e7eSjoerg   unsigned Idx = 1;
708906f32e7eSjoerg   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
709006f32e7eSjoerg     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
709106f32e7eSjoerg       break;
709206f32e7eSjoerg 
709306f32e7eSjoerg   auto Offset1 = getOffsetFromIndex(GEP1, Idx, DL);
709406f32e7eSjoerg   auto Offset2 = getOffsetFromIndex(GEP2, Idx, DL);
709506f32e7eSjoerg   if (!Offset1 || !Offset2)
709606f32e7eSjoerg     return None;
709706f32e7eSjoerg   return *Offset2 - *Offset1;
709806f32e7eSjoerg }
7099