xref: /aosp_15_r20/external/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- InstCombineCompares.cpp --------------------------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements the visitICmp and visitFCmp functions.
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
13*9880d681SAndroid Build Coastguard Worker 
14*9880d681SAndroid Build Coastguard Worker #include "InstCombineInternal.h"
15*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/APSInt.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/VectorUtils.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ConstantRange.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GetElementPtrTypeIterator.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
29*9880d681SAndroid Build Coastguard Worker 
30*9880d681SAndroid Build Coastguard Worker using namespace llvm;
31*9880d681SAndroid Build Coastguard Worker using namespace PatternMatch;
32*9880d681SAndroid Build Coastguard Worker 
33*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "instcombine"
34*9880d681SAndroid Build Coastguard Worker 
35*9880d681SAndroid Build Coastguard Worker // How many times is a select replaced by one of its operands?
36*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSel, "Number of select opts");
37*9880d681SAndroid Build Coastguard Worker 
38*9880d681SAndroid Build Coastguard Worker // Initialization Routines
39*9880d681SAndroid Build Coastguard Worker 
getOne(Constant * C)40*9880d681SAndroid Build Coastguard Worker static ConstantInt *getOne(Constant *C) {
41*9880d681SAndroid Build Coastguard Worker   return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
42*9880d681SAndroid Build Coastguard Worker }
43*9880d681SAndroid Build Coastguard Worker 
ExtractElement(Constant * V,Constant * Idx)44*9880d681SAndroid Build Coastguard Worker static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
45*9880d681SAndroid Build Coastguard Worker   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
46*9880d681SAndroid Build Coastguard Worker }
47*9880d681SAndroid Build Coastguard Worker 
HasAddOverflow(ConstantInt * Result,ConstantInt * In1,ConstantInt * In2,bool IsSigned)48*9880d681SAndroid Build Coastguard Worker static bool HasAddOverflow(ConstantInt *Result,
49*9880d681SAndroid Build Coastguard Worker                            ConstantInt *In1, ConstantInt *In2,
50*9880d681SAndroid Build Coastguard Worker                            bool IsSigned) {
51*9880d681SAndroid Build Coastguard Worker   if (!IsSigned)
52*9880d681SAndroid Build Coastguard Worker     return Result->getValue().ult(In1->getValue());
53*9880d681SAndroid Build Coastguard Worker 
54*9880d681SAndroid Build Coastguard Worker   if (In2->isNegative())
55*9880d681SAndroid Build Coastguard Worker     return Result->getValue().sgt(In1->getValue());
56*9880d681SAndroid Build Coastguard Worker   return Result->getValue().slt(In1->getValue());
57*9880d681SAndroid Build Coastguard Worker }
58*9880d681SAndroid Build Coastguard Worker 
59*9880d681SAndroid Build Coastguard Worker /// Compute Result = In1+In2, returning true if the result overflowed for this
60*9880d681SAndroid Build Coastguard Worker /// type.
AddWithOverflow(Constant * & Result,Constant * In1,Constant * In2,bool IsSigned=false)61*9880d681SAndroid Build Coastguard Worker static bool AddWithOverflow(Constant *&Result, Constant *In1,
62*9880d681SAndroid Build Coastguard Worker                             Constant *In2, bool IsSigned = false) {
63*9880d681SAndroid Build Coastguard Worker   Result = ConstantExpr::getAdd(In1, In2);
64*9880d681SAndroid Build Coastguard Worker 
65*9880d681SAndroid Build Coastguard Worker   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
66*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
67*9880d681SAndroid Build Coastguard Worker       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
68*9880d681SAndroid Build Coastguard Worker       if (HasAddOverflow(ExtractElement(Result, Idx),
69*9880d681SAndroid Build Coastguard Worker                          ExtractElement(In1, Idx),
70*9880d681SAndroid Build Coastguard Worker                          ExtractElement(In2, Idx),
71*9880d681SAndroid Build Coastguard Worker                          IsSigned))
72*9880d681SAndroid Build Coastguard Worker         return true;
73*9880d681SAndroid Build Coastguard Worker     }
74*9880d681SAndroid Build Coastguard Worker     return false;
75*9880d681SAndroid Build Coastguard Worker   }
76*9880d681SAndroid Build Coastguard Worker 
77*9880d681SAndroid Build Coastguard Worker   return HasAddOverflow(cast<ConstantInt>(Result),
78*9880d681SAndroid Build Coastguard Worker                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
79*9880d681SAndroid Build Coastguard Worker                         IsSigned);
80*9880d681SAndroid Build Coastguard Worker }
81*9880d681SAndroid Build Coastguard Worker 
HasSubOverflow(ConstantInt * Result,ConstantInt * In1,ConstantInt * In2,bool IsSigned)82*9880d681SAndroid Build Coastguard Worker static bool HasSubOverflow(ConstantInt *Result,
83*9880d681SAndroid Build Coastguard Worker                            ConstantInt *In1, ConstantInt *In2,
84*9880d681SAndroid Build Coastguard Worker                            bool IsSigned) {
85*9880d681SAndroid Build Coastguard Worker   if (!IsSigned)
86*9880d681SAndroid Build Coastguard Worker     return Result->getValue().ugt(In1->getValue());
87*9880d681SAndroid Build Coastguard Worker 
88*9880d681SAndroid Build Coastguard Worker   if (In2->isNegative())
89*9880d681SAndroid Build Coastguard Worker     return Result->getValue().slt(In1->getValue());
90*9880d681SAndroid Build Coastguard Worker 
91*9880d681SAndroid Build Coastguard Worker   return Result->getValue().sgt(In1->getValue());
92*9880d681SAndroid Build Coastguard Worker }
93*9880d681SAndroid Build Coastguard Worker 
94*9880d681SAndroid Build Coastguard Worker /// Compute Result = In1-In2, returning true if the result overflowed for this
95*9880d681SAndroid Build Coastguard Worker /// type.
SubWithOverflow(Constant * & Result,Constant * In1,Constant * In2,bool IsSigned=false)96*9880d681SAndroid Build Coastguard Worker static bool SubWithOverflow(Constant *&Result, Constant *In1,
97*9880d681SAndroid Build Coastguard Worker                             Constant *In2, bool IsSigned = false) {
98*9880d681SAndroid Build Coastguard Worker   Result = ConstantExpr::getSub(In1, In2);
99*9880d681SAndroid Build Coastguard Worker 
100*9880d681SAndroid Build Coastguard Worker   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
101*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
102*9880d681SAndroid Build Coastguard Worker       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
103*9880d681SAndroid Build Coastguard Worker       if (HasSubOverflow(ExtractElement(Result, Idx),
104*9880d681SAndroid Build Coastguard Worker                          ExtractElement(In1, Idx),
105*9880d681SAndroid Build Coastguard Worker                          ExtractElement(In2, Idx),
106*9880d681SAndroid Build Coastguard Worker                          IsSigned))
107*9880d681SAndroid Build Coastguard Worker         return true;
108*9880d681SAndroid Build Coastguard Worker     }
109*9880d681SAndroid Build Coastguard Worker     return false;
110*9880d681SAndroid Build Coastguard Worker   }
111*9880d681SAndroid Build Coastguard Worker 
112*9880d681SAndroid Build Coastguard Worker   return HasSubOverflow(cast<ConstantInt>(Result),
113*9880d681SAndroid Build Coastguard Worker                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
114*9880d681SAndroid Build Coastguard Worker                         IsSigned);
115*9880d681SAndroid Build Coastguard Worker }
116*9880d681SAndroid Build Coastguard Worker 
117*9880d681SAndroid Build Coastguard Worker /// Given an icmp instruction, return true if any use of this comparison is a
118*9880d681SAndroid Build Coastguard Worker /// branch on sign bit comparison.
isBranchOnSignBitCheck(ICmpInst & I,bool isSignBit)119*9880d681SAndroid Build Coastguard Worker static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) {
120*9880d681SAndroid Build Coastguard Worker   for (auto *U : I.users())
121*9880d681SAndroid Build Coastguard Worker     if (isa<BranchInst>(U))
122*9880d681SAndroid Build Coastguard Worker       return isSignBit;
123*9880d681SAndroid Build Coastguard Worker   return false;
124*9880d681SAndroid Build Coastguard Worker }
125*9880d681SAndroid Build Coastguard Worker 
126*9880d681SAndroid Build Coastguard Worker /// Given an exploded icmp instruction, return true if the comparison only
127*9880d681SAndroid Build Coastguard Worker /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
128*9880d681SAndroid Build Coastguard Worker /// result of the comparison is true when the input value is signed.
isSignBitCheck(ICmpInst::Predicate Pred,ConstantInt * RHS,bool & TrueIfSigned)129*9880d681SAndroid Build Coastguard Worker static bool isSignBitCheck(ICmpInst::Predicate Pred, ConstantInt *RHS,
130*9880d681SAndroid Build Coastguard Worker                            bool &TrueIfSigned) {
131*9880d681SAndroid Build Coastguard Worker   switch (Pred) {
132*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
133*9880d681SAndroid Build Coastguard Worker     TrueIfSigned = true;
134*9880d681SAndroid Build Coastguard Worker     return RHS->isZero();
135*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
136*9880d681SAndroid Build Coastguard Worker     TrueIfSigned = true;
137*9880d681SAndroid Build Coastguard Worker     return RHS->isAllOnesValue();
138*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
139*9880d681SAndroid Build Coastguard Worker     TrueIfSigned = false;
140*9880d681SAndroid Build Coastguard Worker     return RHS->isAllOnesValue();
141*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGT:
142*9880d681SAndroid Build Coastguard Worker     // True if LHS u> RHS and RHS == high-bit-mask - 1
143*9880d681SAndroid Build Coastguard Worker     TrueIfSigned = true;
144*9880d681SAndroid Build Coastguard Worker     return RHS->isMaxValue(true);
145*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGE:
146*9880d681SAndroid Build Coastguard Worker     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
147*9880d681SAndroid Build Coastguard Worker     TrueIfSigned = true;
148*9880d681SAndroid Build Coastguard Worker     return RHS->getValue().isSignBit();
149*9880d681SAndroid Build Coastguard Worker   default:
150*9880d681SAndroid Build Coastguard Worker     return false;
151*9880d681SAndroid Build Coastguard Worker   }
152*9880d681SAndroid Build Coastguard Worker }
153*9880d681SAndroid Build Coastguard Worker 
154*9880d681SAndroid Build Coastguard Worker /// Returns true if the exploded icmp can be expressed as a signed comparison
155*9880d681SAndroid Build Coastguard Worker /// to zero and updates the predicate accordingly.
156*9880d681SAndroid Build Coastguard Worker /// The signedness of the comparison is preserved.
isSignTest(ICmpInst::Predicate & Pred,const ConstantInt * RHS)157*9880d681SAndroid Build Coastguard Worker static bool isSignTest(ICmpInst::Predicate &Pred, const ConstantInt *RHS) {
158*9880d681SAndroid Build Coastguard Worker   if (!ICmpInst::isSigned(Pred))
159*9880d681SAndroid Build Coastguard Worker     return false;
160*9880d681SAndroid Build Coastguard Worker 
161*9880d681SAndroid Build Coastguard Worker   if (RHS->isZero())
162*9880d681SAndroid Build Coastguard Worker     return ICmpInst::isRelational(Pred);
163*9880d681SAndroid Build Coastguard Worker 
164*9880d681SAndroid Build Coastguard Worker   if (RHS->isOne()) {
165*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_SLT) {
166*9880d681SAndroid Build Coastguard Worker       Pred = ICmpInst::ICMP_SLE;
167*9880d681SAndroid Build Coastguard Worker       return true;
168*9880d681SAndroid Build Coastguard Worker     }
169*9880d681SAndroid Build Coastguard Worker   } else if (RHS->isAllOnesValue()) {
170*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_SGT) {
171*9880d681SAndroid Build Coastguard Worker       Pred = ICmpInst::ICMP_SGE;
172*9880d681SAndroid Build Coastguard Worker       return true;
173*9880d681SAndroid Build Coastguard Worker     }
174*9880d681SAndroid Build Coastguard Worker   }
175*9880d681SAndroid Build Coastguard Worker 
176*9880d681SAndroid Build Coastguard Worker   return false;
177*9880d681SAndroid Build Coastguard Worker }
178*9880d681SAndroid Build Coastguard Worker 
179*9880d681SAndroid Build Coastguard Worker /// Return true if the constant is of the form 1+0+. This is the same as
180*9880d681SAndroid Build Coastguard Worker /// lowones(~X).
isHighOnes(const ConstantInt * CI)181*9880d681SAndroid Build Coastguard Worker static bool isHighOnes(const ConstantInt *CI) {
182*9880d681SAndroid Build Coastguard Worker   return (~CI->getValue() + 1).isPowerOf2();
183*9880d681SAndroid Build Coastguard Worker }
184*9880d681SAndroid Build Coastguard Worker 
185*9880d681SAndroid Build Coastguard Worker /// Given a signed integer type and a set of known zero and one bits, compute
186*9880d681SAndroid Build Coastguard Worker /// the maximum and minimum values that could have the specified known zero and
187*9880d681SAndroid Build Coastguard Worker /// known one bits, returning them in Min/Max.
ComputeSignedMinMaxValuesFromKnownBits(const APInt & KnownZero,const APInt & KnownOne,APInt & Min,APInt & Max)188*9880d681SAndroid Build Coastguard Worker static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
189*9880d681SAndroid Build Coastguard Worker                                                    const APInt &KnownOne,
190*9880d681SAndroid Build Coastguard Worker                                                    APInt &Min, APInt &Max) {
191*9880d681SAndroid Build Coastguard Worker   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
192*9880d681SAndroid Build Coastguard Worker          KnownZero.getBitWidth() == Min.getBitWidth() &&
193*9880d681SAndroid Build Coastguard Worker          KnownZero.getBitWidth() == Max.getBitWidth() &&
194*9880d681SAndroid Build Coastguard Worker          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
195*9880d681SAndroid Build Coastguard Worker   APInt UnknownBits = ~(KnownZero|KnownOne);
196*9880d681SAndroid Build Coastguard Worker 
197*9880d681SAndroid Build Coastguard Worker   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
198*9880d681SAndroid Build Coastguard Worker   // bit if it is unknown.
199*9880d681SAndroid Build Coastguard Worker   Min = KnownOne;
200*9880d681SAndroid Build Coastguard Worker   Max = KnownOne|UnknownBits;
201*9880d681SAndroid Build Coastguard Worker 
202*9880d681SAndroid Build Coastguard Worker   if (UnknownBits.isNegative()) { // Sign bit is unknown
203*9880d681SAndroid Build Coastguard Worker     Min.setBit(Min.getBitWidth()-1);
204*9880d681SAndroid Build Coastguard Worker     Max.clearBit(Max.getBitWidth()-1);
205*9880d681SAndroid Build Coastguard Worker   }
206*9880d681SAndroid Build Coastguard Worker }
207*9880d681SAndroid Build Coastguard Worker 
208*9880d681SAndroid Build Coastguard Worker /// Given an unsigned integer type and a set of known zero and one bits, compute
209*9880d681SAndroid Build Coastguard Worker /// the maximum and minimum values that could have the specified known zero and
210*9880d681SAndroid Build Coastguard Worker /// known one bits, returning them in Min/Max.
ComputeUnsignedMinMaxValuesFromKnownBits(const APInt & KnownZero,const APInt & KnownOne,APInt & Min,APInt & Max)211*9880d681SAndroid Build Coastguard Worker static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
212*9880d681SAndroid Build Coastguard Worker                                                      const APInt &KnownOne,
213*9880d681SAndroid Build Coastguard Worker                                                      APInt &Min, APInt &Max) {
214*9880d681SAndroid Build Coastguard Worker   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
215*9880d681SAndroid Build Coastguard Worker          KnownZero.getBitWidth() == Min.getBitWidth() &&
216*9880d681SAndroid Build Coastguard Worker          KnownZero.getBitWidth() == Max.getBitWidth() &&
217*9880d681SAndroid Build Coastguard Worker          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
218*9880d681SAndroid Build Coastguard Worker   APInt UnknownBits = ~(KnownZero|KnownOne);
219*9880d681SAndroid Build Coastguard Worker 
220*9880d681SAndroid Build Coastguard Worker   // The minimum value is when the unknown bits are all zeros.
221*9880d681SAndroid Build Coastguard Worker   Min = KnownOne;
222*9880d681SAndroid Build Coastguard Worker   // The maximum value is when the unknown bits are all ones.
223*9880d681SAndroid Build Coastguard Worker   Max = KnownOne|UnknownBits;
224*9880d681SAndroid Build Coastguard Worker }
225*9880d681SAndroid Build Coastguard Worker 
226*9880d681SAndroid Build Coastguard Worker /// This is called when we see this pattern:
227*9880d681SAndroid Build Coastguard Worker ///   cmp pred (load (gep GV, ...)), cmpcst
228*9880d681SAndroid Build Coastguard Worker /// where GV is a global variable with a constant initializer. Try to simplify
229*9880d681SAndroid Build Coastguard Worker /// this into some simple computation that does not need the load. For example
230*9880d681SAndroid Build Coastguard Worker /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
231*9880d681SAndroid Build Coastguard Worker ///
232*9880d681SAndroid Build Coastguard Worker /// If AndCst is non-null, then the loaded value is masked with that constant
233*9880d681SAndroid Build Coastguard Worker /// before doing the comparison. This handles cases like "A[i]&4 == 0".
234*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::
FoldCmpLoadFromIndexedGlobal(GetElementPtrInst * GEP,GlobalVariable * GV,CmpInst & ICI,ConstantInt * AndCst)235*9880d681SAndroid Build Coastguard Worker FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
236*9880d681SAndroid Build Coastguard Worker                              CmpInst &ICI, ConstantInt *AndCst) {
237*9880d681SAndroid Build Coastguard Worker   Constant *Init = GV->getInitializer();
238*9880d681SAndroid Build Coastguard Worker   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
239*9880d681SAndroid Build Coastguard Worker     return nullptr;
240*9880d681SAndroid Build Coastguard Worker 
241*9880d681SAndroid Build Coastguard Worker   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
242*9880d681SAndroid Build Coastguard Worker   if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
243*9880d681SAndroid Build Coastguard Worker 
244*9880d681SAndroid Build Coastguard Worker   // There are many forms of this optimization we can handle, for now, just do
245*9880d681SAndroid Build Coastguard Worker   // the simple index into a single-dimensional array.
246*9880d681SAndroid Build Coastguard Worker   //
247*9880d681SAndroid Build Coastguard Worker   // Require: GEP GV, 0, i {{, constant indices}}
248*9880d681SAndroid Build Coastguard Worker   if (GEP->getNumOperands() < 3 ||
249*9880d681SAndroid Build Coastguard Worker       !isa<ConstantInt>(GEP->getOperand(1)) ||
250*9880d681SAndroid Build Coastguard Worker       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
251*9880d681SAndroid Build Coastguard Worker       isa<Constant>(GEP->getOperand(2)))
252*9880d681SAndroid Build Coastguard Worker     return nullptr;
253*9880d681SAndroid Build Coastguard Worker 
254*9880d681SAndroid Build Coastguard Worker   // Check that indices after the variable are constants and in-range for the
255*9880d681SAndroid Build Coastguard Worker   // type they index.  Collect the indices.  This is typically for arrays of
256*9880d681SAndroid Build Coastguard Worker   // structs.
257*9880d681SAndroid Build Coastguard Worker   SmallVector<unsigned, 4> LaterIndices;
258*9880d681SAndroid Build Coastguard Worker 
259*9880d681SAndroid Build Coastguard Worker   Type *EltTy = Init->getType()->getArrayElementType();
260*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
261*9880d681SAndroid Build Coastguard Worker     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
262*9880d681SAndroid Build Coastguard Worker     if (!Idx) return nullptr;  // Variable index.
263*9880d681SAndroid Build Coastguard Worker 
264*9880d681SAndroid Build Coastguard Worker     uint64_t IdxVal = Idx->getZExtValue();
265*9880d681SAndroid Build Coastguard Worker     if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
266*9880d681SAndroid Build Coastguard Worker 
267*9880d681SAndroid Build Coastguard Worker     if (StructType *STy = dyn_cast<StructType>(EltTy))
268*9880d681SAndroid Build Coastguard Worker       EltTy = STy->getElementType(IdxVal);
269*9880d681SAndroid Build Coastguard Worker     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
270*9880d681SAndroid Build Coastguard Worker       if (IdxVal >= ATy->getNumElements()) return nullptr;
271*9880d681SAndroid Build Coastguard Worker       EltTy = ATy->getElementType();
272*9880d681SAndroid Build Coastguard Worker     } else {
273*9880d681SAndroid Build Coastguard Worker       return nullptr; // Unknown type.
274*9880d681SAndroid Build Coastguard Worker     }
275*9880d681SAndroid Build Coastguard Worker 
276*9880d681SAndroid Build Coastguard Worker     LaterIndices.push_back(IdxVal);
277*9880d681SAndroid Build Coastguard Worker   }
278*9880d681SAndroid Build Coastguard Worker 
279*9880d681SAndroid Build Coastguard Worker   enum { Overdefined = -3, Undefined = -2 };
280*9880d681SAndroid Build Coastguard Worker 
281*9880d681SAndroid Build Coastguard Worker   // Variables for our state machines.
282*9880d681SAndroid Build Coastguard Worker 
283*9880d681SAndroid Build Coastguard Worker   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
284*9880d681SAndroid Build Coastguard Worker   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
285*9880d681SAndroid Build Coastguard Worker   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
286*9880d681SAndroid Build Coastguard Worker   // undefined, otherwise set to the first true element.  SecondTrueElement is
287*9880d681SAndroid Build Coastguard Worker   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
288*9880d681SAndroid Build Coastguard Worker   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
289*9880d681SAndroid Build Coastguard Worker 
290*9880d681SAndroid Build Coastguard Worker   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
291*9880d681SAndroid Build Coastguard Worker   // form "i != 47 & i != 87".  Same state transitions as for true elements.
292*9880d681SAndroid Build Coastguard Worker   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
293*9880d681SAndroid Build Coastguard Worker 
294*9880d681SAndroid Build Coastguard Worker   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
295*9880d681SAndroid Build Coastguard Worker   /// define a state machine that triggers for ranges of values that the index
296*9880d681SAndroid Build Coastguard Worker   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
297*9880d681SAndroid Build Coastguard Worker   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
298*9880d681SAndroid Build Coastguard Worker   /// index in the range (inclusive).  We use -2 for undefined here because we
299*9880d681SAndroid Build Coastguard Worker   /// use relative comparisons and don't want 0-1 to match -1.
300*9880d681SAndroid Build Coastguard Worker   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
301*9880d681SAndroid Build Coastguard Worker 
302*9880d681SAndroid Build Coastguard Worker   // MagicBitvector - This is a magic bitvector where we set a bit if the
303*9880d681SAndroid Build Coastguard Worker   // comparison is true for element 'i'.  If there are 64 elements or less in
304*9880d681SAndroid Build Coastguard Worker   // the array, this will fully represent all the comparison results.
305*9880d681SAndroid Build Coastguard Worker   uint64_t MagicBitvector = 0;
306*9880d681SAndroid Build Coastguard Worker 
307*9880d681SAndroid Build Coastguard Worker   // Scan the array and see if one of our patterns matches.
308*9880d681SAndroid Build Coastguard Worker   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
309*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
310*9880d681SAndroid Build Coastguard Worker     Constant *Elt = Init->getAggregateElement(i);
311*9880d681SAndroid Build Coastguard Worker     if (!Elt) return nullptr;
312*9880d681SAndroid Build Coastguard Worker 
313*9880d681SAndroid Build Coastguard Worker     // If this is indexing an array of structures, get the structure element.
314*9880d681SAndroid Build Coastguard Worker     if (!LaterIndices.empty())
315*9880d681SAndroid Build Coastguard Worker       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
316*9880d681SAndroid Build Coastguard Worker 
317*9880d681SAndroid Build Coastguard Worker     // If the element is masked, handle it.
318*9880d681SAndroid Build Coastguard Worker     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
319*9880d681SAndroid Build Coastguard Worker 
320*9880d681SAndroid Build Coastguard Worker     // Find out if the comparison would be true or false for the i'th element.
321*9880d681SAndroid Build Coastguard Worker     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
322*9880d681SAndroid Build Coastguard Worker                                                   CompareRHS, DL, TLI);
323*9880d681SAndroid Build Coastguard Worker     // If the result is undef for this element, ignore it.
324*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(C)) {
325*9880d681SAndroid Build Coastguard Worker       // Extend range state machines to cover this element in case there is an
326*9880d681SAndroid Build Coastguard Worker       // undef in the middle of the range.
327*9880d681SAndroid Build Coastguard Worker       if (TrueRangeEnd == (int)i-1)
328*9880d681SAndroid Build Coastguard Worker         TrueRangeEnd = i;
329*9880d681SAndroid Build Coastguard Worker       if (FalseRangeEnd == (int)i-1)
330*9880d681SAndroid Build Coastguard Worker         FalseRangeEnd = i;
331*9880d681SAndroid Build Coastguard Worker       continue;
332*9880d681SAndroid Build Coastguard Worker     }
333*9880d681SAndroid Build Coastguard Worker 
334*9880d681SAndroid Build Coastguard Worker     // If we can't compute the result for any of the elements, we have to give
335*9880d681SAndroid Build Coastguard Worker     // up evaluating the entire conditional.
336*9880d681SAndroid Build Coastguard Worker     if (!isa<ConstantInt>(C)) return nullptr;
337*9880d681SAndroid Build Coastguard Worker 
338*9880d681SAndroid Build Coastguard Worker     // Otherwise, we know if the comparison is true or false for this element,
339*9880d681SAndroid Build Coastguard Worker     // update our state machines.
340*9880d681SAndroid Build Coastguard Worker     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
341*9880d681SAndroid Build Coastguard Worker 
342*9880d681SAndroid Build Coastguard Worker     // State machine for single/double/range index comparison.
343*9880d681SAndroid Build Coastguard Worker     if (IsTrueForElt) {
344*9880d681SAndroid Build Coastguard Worker       // Update the TrueElement state machine.
345*9880d681SAndroid Build Coastguard Worker       if (FirstTrueElement == Undefined)
346*9880d681SAndroid Build Coastguard Worker         FirstTrueElement = TrueRangeEnd = i;  // First true element.
347*9880d681SAndroid Build Coastguard Worker       else {
348*9880d681SAndroid Build Coastguard Worker         // Update double-compare state machine.
349*9880d681SAndroid Build Coastguard Worker         if (SecondTrueElement == Undefined)
350*9880d681SAndroid Build Coastguard Worker           SecondTrueElement = i;
351*9880d681SAndroid Build Coastguard Worker         else
352*9880d681SAndroid Build Coastguard Worker           SecondTrueElement = Overdefined;
353*9880d681SAndroid Build Coastguard Worker 
354*9880d681SAndroid Build Coastguard Worker         // Update range state machine.
355*9880d681SAndroid Build Coastguard Worker         if (TrueRangeEnd == (int)i-1)
356*9880d681SAndroid Build Coastguard Worker           TrueRangeEnd = i;
357*9880d681SAndroid Build Coastguard Worker         else
358*9880d681SAndroid Build Coastguard Worker           TrueRangeEnd = Overdefined;
359*9880d681SAndroid Build Coastguard Worker       }
360*9880d681SAndroid Build Coastguard Worker     } else {
361*9880d681SAndroid Build Coastguard Worker       // Update the FalseElement state machine.
362*9880d681SAndroid Build Coastguard Worker       if (FirstFalseElement == Undefined)
363*9880d681SAndroid Build Coastguard Worker         FirstFalseElement = FalseRangeEnd = i; // First false element.
364*9880d681SAndroid Build Coastguard Worker       else {
365*9880d681SAndroid Build Coastguard Worker         // Update double-compare state machine.
366*9880d681SAndroid Build Coastguard Worker         if (SecondFalseElement == Undefined)
367*9880d681SAndroid Build Coastguard Worker           SecondFalseElement = i;
368*9880d681SAndroid Build Coastguard Worker         else
369*9880d681SAndroid Build Coastguard Worker           SecondFalseElement = Overdefined;
370*9880d681SAndroid Build Coastguard Worker 
371*9880d681SAndroid Build Coastguard Worker         // Update range state machine.
372*9880d681SAndroid Build Coastguard Worker         if (FalseRangeEnd == (int)i-1)
373*9880d681SAndroid Build Coastguard Worker           FalseRangeEnd = i;
374*9880d681SAndroid Build Coastguard Worker         else
375*9880d681SAndroid Build Coastguard Worker           FalseRangeEnd = Overdefined;
376*9880d681SAndroid Build Coastguard Worker       }
377*9880d681SAndroid Build Coastguard Worker     }
378*9880d681SAndroid Build Coastguard Worker 
379*9880d681SAndroid Build Coastguard Worker     // If this element is in range, update our magic bitvector.
380*9880d681SAndroid Build Coastguard Worker     if (i < 64 && IsTrueForElt)
381*9880d681SAndroid Build Coastguard Worker       MagicBitvector |= 1ULL << i;
382*9880d681SAndroid Build Coastguard Worker 
383*9880d681SAndroid Build Coastguard Worker     // If all of our states become overdefined, bail out early.  Since the
384*9880d681SAndroid Build Coastguard Worker     // predicate is expensive, only check it every 8 elements.  This is only
385*9880d681SAndroid Build Coastguard Worker     // really useful for really huge arrays.
386*9880d681SAndroid Build Coastguard Worker     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
387*9880d681SAndroid Build Coastguard Worker         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
388*9880d681SAndroid Build Coastguard Worker         FalseRangeEnd == Overdefined)
389*9880d681SAndroid Build Coastguard Worker       return nullptr;
390*9880d681SAndroid Build Coastguard Worker   }
391*9880d681SAndroid Build Coastguard Worker 
392*9880d681SAndroid Build Coastguard Worker   // Now that we've scanned the entire array, emit our new comparison(s).  We
393*9880d681SAndroid Build Coastguard Worker   // order the state machines in complexity of the generated code.
394*9880d681SAndroid Build Coastguard Worker   Value *Idx = GEP->getOperand(2);
395*9880d681SAndroid Build Coastguard Worker 
396*9880d681SAndroid Build Coastguard Worker   // If the index is larger than the pointer size of the target, truncate the
397*9880d681SAndroid Build Coastguard Worker   // index down like the GEP would do implicitly.  We don't have to do this for
398*9880d681SAndroid Build Coastguard Worker   // an inbounds GEP because the index can't be out of range.
399*9880d681SAndroid Build Coastguard Worker   if (!GEP->isInBounds()) {
400*9880d681SAndroid Build Coastguard Worker     Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
401*9880d681SAndroid Build Coastguard Worker     unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
402*9880d681SAndroid Build Coastguard Worker     if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
403*9880d681SAndroid Build Coastguard Worker       Idx = Builder->CreateTrunc(Idx, IntPtrTy);
404*9880d681SAndroid Build Coastguard Worker   }
405*9880d681SAndroid Build Coastguard Worker 
406*9880d681SAndroid Build Coastguard Worker   // If the comparison is only true for one or two elements, emit direct
407*9880d681SAndroid Build Coastguard Worker   // comparisons.
408*9880d681SAndroid Build Coastguard Worker   if (SecondTrueElement != Overdefined) {
409*9880d681SAndroid Build Coastguard Worker     // None true -> false.
410*9880d681SAndroid Build Coastguard Worker     if (FirstTrueElement == Undefined)
411*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getFalse());
412*9880d681SAndroid Build Coastguard Worker 
413*9880d681SAndroid Build Coastguard Worker     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
414*9880d681SAndroid Build Coastguard Worker 
415*9880d681SAndroid Build Coastguard Worker     // True for one element -> 'i == 47'.
416*9880d681SAndroid Build Coastguard Worker     if (SecondTrueElement == Undefined)
417*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
418*9880d681SAndroid Build Coastguard Worker 
419*9880d681SAndroid Build Coastguard Worker     // True for two elements -> 'i == 47 | i == 72'.
420*9880d681SAndroid Build Coastguard Worker     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
421*9880d681SAndroid Build Coastguard Worker     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
422*9880d681SAndroid Build Coastguard Worker     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
423*9880d681SAndroid Build Coastguard Worker     return BinaryOperator::CreateOr(C1, C2);
424*9880d681SAndroid Build Coastguard Worker   }
425*9880d681SAndroid Build Coastguard Worker 
426*9880d681SAndroid Build Coastguard Worker   // If the comparison is only false for one or two elements, emit direct
427*9880d681SAndroid Build Coastguard Worker   // comparisons.
428*9880d681SAndroid Build Coastguard Worker   if (SecondFalseElement != Overdefined) {
429*9880d681SAndroid Build Coastguard Worker     // None false -> true.
430*9880d681SAndroid Build Coastguard Worker     if (FirstFalseElement == Undefined)
431*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getTrue());
432*9880d681SAndroid Build Coastguard Worker 
433*9880d681SAndroid Build Coastguard Worker     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
434*9880d681SAndroid Build Coastguard Worker 
435*9880d681SAndroid Build Coastguard Worker     // False for one element -> 'i != 47'.
436*9880d681SAndroid Build Coastguard Worker     if (SecondFalseElement == Undefined)
437*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
438*9880d681SAndroid Build Coastguard Worker 
439*9880d681SAndroid Build Coastguard Worker     // False for two elements -> 'i != 47 & i != 72'.
440*9880d681SAndroid Build Coastguard Worker     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
441*9880d681SAndroid Build Coastguard Worker     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
442*9880d681SAndroid Build Coastguard Worker     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
443*9880d681SAndroid Build Coastguard Worker     return BinaryOperator::CreateAnd(C1, C2);
444*9880d681SAndroid Build Coastguard Worker   }
445*9880d681SAndroid Build Coastguard Worker 
446*9880d681SAndroid Build Coastguard Worker   // If the comparison can be replaced with a range comparison for the elements
447*9880d681SAndroid Build Coastguard Worker   // where it is true, emit the range check.
448*9880d681SAndroid Build Coastguard Worker   if (TrueRangeEnd != Overdefined) {
449*9880d681SAndroid Build Coastguard Worker     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
450*9880d681SAndroid Build Coastguard Worker 
451*9880d681SAndroid Build Coastguard Worker     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
452*9880d681SAndroid Build Coastguard Worker     if (FirstTrueElement) {
453*9880d681SAndroid Build Coastguard Worker       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
454*9880d681SAndroid Build Coastguard Worker       Idx = Builder->CreateAdd(Idx, Offs);
455*9880d681SAndroid Build Coastguard Worker     }
456*9880d681SAndroid Build Coastguard Worker 
457*9880d681SAndroid Build Coastguard Worker     Value *End = ConstantInt::get(Idx->getType(),
458*9880d681SAndroid Build Coastguard Worker                                   TrueRangeEnd-FirstTrueElement+1);
459*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
460*9880d681SAndroid Build Coastguard Worker   }
461*9880d681SAndroid Build Coastguard Worker 
462*9880d681SAndroid Build Coastguard Worker   // False range check.
463*9880d681SAndroid Build Coastguard Worker   if (FalseRangeEnd != Overdefined) {
464*9880d681SAndroid Build Coastguard Worker     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
465*9880d681SAndroid Build Coastguard Worker     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
466*9880d681SAndroid Build Coastguard Worker     if (FirstFalseElement) {
467*9880d681SAndroid Build Coastguard Worker       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
468*9880d681SAndroid Build Coastguard Worker       Idx = Builder->CreateAdd(Idx, Offs);
469*9880d681SAndroid Build Coastguard Worker     }
470*9880d681SAndroid Build Coastguard Worker 
471*9880d681SAndroid Build Coastguard Worker     Value *End = ConstantInt::get(Idx->getType(),
472*9880d681SAndroid Build Coastguard Worker                                   FalseRangeEnd-FirstFalseElement);
473*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
474*9880d681SAndroid Build Coastguard Worker   }
475*9880d681SAndroid Build Coastguard Worker 
476*9880d681SAndroid Build Coastguard Worker   // If a magic bitvector captures the entire comparison state
477*9880d681SAndroid Build Coastguard Worker   // of this load, replace it with computation that does:
478*9880d681SAndroid Build Coastguard Worker   //   ((magic_cst >> i) & 1) != 0
479*9880d681SAndroid Build Coastguard Worker   {
480*9880d681SAndroid Build Coastguard Worker     Type *Ty = nullptr;
481*9880d681SAndroid Build Coastguard Worker 
482*9880d681SAndroid Build Coastguard Worker     // Look for an appropriate type:
483*9880d681SAndroid Build Coastguard Worker     // - The type of Idx if the magic fits
484*9880d681SAndroid Build Coastguard Worker     // - The smallest fitting legal type if we have a DataLayout
485*9880d681SAndroid Build Coastguard Worker     // - Default to i32
486*9880d681SAndroid Build Coastguard Worker     if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
487*9880d681SAndroid Build Coastguard Worker       Ty = Idx->getType();
488*9880d681SAndroid Build Coastguard Worker     else
489*9880d681SAndroid Build Coastguard Worker       Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
490*9880d681SAndroid Build Coastguard Worker 
491*9880d681SAndroid Build Coastguard Worker     if (Ty) {
492*9880d681SAndroid Build Coastguard Worker       Value *V = Builder->CreateIntCast(Idx, Ty, false);
493*9880d681SAndroid Build Coastguard Worker       V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
494*9880d681SAndroid Build Coastguard Worker       V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
495*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
496*9880d681SAndroid Build Coastguard Worker     }
497*9880d681SAndroid Build Coastguard Worker   }
498*9880d681SAndroid Build Coastguard Worker 
499*9880d681SAndroid Build Coastguard Worker   return nullptr;
500*9880d681SAndroid Build Coastguard Worker }
501*9880d681SAndroid Build Coastguard Worker 
502*9880d681SAndroid Build Coastguard Worker /// Return a value that can be used to compare the *offset* implied by a GEP to
503*9880d681SAndroid Build Coastguard Worker /// zero. For example, if we have &A[i], we want to return 'i' for
504*9880d681SAndroid Build Coastguard Worker /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
505*9880d681SAndroid Build Coastguard Worker /// are involved. The above expression would also be legal to codegen as
506*9880d681SAndroid Build Coastguard Worker /// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
507*9880d681SAndroid Build Coastguard Worker /// This latter form is less amenable to optimization though, and we are allowed
508*9880d681SAndroid Build Coastguard Worker /// to generate the first by knowing that pointer arithmetic doesn't overflow.
509*9880d681SAndroid Build Coastguard Worker ///
510*9880d681SAndroid Build Coastguard Worker /// If we can't emit an optimized form for this expression, this returns null.
511*9880d681SAndroid Build Coastguard Worker ///
EvaluateGEPOffsetExpression(User * GEP,InstCombiner & IC,const DataLayout & DL)512*9880d681SAndroid Build Coastguard Worker static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
513*9880d681SAndroid Build Coastguard Worker                                           const DataLayout &DL) {
514*9880d681SAndroid Build Coastguard Worker   gep_type_iterator GTI = gep_type_begin(GEP);
515*9880d681SAndroid Build Coastguard Worker 
516*9880d681SAndroid Build Coastguard Worker   // Check to see if this gep only has a single variable index.  If so, and if
517*9880d681SAndroid Build Coastguard Worker   // any constant indices are a multiple of its scale, then we can compute this
518*9880d681SAndroid Build Coastguard Worker   // in terms of the scale of the variable index.  For example, if the GEP
519*9880d681SAndroid Build Coastguard Worker   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
520*9880d681SAndroid Build Coastguard Worker   // because the expression will cross zero at the same point.
521*9880d681SAndroid Build Coastguard Worker   unsigned i, e = GEP->getNumOperands();
522*9880d681SAndroid Build Coastguard Worker   int64_t Offset = 0;
523*9880d681SAndroid Build Coastguard Worker   for (i = 1; i != e; ++i, ++GTI) {
524*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
525*9880d681SAndroid Build Coastguard Worker       // Compute the aggregate offset of constant indices.
526*9880d681SAndroid Build Coastguard Worker       if (CI->isZero()) continue;
527*9880d681SAndroid Build Coastguard Worker 
528*9880d681SAndroid Build Coastguard Worker       // Handle a struct index, which adds its field offset to the pointer.
529*9880d681SAndroid Build Coastguard Worker       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
530*9880d681SAndroid Build Coastguard Worker         Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
531*9880d681SAndroid Build Coastguard Worker       } else {
532*9880d681SAndroid Build Coastguard Worker         uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
533*9880d681SAndroid Build Coastguard Worker         Offset += Size*CI->getSExtValue();
534*9880d681SAndroid Build Coastguard Worker       }
535*9880d681SAndroid Build Coastguard Worker     } else {
536*9880d681SAndroid Build Coastguard Worker       // Found our variable index.
537*9880d681SAndroid Build Coastguard Worker       break;
538*9880d681SAndroid Build Coastguard Worker     }
539*9880d681SAndroid Build Coastguard Worker   }
540*9880d681SAndroid Build Coastguard Worker 
541*9880d681SAndroid Build Coastguard Worker   // If there are no variable indices, we must have a constant offset, just
542*9880d681SAndroid Build Coastguard Worker   // evaluate it the general way.
543*9880d681SAndroid Build Coastguard Worker   if (i == e) return nullptr;
544*9880d681SAndroid Build Coastguard Worker 
545*9880d681SAndroid Build Coastguard Worker   Value *VariableIdx = GEP->getOperand(i);
546*9880d681SAndroid Build Coastguard Worker   // Determine the scale factor of the variable element.  For example, this is
547*9880d681SAndroid Build Coastguard Worker   // 4 if the variable index is into an array of i32.
548*9880d681SAndroid Build Coastguard Worker   uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
549*9880d681SAndroid Build Coastguard Worker 
550*9880d681SAndroid Build Coastguard Worker   // Verify that there are no other variable indices.  If so, emit the hard way.
551*9880d681SAndroid Build Coastguard Worker   for (++i, ++GTI; i != e; ++i, ++GTI) {
552*9880d681SAndroid Build Coastguard Worker     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
553*9880d681SAndroid Build Coastguard Worker     if (!CI) return nullptr;
554*9880d681SAndroid Build Coastguard Worker 
555*9880d681SAndroid Build Coastguard Worker     // Compute the aggregate offset of constant indices.
556*9880d681SAndroid Build Coastguard Worker     if (CI->isZero()) continue;
557*9880d681SAndroid Build Coastguard Worker 
558*9880d681SAndroid Build Coastguard Worker     // Handle a struct index, which adds its field offset to the pointer.
559*9880d681SAndroid Build Coastguard Worker     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
560*9880d681SAndroid Build Coastguard Worker       Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
561*9880d681SAndroid Build Coastguard Worker     } else {
562*9880d681SAndroid Build Coastguard Worker       uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
563*9880d681SAndroid Build Coastguard Worker       Offset += Size*CI->getSExtValue();
564*9880d681SAndroid Build Coastguard Worker     }
565*9880d681SAndroid Build Coastguard Worker   }
566*9880d681SAndroid Build Coastguard Worker 
567*9880d681SAndroid Build Coastguard Worker   // Okay, we know we have a single variable index, which must be a
568*9880d681SAndroid Build Coastguard Worker   // pointer/array/vector index.  If there is no offset, life is simple, return
569*9880d681SAndroid Build Coastguard Worker   // the index.
570*9880d681SAndroid Build Coastguard Worker   Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
571*9880d681SAndroid Build Coastguard Worker   unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
572*9880d681SAndroid Build Coastguard Worker   if (Offset == 0) {
573*9880d681SAndroid Build Coastguard Worker     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
574*9880d681SAndroid Build Coastguard Worker     // we don't need to bother extending: the extension won't affect where the
575*9880d681SAndroid Build Coastguard Worker     // computation crosses zero.
576*9880d681SAndroid Build Coastguard Worker     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
577*9880d681SAndroid Build Coastguard Worker       VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
578*9880d681SAndroid Build Coastguard Worker     }
579*9880d681SAndroid Build Coastguard Worker     return VariableIdx;
580*9880d681SAndroid Build Coastguard Worker   }
581*9880d681SAndroid Build Coastguard Worker 
582*9880d681SAndroid Build Coastguard Worker   // Otherwise, there is an index.  The computation we will do will be modulo
583*9880d681SAndroid Build Coastguard Worker   // the pointer size, so get it.
584*9880d681SAndroid Build Coastguard Worker   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
585*9880d681SAndroid Build Coastguard Worker 
586*9880d681SAndroid Build Coastguard Worker   Offset &= PtrSizeMask;
587*9880d681SAndroid Build Coastguard Worker   VariableScale &= PtrSizeMask;
588*9880d681SAndroid Build Coastguard Worker 
589*9880d681SAndroid Build Coastguard Worker   // To do this transformation, any constant index must be a multiple of the
590*9880d681SAndroid Build Coastguard Worker   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
591*9880d681SAndroid Build Coastguard Worker   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
592*9880d681SAndroid Build Coastguard Worker   // multiple of the variable scale.
593*9880d681SAndroid Build Coastguard Worker   int64_t NewOffs = Offset / (int64_t)VariableScale;
594*9880d681SAndroid Build Coastguard Worker   if (Offset != NewOffs*(int64_t)VariableScale)
595*9880d681SAndroid Build Coastguard Worker     return nullptr;
596*9880d681SAndroid Build Coastguard Worker 
597*9880d681SAndroid Build Coastguard Worker   // Okay, we can do this evaluation.  Start by converting the index to intptr.
598*9880d681SAndroid Build Coastguard Worker   if (VariableIdx->getType() != IntPtrTy)
599*9880d681SAndroid Build Coastguard Worker     VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
600*9880d681SAndroid Build Coastguard Worker                                             true /*Signed*/);
601*9880d681SAndroid Build Coastguard Worker   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
602*9880d681SAndroid Build Coastguard Worker   return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
603*9880d681SAndroid Build Coastguard Worker }
604*9880d681SAndroid Build Coastguard Worker 
605*9880d681SAndroid Build Coastguard Worker /// Returns true if we can rewrite Start as a GEP with pointer Base
606*9880d681SAndroid Build Coastguard Worker /// and some integer offset. The nodes that need to be re-written
607*9880d681SAndroid Build Coastguard Worker /// for this transformation will be added to Explored.
canRewriteGEPAsOffset(Value * Start,Value * Base,const DataLayout & DL,SetVector<Value * > & Explored)608*9880d681SAndroid Build Coastguard Worker static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
609*9880d681SAndroid Build Coastguard Worker                                   const DataLayout &DL,
610*9880d681SAndroid Build Coastguard Worker                                   SetVector<Value *> &Explored) {
611*9880d681SAndroid Build Coastguard Worker   SmallVector<Value *, 16> WorkList(1, Start);
612*9880d681SAndroid Build Coastguard Worker   Explored.insert(Base);
613*9880d681SAndroid Build Coastguard Worker 
614*9880d681SAndroid Build Coastguard Worker   // The following traversal gives us an order which can be used
615*9880d681SAndroid Build Coastguard Worker   // when doing the final transformation. Since in the final
616*9880d681SAndroid Build Coastguard Worker   // transformation we create the PHI replacement instructions first,
617*9880d681SAndroid Build Coastguard Worker   // we don't have to get them in any particular order.
618*9880d681SAndroid Build Coastguard Worker   //
619*9880d681SAndroid Build Coastguard Worker   // However, for other instructions we will have to traverse the
620*9880d681SAndroid Build Coastguard Worker   // operands of an instruction first, which means that we have to
621*9880d681SAndroid Build Coastguard Worker   // do a post-order traversal.
622*9880d681SAndroid Build Coastguard Worker   while (!WorkList.empty()) {
623*9880d681SAndroid Build Coastguard Worker     SetVector<PHINode *> PHIs;
624*9880d681SAndroid Build Coastguard Worker 
625*9880d681SAndroid Build Coastguard Worker     while (!WorkList.empty()) {
626*9880d681SAndroid Build Coastguard Worker       if (Explored.size() >= 100)
627*9880d681SAndroid Build Coastguard Worker         return false;
628*9880d681SAndroid Build Coastguard Worker 
629*9880d681SAndroid Build Coastguard Worker       Value *V = WorkList.back();
630*9880d681SAndroid Build Coastguard Worker 
631*9880d681SAndroid Build Coastguard Worker       if (Explored.count(V) != 0) {
632*9880d681SAndroid Build Coastguard Worker         WorkList.pop_back();
633*9880d681SAndroid Build Coastguard Worker         continue;
634*9880d681SAndroid Build Coastguard Worker       }
635*9880d681SAndroid Build Coastguard Worker 
636*9880d681SAndroid Build Coastguard Worker       if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
637*9880d681SAndroid Build Coastguard Worker           !isa<GEPOperator>(V) && !isa<PHINode>(V))
638*9880d681SAndroid Build Coastguard Worker         // We've found some value that we can't explore which is different from
639*9880d681SAndroid Build Coastguard Worker         // the base. Therefore we can't do this transformation.
640*9880d681SAndroid Build Coastguard Worker         return false;
641*9880d681SAndroid Build Coastguard Worker 
642*9880d681SAndroid Build Coastguard Worker       if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
643*9880d681SAndroid Build Coastguard Worker         auto *CI = dyn_cast<CastInst>(V);
644*9880d681SAndroid Build Coastguard Worker         if (!CI->isNoopCast(DL))
645*9880d681SAndroid Build Coastguard Worker           return false;
646*9880d681SAndroid Build Coastguard Worker 
647*9880d681SAndroid Build Coastguard Worker         if (Explored.count(CI->getOperand(0)) == 0)
648*9880d681SAndroid Build Coastguard Worker           WorkList.push_back(CI->getOperand(0));
649*9880d681SAndroid Build Coastguard Worker       }
650*9880d681SAndroid Build Coastguard Worker 
651*9880d681SAndroid Build Coastguard Worker       if (auto *GEP = dyn_cast<GEPOperator>(V)) {
652*9880d681SAndroid Build Coastguard Worker         // We're limiting the GEP to having one index. This will preserve
653*9880d681SAndroid Build Coastguard Worker         // the original pointer type. We could handle more cases in the
654*9880d681SAndroid Build Coastguard Worker         // future.
655*9880d681SAndroid Build Coastguard Worker         if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
656*9880d681SAndroid Build Coastguard Worker             GEP->getType() != Start->getType())
657*9880d681SAndroid Build Coastguard Worker           return false;
658*9880d681SAndroid Build Coastguard Worker 
659*9880d681SAndroid Build Coastguard Worker         if (Explored.count(GEP->getOperand(0)) == 0)
660*9880d681SAndroid Build Coastguard Worker           WorkList.push_back(GEP->getOperand(0));
661*9880d681SAndroid Build Coastguard Worker       }
662*9880d681SAndroid Build Coastguard Worker 
663*9880d681SAndroid Build Coastguard Worker       if (WorkList.back() == V) {
664*9880d681SAndroid Build Coastguard Worker         WorkList.pop_back();
665*9880d681SAndroid Build Coastguard Worker         // We've finished visiting this node, mark it as such.
666*9880d681SAndroid Build Coastguard Worker         Explored.insert(V);
667*9880d681SAndroid Build Coastguard Worker       }
668*9880d681SAndroid Build Coastguard Worker 
669*9880d681SAndroid Build Coastguard Worker       if (auto *PN = dyn_cast<PHINode>(V)) {
670*9880d681SAndroid Build Coastguard Worker         // We cannot transform PHIs on unsplittable basic blocks.
671*9880d681SAndroid Build Coastguard Worker         if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
672*9880d681SAndroid Build Coastguard Worker           return false;
673*9880d681SAndroid Build Coastguard Worker         Explored.insert(PN);
674*9880d681SAndroid Build Coastguard Worker         PHIs.insert(PN);
675*9880d681SAndroid Build Coastguard Worker       }
676*9880d681SAndroid Build Coastguard Worker     }
677*9880d681SAndroid Build Coastguard Worker 
678*9880d681SAndroid Build Coastguard Worker     // Explore the PHI nodes further.
679*9880d681SAndroid Build Coastguard Worker     for (auto *PN : PHIs)
680*9880d681SAndroid Build Coastguard Worker       for (Value *Op : PN->incoming_values())
681*9880d681SAndroid Build Coastguard Worker         if (Explored.count(Op) == 0)
682*9880d681SAndroid Build Coastguard Worker           WorkList.push_back(Op);
683*9880d681SAndroid Build Coastguard Worker   }
684*9880d681SAndroid Build Coastguard Worker 
685*9880d681SAndroid Build Coastguard Worker   // Make sure that we can do this. Since we can't insert GEPs in a basic
686*9880d681SAndroid Build Coastguard Worker   // block before a PHI node, we can't easily do this transformation if
687*9880d681SAndroid Build Coastguard Worker   // we have PHI node users of transformed instructions.
688*9880d681SAndroid Build Coastguard Worker   for (Value *Val : Explored) {
689*9880d681SAndroid Build Coastguard Worker     for (Value *Use : Val->uses()) {
690*9880d681SAndroid Build Coastguard Worker 
691*9880d681SAndroid Build Coastguard Worker       auto *PHI = dyn_cast<PHINode>(Use);
692*9880d681SAndroid Build Coastguard Worker       auto *Inst = dyn_cast<Instruction>(Val);
693*9880d681SAndroid Build Coastguard Worker 
694*9880d681SAndroid Build Coastguard Worker       if (Inst == Base || Inst == PHI || !Inst || !PHI ||
695*9880d681SAndroid Build Coastguard Worker           Explored.count(PHI) == 0)
696*9880d681SAndroid Build Coastguard Worker         continue;
697*9880d681SAndroid Build Coastguard Worker 
698*9880d681SAndroid Build Coastguard Worker       if (PHI->getParent() == Inst->getParent())
699*9880d681SAndroid Build Coastguard Worker         return false;
700*9880d681SAndroid Build Coastguard Worker     }
701*9880d681SAndroid Build Coastguard Worker   }
702*9880d681SAndroid Build Coastguard Worker   return true;
703*9880d681SAndroid Build Coastguard Worker }
704*9880d681SAndroid Build Coastguard Worker 
705*9880d681SAndroid Build Coastguard Worker // Sets the appropriate insert point on Builder where we can add
706*9880d681SAndroid Build Coastguard Worker // a replacement Instruction for V (if that is possible).
setInsertionPoint(IRBuilder<> & Builder,Value * V,bool Before=true)707*9880d681SAndroid Build Coastguard Worker static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
708*9880d681SAndroid Build Coastguard Worker                               bool Before = true) {
709*9880d681SAndroid Build Coastguard Worker   if (auto *PHI = dyn_cast<PHINode>(V)) {
710*9880d681SAndroid Build Coastguard Worker     Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
711*9880d681SAndroid Build Coastguard Worker     return;
712*9880d681SAndroid Build Coastguard Worker   }
713*9880d681SAndroid Build Coastguard Worker   if (auto *I = dyn_cast<Instruction>(V)) {
714*9880d681SAndroid Build Coastguard Worker     if (!Before)
715*9880d681SAndroid Build Coastguard Worker       I = &*std::next(I->getIterator());
716*9880d681SAndroid Build Coastguard Worker     Builder.SetInsertPoint(I);
717*9880d681SAndroid Build Coastguard Worker     return;
718*9880d681SAndroid Build Coastguard Worker   }
719*9880d681SAndroid Build Coastguard Worker   if (auto *A = dyn_cast<Argument>(V)) {
720*9880d681SAndroid Build Coastguard Worker     // Set the insertion point in the entry block.
721*9880d681SAndroid Build Coastguard Worker     BasicBlock &Entry = A->getParent()->getEntryBlock();
722*9880d681SAndroid Build Coastguard Worker     Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
723*9880d681SAndroid Build Coastguard Worker     return;
724*9880d681SAndroid Build Coastguard Worker   }
725*9880d681SAndroid Build Coastguard Worker   // Otherwise, this is a constant and we don't need to set a new
726*9880d681SAndroid Build Coastguard Worker   // insertion point.
727*9880d681SAndroid Build Coastguard Worker   assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
728*9880d681SAndroid Build Coastguard Worker }
729*9880d681SAndroid Build Coastguard Worker 
730*9880d681SAndroid Build Coastguard Worker /// Returns a re-written value of Start as an indexed GEP using Base as a
731*9880d681SAndroid Build Coastguard Worker /// pointer.
rewriteGEPAsOffset(Value * Start,Value * Base,const DataLayout & DL,SetVector<Value * > & Explored)732*9880d681SAndroid Build Coastguard Worker static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
733*9880d681SAndroid Build Coastguard Worker                                  const DataLayout &DL,
734*9880d681SAndroid Build Coastguard Worker                                  SetVector<Value *> &Explored) {
735*9880d681SAndroid Build Coastguard Worker   // Perform all the substitutions. This is a bit tricky because we can
736*9880d681SAndroid Build Coastguard Worker   // have cycles in our use-def chains.
737*9880d681SAndroid Build Coastguard Worker   // 1. Create the PHI nodes without any incoming values.
738*9880d681SAndroid Build Coastguard Worker   // 2. Create all the other values.
739*9880d681SAndroid Build Coastguard Worker   // 3. Add the edges for the PHI nodes.
740*9880d681SAndroid Build Coastguard Worker   // 4. Emit GEPs to get the original pointers.
741*9880d681SAndroid Build Coastguard Worker   // 5. Remove the original instructions.
742*9880d681SAndroid Build Coastguard Worker   Type *IndexType = IntegerType::get(
743*9880d681SAndroid Build Coastguard Worker       Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
744*9880d681SAndroid Build Coastguard Worker 
745*9880d681SAndroid Build Coastguard Worker   DenseMap<Value *, Value *> NewInsts;
746*9880d681SAndroid Build Coastguard Worker   NewInsts[Base] = ConstantInt::getNullValue(IndexType);
747*9880d681SAndroid Build Coastguard Worker 
748*9880d681SAndroid Build Coastguard Worker   // Create the new PHI nodes, without adding any incoming values.
749*9880d681SAndroid Build Coastguard Worker   for (Value *Val : Explored) {
750*9880d681SAndroid Build Coastguard Worker     if (Val == Base)
751*9880d681SAndroid Build Coastguard Worker       continue;
752*9880d681SAndroid Build Coastguard Worker     // Create empty phi nodes. This avoids cyclic dependencies when creating
753*9880d681SAndroid Build Coastguard Worker     // the remaining instructions.
754*9880d681SAndroid Build Coastguard Worker     if (auto *PHI = dyn_cast<PHINode>(Val))
755*9880d681SAndroid Build Coastguard Worker       NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
756*9880d681SAndroid Build Coastguard Worker                                       PHI->getName() + ".idx", PHI);
757*9880d681SAndroid Build Coastguard Worker   }
758*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(Base->getContext());
759*9880d681SAndroid Build Coastguard Worker 
760*9880d681SAndroid Build Coastguard Worker   // Create all the other instructions.
761*9880d681SAndroid Build Coastguard Worker   for (Value *Val : Explored) {
762*9880d681SAndroid Build Coastguard Worker 
763*9880d681SAndroid Build Coastguard Worker     if (NewInsts.find(Val) != NewInsts.end())
764*9880d681SAndroid Build Coastguard Worker       continue;
765*9880d681SAndroid Build Coastguard Worker 
766*9880d681SAndroid Build Coastguard Worker     if (auto *CI = dyn_cast<CastInst>(Val)) {
767*9880d681SAndroid Build Coastguard Worker       NewInsts[CI] = NewInsts[CI->getOperand(0)];
768*9880d681SAndroid Build Coastguard Worker       continue;
769*9880d681SAndroid Build Coastguard Worker     }
770*9880d681SAndroid Build Coastguard Worker     if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
771*9880d681SAndroid Build Coastguard Worker       Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
772*9880d681SAndroid Build Coastguard Worker                                                   : GEP->getOperand(1);
773*9880d681SAndroid Build Coastguard Worker       setInsertionPoint(Builder, GEP);
774*9880d681SAndroid Build Coastguard Worker       // Indices might need to be sign extended. GEPs will magically do
775*9880d681SAndroid Build Coastguard Worker       // this, but we need to do it ourselves here.
776*9880d681SAndroid Build Coastguard Worker       if (Index->getType()->getScalarSizeInBits() !=
777*9880d681SAndroid Build Coastguard Worker           NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
778*9880d681SAndroid Build Coastguard Worker         Index = Builder.CreateSExtOrTrunc(
779*9880d681SAndroid Build Coastguard Worker             Index, NewInsts[GEP->getOperand(0)]->getType(),
780*9880d681SAndroid Build Coastguard Worker             GEP->getOperand(0)->getName() + ".sext");
781*9880d681SAndroid Build Coastguard Worker       }
782*9880d681SAndroid Build Coastguard Worker 
783*9880d681SAndroid Build Coastguard Worker       auto *Op = NewInsts[GEP->getOperand(0)];
784*9880d681SAndroid Build Coastguard Worker       if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
785*9880d681SAndroid Build Coastguard Worker         NewInsts[GEP] = Index;
786*9880d681SAndroid Build Coastguard Worker       else
787*9880d681SAndroid Build Coastguard Worker         NewInsts[GEP] = Builder.CreateNSWAdd(
788*9880d681SAndroid Build Coastguard Worker             Op, Index, GEP->getOperand(0)->getName() + ".add");
789*9880d681SAndroid Build Coastguard Worker       continue;
790*9880d681SAndroid Build Coastguard Worker     }
791*9880d681SAndroid Build Coastguard Worker     if (isa<PHINode>(Val))
792*9880d681SAndroid Build Coastguard Worker       continue;
793*9880d681SAndroid Build Coastguard Worker 
794*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unexpected instruction type");
795*9880d681SAndroid Build Coastguard Worker   }
796*9880d681SAndroid Build Coastguard Worker 
797*9880d681SAndroid Build Coastguard Worker   // Add the incoming values to the PHI nodes.
798*9880d681SAndroid Build Coastguard Worker   for (Value *Val : Explored) {
799*9880d681SAndroid Build Coastguard Worker     if (Val == Base)
800*9880d681SAndroid Build Coastguard Worker       continue;
801*9880d681SAndroid Build Coastguard Worker     // All the instructions have been created, we can now add edges to the
802*9880d681SAndroid Build Coastguard Worker     // phi nodes.
803*9880d681SAndroid Build Coastguard Worker     if (auto *PHI = dyn_cast<PHINode>(Val)) {
804*9880d681SAndroid Build Coastguard Worker       PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
805*9880d681SAndroid Build Coastguard Worker       for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
806*9880d681SAndroid Build Coastguard Worker         Value *NewIncoming = PHI->getIncomingValue(I);
807*9880d681SAndroid Build Coastguard Worker 
808*9880d681SAndroid Build Coastguard Worker         if (NewInsts.find(NewIncoming) != NewInsts.end())
809*9880d681SAndroid Build Coastguard Worker           NewIncoming = NewInsts[NewIncoming];
810*9880d681SAndroid Build Coastguard Worker 
811*9880d681SAndroid Build Coastguard Worker         NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
812*9880d681SAndroid Build Coastguard Worker       }
813*9880d681SAndroid Build Coastguard Worker     }
814*9880d681SAndroid Build Coastguard Worker   }
815*9880d681SAndroid Build Coastguard Worker 
816*9880d681SAndroid Build Coastguard Worker   for (Value *Val : Explored) {
817*9880d681SAndroid Build Coastguard Worker     if (Val == Base)
818*9880d681SAndroid Build Coastguard Worker       continue;
819*9880d681SAndroid Build Coastguard Worker 
820*9880d681SAndroid Build Coastguard Worker     // Depending on the type, for external users we have to emit
821*9880d681SAndroid Build Coastguard Worker     // a GEP or a GEP + ptrtoint.
822*9880d681SAndroid Build Coastguard Worker     setInsertionPoint(Builder, Val, false);
823*9880d681SAndroid Build Coastguard Worker 
824*9880d681SAndroid Build Coastguard Worker     // If required, create an inttoptr instruction for Base.
825*9880d681SAndroid Build Coastguard Worker     Value *NewBase = Base;
826*9880d681SAndroid Build Coastguard Worker     if (!Base->getType()->isPointerTy())
827*9880d681SAndroid Build Coastguard Worker       NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
828*9880d681SAndroid Build Coastguard Worker                                                Start->getName() + "to.ptr");
829*9880d681SAndroid Build Coastguard Worker 
830*9880d681SAndroid Build Coastguard Worker     Value *GEP = Builder.CreateInBoundsGEP(
831*9880d681SAndroid Build Coastguard Worker         Start->getType()->getPointerElementType(), NewBase,
832*9880d681SAndroid Build Coastguard Worker         makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
833*9880d681SAndroid Build Coastguard Worker 
834*9880d681SAndroid Build Coastguard Worker     if (!Val->getType()->isPointerTy()) {
835*9880d681SAndroid Build Coastguard Worker       Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
836*9880d681SAndroid Build Coastguard Worker                                               Val->getName() + ".conv");
837*9880d681SAndroid Build Coastguard Worker       GEP = Cast;
838*9880d681SAndroid Build Coastguard Worker     }
839*9880d681SAndroid Build Coastguard Worker     Val->replaceAllUsesWith(GEP);
840*9880d681SAndroid Build Coastguard Worker   }
841*9880d681SAndroid Build Coastguard Worker 
842*9880d681SAndroid Build Coastguard Worker   return NewInsts[Start];
843*9880d681SAndroid Build Coastguard Worker }
844*9880d681SAndroid Build Coastguard Worker 
845*9880d681SAndroid Build Coastguard Worker /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
846*9880d681SAndroid Build Coastguard Worker /// the input Value as a constant indexed GEP. Returns a pair containing
847*9880d681SAndroid Build Coastguard Worker /// the GEPs Pointer and Index.
848*9880d681SAndroid Build Coastguard Worker static std::pair<Value *, Value *>
getAsConstantIndexedAddress(Value * V,const DataLayout & DL)849*9880d681SAndroid Build Coastguard Worker getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
850*9880d681SAndroid Build Coastguard Worker   Type *IndexType = IntegerType::get(V->getContext(),
851*9880d681SAndroid Build Coastguard Worker                                      DL.getPointerTypeSizeInBits(V->getType()));
852*9880d681SAndroid Build Coastguard Worker 
853*9880d681SAndroid Build Coastguard Worker   Constant *Index = ConstantInt::getNullValue(IndexType);
854*9880d681SAndroid Build Coastguard Worker   while (true) {
855*9880d681SAndroid Build Coastguard Worker     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
856*9880d681SAndroid Build Coastguard Worker       // We accept only inbouds GEPs here to exclude the possibility of
857*9880d681SAndroid Build Coastguard Worker       // overflow.
858*9880d681SAndroid Build Coastguard Worker       if (!GEP->isInBounds())
859*9880d681SAndroid Build Coastguard Worker         break;
860*9880d681SAndroid Build Coastguard Worker       if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
861*9880d681SAndroid Build Coastguard Worker           GEP->getType() == V->getType()) {
862*9880d681SAndroid Build Coastguard Worker         V = GEP->getOperand(0);
863*9880d681SAndroid Build Coastguard Worker         Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
864*9880d681SAndroid Build Coastguard Worker         Index = ConstantExpr::getAdd(
865*9880d681SAndroid Build Coastguard Worker             Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
866*9880d681SAndroid Build Coastguard Worker         continue;
867*9880d681SAndroid Build Coastguard Worker       }
868*9880d681SAndroid Build Coastguard Worker       break;
869*9880d681SAndroid Build Coastguard Worker     }
870*9880d681SAndroid Build Coastguard Worker     if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
871*9880d681SAndroid Build Coastguard Worker       if (!CI->isNoopCast(DL))
872*9880d681SAndroid Build Coastguard Worker         break;
873*9880d681SAndroid Build Coastguard Worker       V = CI->getOperand(0);
874*9880d681SAndroid Build Coastguard Worker       continue;
875*9880d681SAndroid Build Coastguard Worker     }
876*9880d681SAndroid Build Coastguard Worker     if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
877*9880d681SAndroid Build Coastguard Worker       if (!CI->isNoopCast(DL))
878*9880d681SAndroid Build Coastguard Worker         break;
879*9880d681SAndroid Build Coastguard Worker       V = CI->getOperand(0);
880*9880d681SAndroid Build Coastguard Worker       continue;
881*9880d681SAndroid Build Coastguard Worker     }
882*9880d681SAndroid Build Coastguard Worker     break;
883*9880d681SAndroid Build Coastguard Worker   }
884*9880d681SAndroid Build Coastguard Worker   return {V, Index};
885*9880d681SAndroid Build Coastguard Worker }
886*9880d681SAndroid Build Coastguard Worker 
887*9880d681SAndroid Build Coastguard Worker /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
888*9880d681SAndroid Build Coastguard Worker /// We can look through PHIs, GEPs and casts in order to determine a common base
889*9880d681SAndroid Build Coastguard Worker /// between GEPLHS and RHS.
transformToIndexedCompare(GEPOperator * GEPLHS,Value * RHS,ICmpInst::Predicate Cond,const DataLayout & DL)890*9880d681SAndroid Build Coastguard Worker static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
891*9880d681SAndroid Build Coastguard Worker                                               ICmpInst::Predicate Cond,
892*9880d681SAndroid Build Coastguard Worker                                               const DataLayout &DL) {
893*9880d681SAndroid Build Coastguard Worker   if (!GEPLHS->hasAllConstantIndices())
894*9880d681SAndroid Build Coastguard Worker     return nullptr;
895*9880d681SAndroid Build Coastguard Worker 
896*9880d681SAndroid Build Coastguard Worker   Value *PtrBase, *Index;
897*9880d681SAndroid Build Coastguard Worker   std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
898*9880d681SAndroid Build Coastguard Worker 
899*9880d681SAndroid Build Coastguard Worker   // The set of nodes that will take part in this transformation.
900*9880d681SAndroid Build Coastguard Worker   SetVector<Value *> Nodes;
901*9880d681SAndroid Build Coastguard Worker 
902*9880d681SAndroid Build Coastguard Worker   if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
903*9880d681SAndroid Build Coastguard Worker     return nullptr;
904*9880d681SAndroid Build Coastguard Worker 
905*9880d681SAndroid Build Coastguard Worker   // We know we can re-write this as
906*9880d681SAndroid Build Coastguard Worker   //  ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
907*9880d681SAndroid Build Coastguard Worker   // Since we've only looked through inbouds GEPs we know that we
908*9880d681SAndroid Build Coastguard Worker   // can't have overflow on either side. We can therefore re-write
909*9880d681SAndroid Build Coastguard Worker   // this as:
910*9880d681SAndroid Build Coastguard Worker   //   OFFSET1 cmp OFFSET2
911*9880d681SAndroid Build Coastguard Worker   Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
912*9880d681SAndroid Build Coastguard Worker 
913*9880d681SAndroid Build Coastguard Worker   // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
914*9880d681SAndroid Build Coastguard Worker   // GEP having PtrBase as the pointer base, and has returned in NewRHS the
915*9880d681SAndroid Build Coastguard Worker   // offset. Since Index is the offset of LHS to the base pointer, we will now
916*9880d681SAndroid Build Coastguard Worker   // compare the offsets instead of comparing the pointers.
917*9880d681SAndroid Build Coastguard Worker   return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
918*9880d681SAndroid Build Coastguard Worker }
919*9880d681SAndroid Build Coastguard Worker 
920*9880d681SAndroid Build Coastguard Worker /// Fold comparisons between a GEP instruction and something else. At this point
921*9880d681SAndroid Build Coastguard Worker /// we know that the GEP is on the LHS of the comparison.
FoldGEPICmp(GEPOperator * GEPLHS,Value * RHS,ICmpInst::Predicate Cond,Instruction & I)922*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
923*9880d681SAndroid Build Coastguard Worker                                        ICmpInst::Predicate Cond,
924*9880d681SAndroid Build Coastguard Worker                                        Instruction &I) {
925*9880d681SAndroid Build Coastguard Worker   // Don't transform signed compares of GEPs into index compares. Even if the
926*9880d681SAndroid Build Coastguard Worker   // GEP is inbounds, the final add of the base pointer can have signed overflow
927*9880d681SAndroid Build Coastguard Worker   // and would change the result of the icmp.
928*9880d681SAndroid Build Coastguard Worker   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
929*9880d681SAndroid Build Coastguard Worker   // the maximum signed value for the pointer type.
930*9880d681SAndroid Build Coastguard Worker   if (ICmpInst::isSigned(Cond))
931*9880d681SAndroid Build Coastguard Worker     return nullptr;
932*9880d681SAndroid Build Coastguard Worker 
933*9880d681SAndroid Build Coastguard Worker   // Look through bitcasts and addrspacecasts. We do not however want to remove
934*9880d681SAndroid Build Coastguard Worker   // 0 GEPs.
935*9880d681SAndroid Build Coastguard Worker   if (!isa<GetElementPtrInst>(RHS))
936*9880d681SAndroid Build Coastguard Worker     RHS = RHS->stripPointerCasts();
937*9880d681SAndroid Build Coastguard Worker 
938*9880d681SAndroid Build Coastguard Worker   Value *PtrBase = GEPLHS->getOperand(0);
939*9880d681SAndroid Build Coastguard Worker   if (PtrBase == RHS && GEPLHS->isInBounds()) {
940*9880d681SAndroid Build Coastguard Worker     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
941*9880d681SAndroid Build Coastguard Worker     // This transformation (ignoring the base and scales) is valid because we
942*9880d681SAndroid Build Coastguard Worker     // know pointers can't overflow since the gep is inbounds.  See if we can
943*9880d681SAndroid Build Coastguard Worker     // output an optimized form.
944*9880d681SAndroid Build Coastguard Worker     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
945*9880d681SAndroid Build Coastguard Worker 
946*9880d681SAndroid Build Coastguard Worker     // If not, synthesize the offset the hard way.
947*9880d681SAndroid Build Coastguard Worker     if (!Offset)
948*9880d681SAndroid Build Coastguard Worker       Offset = EmitGEPOffset(GEPLHS);
949*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
950*9880d681SAndroid Build Coastguard Worker                         Constant::getNullValue(Offset->getType()));
951*9880d681SAndroid Build Coastguard Worker   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
952*9880d681SAndroid Build Coastguard Worker     // If the base pointers are different, but the indices are the same, just
953*9880d681SAndroid Build Coastguard Worker     // compare the base pointer.
954*9880d681SAndroid Build Coastguard Worker     if (PtrBase != GEPRHS->getOperand(0)) {
955*9880d681SAndroid Build Coastguard Worker       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
956*9880d681SAndroid Build Coastguard Worker       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
957*9880d681SAndroid Build Coastguard Worker                         GEPRHS->getOperand(0)->getType();
958*9880d681SAndroid Build Coastguard Worker       if (IndicesTheSame)
959*9880d681SAndroid Build Coastguard Worker         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
960*9880d681SAndroid Build Coastguard Worker           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
961*9880d681SAndroid Build Coastguard Worker             IndicesTheSame = false;
962*9880d681SAndroid Build Coastguard Worker             break;
963*9880d681SAndroid Build Coastguard Worker           }
964*9880d681SAndroid Build Coastguard Worker 
965*9880d681SAndroid Build Coastguard Worker       // If all indices are the same, just compare the base pointers.
966*9880d681SAndroid Build Coastguard Worker       if (IndicesTheSame)
967*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
968*9880d681SAndroid Build Coastguard Worker 
969*9880d681SAndroid Build Coastguard Worker       // If we're comparing GEPs with two base pointers that only differ in type
970*9880d681SAndroid Build Coastguard Worker       // and both GEPs have only constant indices or just one use, then fold
971*9880d681SAndroid Build Coastguard Worker       // the compare with the adjusted indices.
972*9880d681SAndroid Build Coastguard Worker       if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
973*9880d681SAndroid Build Coastguard Worker           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
974*9880d681SAndroid Build Coastguard Worker           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
975*9880d681SAndroid Build Coastguard Worker           PtrBase->stripPointerCasts() ==
976*9880d681SAndroid Build Coastguard Worker               GEPRHS->getOperand(0)->stripPointerCasts()) {
977*9880d681SAndroid Build Coastguard Worker         Value *LOffset = EmitGEPOffset(GEPLHS);
978*9880d681SAndroid Build Coastguard Worker         Value *ROffset = EmitGEPOffset(GEPRHS);
979*9880d681SAndroid Build Coastguard Worker 
980*9880d681SAndroid Build Coastguard Worker         // If we looked through an addrspacecast between different sized address
981*9880d681SAndroid Build Coastguard Worker         // spaces, the LHS and RHS pointers are different sized
982*9880d681SAndroid Build Coastguard Worker         // integers. Truncate to the smaller one.
983*9880d681SAndroid Build Coastguard Worker         Type *LHSIndexTy = LOffset->getType();
984*9880d681SAndroid Build Coastguard Worker         Type *RHSIndexTy = ROffset->getType();
985*9880d681SAndroid Build Coastguard Worker         if (LHSIndexTy != RHSIndexTy) {
986*9880d681SAndroid Build Coastguard Worker           if (LHSIndexTy->getPrimitiveSizeInBits() <
987*9880d681SAndroid Build Coastguard Worker               RHSIndexTy->getPrimitiveSizeInBits()) {
988*9880d681SAndroid Build Coastguard Worker             ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
989*9880d681SAndroid Build Coastguard Worker           } else
990*9880d681SAndroid Build Coastguard Worker             LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
991*9880d681SAndroid Build Coastguard Worker         }
992*9880d681SAndroid Build Coastguard Worker 
993*9880d681SAndroid Build Coastguard Worker         Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
994*9880d681SAndroid Build Coastguard Worker                                          LOffset, ROffset);
995*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Cmp);
996*9880d681SAndroid Build Coastguard Worker       }
997*9880d681SAndroid Build Coastguard Worker 
998*9880d681SAndroid Build Coastguard Worker       // Otherwise, the base pointers are different and the indices are
999*9880d681SAndroid Build Coastguard Worker       // different. Try convert this to an indexed compare by looking through
1000*9880d681SAndroid Build Coastguard Worker       // PHIs/casts.
1001*9880d681SAndroid Build Coastguard Worker       return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
1002*9880d681SAndroid Build Coastguard Worker     }
1003*9880d681SAndroid Build Coastguard Worker 
1004*9880d681SAndroid Build Coastguard Worker     // If one of the GEPs has all zero indices, recurse.
1005*9880d681SAndroid Build Coastguard Worker     if (GEPLHS->hasAllZeroIndices())
1006*9880d681SAndroid Build Coastguard Worker       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
1007*9880d681SAndroid Build Coastguard Worker                          ICmpInst::getSwappedPredicate(Cond), I);
1008*9880d681SAndroid Build Coastguard Worker 
1009*9880d681SAndroid Build Coastguard Worker     // If the other GEP has all zero indices, recurse.
1010*9880d681SAndroid Build Coastguard Worker     if (GEPRHS->hasAllZeroIndices())
1011*9880d681SAndroid Build Coastguard Worker       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
1012*9880d681SAndroid Build Coastguard Worker 
1013*9880d681SAndroid Build Coastguard Worker     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
1014*9880d681SAndroid Build Coastguard Worker     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1015*9880d681SAndroid Build Coastguard Worker       // If the GEPs only differ by one index, compare it.
1016*9880d681SAndroid Build Coastguard Worker       unsigned NumDifferences = 0;  // Keep track of # differences.
1017*9880d681SAndroid Build Coastguard Worker       unsigned DiffOperand = 0;     // The operand that differs.
1018*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1019*9880d681SAndroid Build Coastguard Worker         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1020*9880d681SAndroid Build Coastguard Worker           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1021*9880d681SAndroid Build Coastguard Worker                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1022*9880d681SAndroid Build Coastguard Worker             // Irreconcilable differences.
1023*9880d681SAndroid Build Coastguard Worker             NumDifferences = 2;
1024*9880d681SAndroid Build Coastguard Worker             break;
1025*9880d681SAndroid Build Coastguard Worker           } else {
1026*9880d681SAndroid Build Coastguard Worker             if (NumDifferences++) break;
1027*9880d681SAndroid Build Coastguard Worker             DiffOperand = i;
1028*9880d681SAndroid Build Coastguard Worker           }
1029*9880d681SAndroid Build Coastguard Worker         }
1030*9880d681SAndroid Build Coastguard Worker 
1031*9880d681SAndroid Build Coastguard Worker       if (NumDifferences == 0)   // SAME GEP?
1032*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, // No comparison is needed here.
1033*9880d681SAndroid Build Coastguard Worker                              Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
1034*9880d681SAndroid Build Coastguard Worker 
1035*9880d681SAndroid Build Coastguard Worker       else if (NumDifferences == 1 && GEPsInBounds) {
1036*9880d681SAndroid Build Coastguard Worker         Value *LHSV = GEPLHS->getOperand(DiffOperand);
1037*9880d681SAndroid Build Coastguard Worker         Value *RHSV = GEPRHS->getOperand(DiffOperand);
1038*9880d681SAndroid Build Coastguard Worker         // Make sure we do a signed comparison here.
1039*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1040*9880d681SAndroid Build Coastguard Worker       }
1041*9880d681SAndroid Build Coastguard Worker     }
1042*9880d681SAndroid Build Coastguard Worker 
1043*9880d681SAndroid Build Coastguard Worker     // Only lower this if the icmp is the only user of the GEP or if we expect
1044*9880d681SAndroid Build Coastguard Worker     // the result to fold to a constant!
1045*9880d681SAndroid Build Coastguard Worker     if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
1046*9880d681SAndroid Build Coastguard Worker         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1047*9880d681SAndroid Build Coastguard Worker       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
1048*9880d681SAndroid Build Coastguard Worker       Value *L = EmitGEPOffset(GEPLHS);
1049*9880d681SAndroid Build Coastguard Worker       Value *R = EmitGEPOffset(GEPRHS);
1050*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1051*9880d681SAndroid Build Coastguard Worker     }
1052*9880d681SAndroid Build Coastguard Worker   }
1053*9880d681SAndroid Build Coastguard Worker 
1054*9880d681SAndroid Build Coastguard Worker   // Try convert this to an indexed compare by looking through PHIs/casts as a
1055*9880d681SAndroid Build Coastguard Worker   // last resort.
1056*9880d681SAndroid Build Coastguard Worker   return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
1057*9880d681SAndroid Build Coastguard Worker }
1058*9880d681SAndroid Build Coastguard Worker 
FoldAllocaCmp(ICmpInst & ICI,AllocaInst * Alloca,Value * Other)1059*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca,
1060*9880d681SAndroid Build Coastguard Worker                                          Value *Other) {
1061*9880d681SAndroid Build Coastguard Worker   assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1062*9880d681SAndroid Build Coastguard Worker 
1063*9880d681SAndroid Build Coastguard Worker   // It would be tempting to fold away comparisons between allocas and any
1064*9880d681SAndroid Build Coastguard Worker   // pointer not based on that alloca (e.g. an argument). However, even
1065*9880d681SAndroid Build Coastguard Worker   // though such pointers cannot alias, they can still compare equal.
1066*9880d681SAndroid Build Coastguard Worker   //
1067*9880d681SAndroid Build Coastguard Worker   // But LLVM doesn't specify where allocas get their memory, so if the alloca
1068*9880d681SAndroid Build Coastguard Worker   // doesn't escape we can argue that it's impossible to guess its value, and we
1069*9880d681SAndroid Build Coastguard Worker   // can therefore act as if any such guesses are wrong.
1070*9880d681SAndroid Build Coastguard Worker   //
1071*9880d681SAndroid Build Coastguard Worker   // The code below checks that the alloca doesn't escape, and that it's only
1072*9880d681SAndroid Build Coastguard Worker   // used in a comparison once (the current instruction). The
1073*9880d681SAndroid Build Coastguard Worker   // single-comparison-use condition ensures that we're trivially folding all
1074*9880d681SAndroid Build Coastguard Worker   // comparisons against the alloca consistently, and avoids the risk of
1075*9880d681SAndroid Build Coastguard Worker   // erroneously folding a comparison of the pointer with itself.
1076*9880d681SAndroid Build Coastguard Worker 
1077*9880d681SAndroid Build Coastguard Worker   unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1078*9880d681SAndroid Build Coastguard Worker 
1079*9880d681SAndroid Build Coastguard Worker   SmallVector<Use *, 32> Worklist;
1080*9880d681SAndroid Build Coastguard Worker   for (Use &U : Alloca->uses()) {
1081*9880d681SAndroid Build Coastguard Worker     if (Worklist.size() >= MaxIter)
1082*9880d681SAndroid Build Coastguard Worker       return nullptr;
1083*9880d681SAndroid Build Coastguard Worker     Worklist.push_back(&U);
1084*9880d681SAndroid Build Coastguard Worker   }
1085*9880d681SAndroid Build Coastguard Worker 
1086*9880d681SAndroid Build Coastguard Worker   unsigned NumCmps = 0;
1087*9880d681SAndroid Build Coastguard Worker   while (!Worklist.empty()) {
1088*9880d681SAndroid Build Coastguard Worker     assert(Worklist.size() <= MaxIter);
1089*9880d681SAndroid Build Coastguard Worker     Use *U = Worklist.pop_back_val();
1090*9880d681SAndroid Build Coastguard Worker     Value *V = U->getUser();
1091*9880d681SAndroid Build Coastguard Worker     --MaxIter;
1092*9880d681SAndroid Build Coastguard Worker 
1093*9880d681SAndroid Build Coastguard Worker     if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1094*9880d681SAndroid Build Coastguard Worker         isa<SelectInst>(V)) {
1095*9880d681SAndroid Build Coastguard Worker       // Track the uses.
1096*9880d681SAndroid Build Coastguard Worker     } else if (isa<LoadInst>(V)) {
1097*9880d681SAndroid Build Coastguard Worker       // Loading from the pointer doesn't escape it.
1098*9880d681SAndroid Build Coastguard Worker       continue;
1099*9880d681SAndroid Build Coastguard Worker     } else if (auto *SI = dyn_cast<StoreInst>(V)) {
1100*9880d681SAndroid Build Coastguard Worker       // Storing *to* the pointer is fine, but storing the pointer escapes it.
1101*9880d681SAndroid Build Coastguard Worker       if (SI->getValueOperand() == U->get())
1102*9880d681SAndroid Build Coastguard Worker         return nullptr;
1103*9880d681SAndroid Build Coastguard Worker       continue;
1104*9880d681SAndroid Build Coastguard Worker     } else if (isa<ICmpInst>(V)) {
1105*9880d681SAndroid Build Coastguard Worker       if (NumCmps++)
1106*9880d681SAndroid Build Coastguard Worker         return nullptr; // Found more than one cmp.
1107*9880d681SAndroid Build Coastguard Worker       continue;
1108*9880d681SAndroid Build Coastguard Worker     } else if (auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1109*9880d681SAndroid Build Coastguard Worker       switch (Intrin->getIntrinsicID()) {
1110*9880d681SAndroid Build Coastguard Worker         // These intrinsics don't escape or compare the pointer. Memset is safe
1111*9880d681SAndroid Build Coastguard Worker         // because we don't allow ptrtoint. Memcpy and memmove are safe because
1112*9880d681SAndroid Build Coastguard Worker         // we don't allow stores, so src cannot point to V.
1113*9880d681SAndroid Build Coastguard Worker         case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1114*9880d681SAndroid Build Coastguard Worker         case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1115*9880d681SAndroid Build Coastguard Worker         case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1116*9880d681SAndroid Build Coastguard Worker           continue;
1117*9880d681SAndroid Build Coastguard Worker         default:
1118*9880d681SAndroid Build Coastguard Worker           return nullptr;
1119*9880d681SAndroid Build Coastguard Worker       }
1120*9880d681SAndroid Build Coastguard Worker     } else {
1121*9880d681SAndroid Build Coastguard Worker       return nullptr;
1122*9880d681SAndroid Build Coastguard Worker     }
1123*9880d681SAndroid Build Coastguard Worker     for (Use &U : V->uses()) {
1124*9880d681SAndroid Build Coastguard Worker       if (Worklist.size() >= MaxIter)
1125*9880d681SAndroid Build Coastguard Worker         return nullptr;
1126*9880d681SAndroid Build Coastguard Worker       Worklist.push_back(&U);
1127*9880d681SAndroid Build Coastguard Worker     }
1128*9880d681SAndroid Build Coastguard Worker   }
1129*9880d681SAndroid Build Coastguard Worker 
1130*9880d681SAndroid Build Coastguard Worker   Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
1131*9880d681SAndroid Build Coastguard Worker   return replaceInstUsesWith(
1132*9880d681SAndroid Build Coastguard Worker       ICI,
1133*9880d681SAndroid Build Coastguard Worker       ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1134*9880d681SAndroid Build Coastguard Worker }
1135*9880d681SAndroid Build Coastguard Worker 
1136*9880d681SAndroid Build Coastguard Worker /// Fold "icmp pred (X+CI), X".
FoldICmpAddOpCst(Instruction & ICI,Value * X,ConstantInt * CI,ICmpInst::Predicate Pred)1137*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
1138*9880d681SAndroid Build Coastguard Worker                                             Value *X, ConstantInt *CI,
1139*9880d681SAndroid Build Coastguard Worker                                             ICmpInst::Predicate Pred) {
1140*9880d681SAndroid Build Coastguard Worker   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
1141*9880d681SAndroid Build Coastguard Worker   // so the values can never be equal.  Similarly for all other "or equals"
1142*9880d681SAndroid Build Coastguard Worker   // operators.
1143*9880d681SAndroid Build Coastguard Worker 
1144*9880d681SAndroid Build Coastguard Worker   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
1145*9880d681SAndroid Build Coastguard Worker   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
1146*9880d681SAndroid Build Coastguard Worker   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
1147*9880d681SAndroid Build Coastguard Worker   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1148*9880d681SAndroid Build Coastguard Worker     Value *R =
1149*9880d681SAndroid Build Coastguard Worker       ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
1150*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1151*9880d681SAndroid Build Coastguard Worker   }
1152*9880d681SAndroid Build Coastguard Worker 
1153*9880d681SAndroid Build Coastguard Worker   // (X+1) >u X        --> X <u (0-1)        --> X != 255
1154*9880d681SAndroid Build Coastguard Worker   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
1155*9880d681SAndroid Build Coastguard Worker   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
1156*9880d681SAndroid Build Coastguard Worker   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
1157*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
1158*9880d681SAndroid Build Coastguard Worker 
1159*9880d681SAndroid Build Coastguard Worker   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1160*9880d681SAndroid Build Coastguard Worker   ConstantInt *SMax = ConstantInt::get(X->getContext(),
1161*9880d681SAndroid Build Coastguard Worker                                        APInt::getSignedMaxValue(BitWidth));
1162*9880d681SAndroid Build Coastguard Worker 
1163*9880d681SAndroid Build Coastguard Worker   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
1164*9880d681SAndroid Build Coastguard Worker   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
1165*9880d681SAndroid Build Coastguard Worker   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
1166*9880d681SAndroid Build Coastguard Worker   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
1167*9880d681SAndroid Build Coastguard Worker   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
1168*9880d681SAndroid Build Coastguard Worker   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
1169*9880d681SAndroid Build Coastguard Worker   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1170*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
1171*9880d681SAndroid Build Coastguard Worker 
1172*9880d681SAndroid Build Coastguard Worker   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
1173*9880d681SAndroid Build Coastguard Worker   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
1174*9880d681SAndroid Build Coastguard Worker   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1175*9880d681SAndroid Build Coastguard Worker   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1176*9880d681SAndroid Build Coastguard Worker   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
1177*9880d681SAndroid Build Coastguard Worker   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
1178*9880d681SAndroid Build Coastguard Worker 
1179*9880d681SAndroid Build Coastguard Worker   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1180*9880d681SAndroid Build Coastguard Worker   Constant *C = Builder->getInt(CI->getValue()-1);
1181*9880d681SAndroid Build Coastguard Worker   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1182*9880d681SAndroid Build Coastguard Worker }
1183*9880d681SAndroid Build Coastguard Worker 
1184*9880d681SAndroid Build Coastguard Worker /// Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS and CmpRHS are
1185*9880d681SAndroid Build Coastguard Worker /// both known to be integer constants.
FoldICmpDivCst(ICmpInst & ICI,BinaryOperator * DivI,ConstantInt * DivRHS)1186*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
1187*9880d681SAndroid Build Coastguard Worker                                           ConstantInt *DivRHS) {
1188*9880d681SAndroid Build Coastguard Worker   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1189*9880d681SAndroid Build Coastguard Worker   const APInt &CmpRHSV = CmpRHS->getValue();
1190*9880d681SAndroid Build Coastguard Worker 
1191*9880d681SAndroid Build Coastguard Worker   // FIXME: If the operand types don't match the type of the divide
1192*9880d681SAndroid Build Coastguard Worker   // then don't attempt this transform. The code below doesn't have the
1193*9880d681SAndroid Build Coastguard Worker   // logic to deal with a signed divide and an unsigned compare (and
1194*9880d681SAndroid Build Coastguard Worker   // vice versa). This is because (x /s C1) <s C2  produces different
1195*9880d681SAndroid Build Coastguard Worker   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
1196*9880d681SAndroid Build Coastguard Worker   // (x /u C1) <u C2.  Simply casting the operands and result won't
1197*9880d681SAndroid Build Coastguard Worker   // work. :(  The if statement below tests that condition and bails
1198*9880d681SAndroid Build Coastguard Worker   // if it finds it.
1199*9880d681SAndroid Build Coastguard Worker   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1200*9880d681SAndroid Build Coastguard Worker   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
1201*9880d681SAndroid Build Coastguard Worker     return nullptr;
1202*9880d681SAndroid Build Coastguard Worker   if (DivRHS->isZero())
1203*9880d681SAndroid Build Coastguard Worker     return nullptr; // The ProdOV computation fails on divide by zero.
1204*9880d681SAndroid Build Coastguard Worker   if (DivIsSigned && DivRHS->isAllOnesValue())
1205*9880d681SAndroid Build Coastguard Worker     return nullptr; // The overflow computation also screws up here
1206*9880d681SAndroid Build Coastguard Worker   if (DivRHS->isOne()) {
1207*9880d681SAndroid Build Coastguard Worker     // This eliminates some funny cases with INT_MIN.
1208*9880d681SAndroid Build Coastguard Worker     ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
1209*9880d681SAndroid Build Coastguard Worker     return &ICI;
1210*9880d681SAndroid Build Coastguard Worker   }
1211*9880d681SAndroid Build Coastguard Worker 
1212*9880d681SAndroid Build Coastguard Worker   // Compute Prod = CI * DivRHS. We are essentially solving an equation
1213*9880d681SAndroid Build Coastguard Worker   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1214*9880d681SAndroid Build Coastguard Worker   // C2 (CI). By solving for X we can turn this into a range check
1215*9880d681SAndroid Build Coastguard Worker   // instead of computing a divide.
1216*9880d681SAndroid Build Coastguard Worker   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1217*9880d681SAndroid Build Coastguard Worker 
1218*9880d681SAndroid Build Coastguard Worker   // Determine if the product overflows by seeing if the product is
1219*9880d681SAndroid Build Coastguard Worker   // not equal to the divide. Make sure we do the same kind of divide
1220*9880d681SAndroid Build Coastguard Worker   // as in the LHS instruction that we're folding.
1221*9880d681SAndroid Build Coastguard Worker   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1222*9880d681SAndroid Build Coastguard Worker                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1223*9880d681SAndroid Build Coastguard Worker 
1224*9880d681SAndroid Build Coastguard Worker   // Get the ICmp opcode
1225*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate Pred = ICI.getPredicate();
1226*9880d681SAndroid Build Coastguard Worker 
1227*9880d681SAndroid Build Coastguard Worker   // If the division is known to be exact, then there is no remainder from the
1228*9880d681SAndroid Build Coastguard Worker   // divide, so the covered range size is unit, otherwise it is the divisor.
1229*9880d681SAndroid Build Coastguard Worker   ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
1230*9880d681SAndroid Build Coastguard Worker 
1231*9880d681SAndroid Build Coastguard Worker   // Figure out the interval that is being checked.  For example, a comparison
1232*9880d681SAndroid Build Coastguard Worker   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
1233*9880d681SAndroid Build Coastguard Worker   // Compute this interval based on the constants involved and the signedness of
1234*9880d681SAndroid Build Coastguard Worker   // the compare/divide.  This computes a half-open interval, keeping track of
1235*9880d681SAndroid Build Coastguard Worker   // whether either value in the interval overflows.  After analysis each
1236*9880d681SAndroid Build Coastguard Worker   // overflow variable is set to 0 if it's corresponding bound variable is valid
1237*9880d681SAndroid Build Coastguard Worker   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1238*9880d681SAndroid Build Coastguard Worker   int LoOverflow = 0, HiOverflow = 0;
1239*9880d681SAndroid Build Coastguard Worker   Constant *LoBound = nullptr, *HiBound = nullptr;
1240*9880d681SAndroid Build Coastguard Worker 
1241*9880d681SAndroid Build Coastguard Worker   if (!DivIsSigned) {  // udiv
1242*9880d681SAndroid Build Coastguard Worker     // e.g. X/5 op 3  --> [15, 20)
1243*9880d681SAndroid Build Coastguard Worker     LoBound = Prod;
1244*9880d681SAndroid Build Coastguard Worker     HiOverflow = LoOverflow = ProdOV;
1245*9880d681SAndroid Build Coastguard Worker     if (!HiOverflow) {
1246*9880d681SAndroid Build Coastguard Worker       // If this is not an exact divide, then many values in the range collapse
1247*9880d681SAndroid Build Coastguard Worker       // to the same result value.
1248*9880d681SAndroid Build Coastguard Worker       HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1249*9880d681SAndroid Build Coastguard Worker     }
1250*9880d681SAndroid Build Coastguard Worker   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1251*9880d681SAndroid Build Coastguard Worker     if (CmpRHSV == 0) {       // (X / pos) op 0
1252*9880d681SAndroid Build Coastguard Worker       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
1253*9880d681SAndroid Build Coastguard Worker       LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1254*9880d681SAndroid Build Coastguard Worker       HiBound = RangeSize;
1255*9880d681SAndroid Build Coastguard Worker     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
1256*9880d681SAndroid Build Coastguard Worker       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
1257*9880d681SAndroid Build Coastguard Worker       HiOverflow = LoOverflow = ProdOV;
1258*9880d681SAndroid Build Coastguard Worker       if (!HiOverflow)
1259*9880d681SAndroid Build Coastguard Worker         HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
1260*9880d681SAndroid Build Coastguard Worker     } else {                       // (X / pos) op neg
1261*9880d681SAndroid Build Coastguard Worker       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
1262*9880d681SAndroid Build Coastguard Worker       HiBound = AddOne(Prod);
1263*9880d681SAndroid Build Coastguard Worker       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1264*9880d681SAndroid Build Coastguard Worker       if (!LoOverflow) {
1265*9880d681SAndroid Build Coastguard Worker         ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
1266*9880d681SAndroid Build Coastguard Worker         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
1267*9880d681SAndroid Build Coastguard Worker       }
1268*9880d681SAndroid Build Coastguard Worker     }
1269*9880d681SAndroid Build Coastguard Worker   } else if (DivRHS->isNegative()) { // Divisor is < 0.
1270*9880d681SAndroid Build Coastguard Worker     if (DivI->isExact())
1271*9880d681SAndroid Build Coastguard Worker       RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
1272*9880d681SAndroid Build Coastguard Worker     if (CmpRHSV == 0) {       // (X / neg) op 0
1273*9880d681SAndroid Build Coastguard Worker       // e.g. X/-5 op 0  --> [-4, 5)
1274*9880d681SAndroid Build Coastguard Worker       LoBound = AddOne(RangeSize);
1275*9880d681SAndroid Build Coastguard Worker       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
1276*9880d681SAndroid Build Coastguard Worker       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
1277*9880d681SAndroid Build Coastguard Worker         HiOverflow = 1;            // [INTMIN+1, overflow)
1278*9880d681SAndroid Build Coastguard Worker         HiBound = nullptr;         // e.g. X/INTMIN = 0 --> X > INTMIN
1279*9880d681SAndroid Build Coastguard Worker       }
1280*9880d681SAndroid Build Coastguard Worker     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
1281*9880d681SAndroid Build Coastguard Worker       // e.g. X/-5 op 3  --> [-19, -14)
1282*9880d681SAndroid Build Coastguard Worker       HiBound = AddOne(Prod);
1283*9880d681SAndroid Build Coastguard Worker       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1284*9880d681SAndroid Build Coastguard Worker       if (!LoOverflow)
1285*9880d681SAndroid Build Coastguard Worker         LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
1286*9880d681SAndroid Build Coastguard Worker     } else {                       // (X / neg) op neg
1287*9880d681SAndroid Build Coastguard Worker       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
1288*9880d681SAndroid Build Coastguard Worker       LoOverflow = HiOverflow = ProdOV;
1289*9880d681SAndroid Build Coastguard Worker       if (!HiOverflow)
1290*9880d681SAndroid Build Coastguard Worker         HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
1291*9880d681SAndroid Build Coastguard Worker     }
1292*9880d681SAndroid Build Coastguard Worker 
1293*9880d681SAndroid Build Coastguard Worker     // Dividing by a negative swaps the condition.  LT <-> GT
1294*9880d681SAndroid Build Coastguard Worker     Pred = ICmpInst::getSwappedPredicate(Pred);
1295*9880d681SAndroid Build Coastguard Worker   }
1296*9880d681SAndroid Build Coastguard Worker 
1297*9880d681SAndroid Build Coastguard Worker   Value *X = DivI->getOperand(0);
1298*9880d681SAndroid Build Coastguard Worker   switch (Pred) {
1299*9880d681SAndroid Build Coastguard Worker   default: llvm_unreachable("Unhandled icmp opcode!");
1300*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_EQ:
1301*9880d681SAndroid Build Coastguard Worker     if (LoOverflow && HiOverflow)
1302*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getFalse());
1303*9880d681SAndroid Build Coastguard Worker     if (HiOverflow)
1304*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1305*9880d681SAndroid Build Coastguard Worker                           ICmpInst::ICMP_UGE, X, LoBound);
1306*9880d681SAndroid Build Coastguard Worker     if (LoOverflow)
1307*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1308*9880d681SAndroid Build Coastguard Worker                           ICmpInst::ICMP_ULT, X, HiBound);
1309*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
1310*9880d681SAndroid Build Coastguard Worker                                                     DivIsSigned, true));
1311*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_NE:
1312*9880d681SAndroid Build Coastguard Worker     if (LoOverflow && HiOverflow)
1313*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getTrue());
1314*9880d681SAndroid Build Coastguard Worker     if (HiOverflow)
1315*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1316*9880d681SAndroid Build Coastguard Worker                           ICmpInst::ICMP_ULT, X, LoBound);
1317*9880d681SAndroid Build Coastguard Worker     if (LoOverflow)
1318*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1319*9880d681SAndroid Build Coastguard Worker                           ICmpInst::ICMP_UGE, X, HiBound);
1320*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
1321*9880d681SAndroid Build Coastguard Worker                                                     DivIsSigned, false));
1322*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULT:
1323*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SLT:
1324*9880d681SAndroid Build Coastguard Worker     if (LoOverflow == +1)   // Low bound is greater than input range.
1325*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getTrue());
1326*9880d681SAndroid Build Coastguard Worker     if (LoOverflow == -1)   // Low bound is less than input range.
1327*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getFalse());
1328*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(Pred, X, LoBound);
1329*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGT:
1330*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_SGT:
1331*9880d681SAndroid Build Coastguard Worker     if (HiOverflow == +1)       // High bound greater than input range.
1332*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getFalse());
1333*9880d681SAndroid Build Coastguard Worker     if (HiOverflow == -1)       // High bound less than input range.
1334*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(ICI, Builder->getTrue());
1335*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_UGT)
1336*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
1337*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
1338*9880d681SAndroid Build Coastguard Worker   }
1339*9880d681SAndroid Build Coastguard Worker }
1340*9880d681SAndroid Build Coastguard Worker 
1341*9880d681SAndroid Build Coastguard Worker /// Handle "icmp(([al]shr X, cst1), cst2)".
FoldICmpShrCst(ICmpInst & ICI,BinaryOperator * Shr,ConstantInt * ShAmt)1342*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
1343*9880d681SAndroid Build Coastguard Worker                                           ConstantInt *ShAmt) {
1344*9880d681SAndroid Build Coastguard Worker   const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
1345*9880d681SAndroid Build Coastguard Worker 
1346*9880d681SAndroid Build Coastguard Worker   // Check that the shift amount is in range.  If not, don't perform
1347*9880d681SAndroid Build Coastguard Worker   // undefined shifts.  When the shift is visited it will be
1348*9880d681SAndroid Build Coastguard Worker   // simplified.
1349*9880d681SAndroid Build Coastguard Worker   uint32_t TypeBits = CmpRHSV.getBitWidth();
1350*9880d681SAndroid Build Coastguard Worker   uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1351*9880d681SAndroid Build Coastguard Worker   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
1352*9880d681SAndroid Build Coastguard Worker     return nullptr;
1353*9880d681SAndroid Build Coastguard Worker 
1354*9880d681SAndroid Build Coastguard Worker   if (!ICI.isEquality()) {
1355*9880d681SAndroid Build Coastguard Worker     // If we have an unsigned comparison and an ashr, we can't simplify this.
1356*9880d681SAndroid Build Coastguard Worker     // Similarly for signed comparisons with lshr.
1357*9880d681SAndroid Build Coastguard Worker     if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
1358*9880d681SAndroid Build Coastguard Worker       return nullptr;
1359*9880d681SAndroid Build Coastguard Worker 
1360*9880d681SAndroid Build Coastguard Worker     // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1361*9880d681SAndroid Build Coastguard Worker     // by a power of 2.  Since we already have logic to simplify these,
1362*9880d681SAndroid Build Coastguard Worker     // transform to div and then simplify the resultant comparison.
1363*9880d681SAndroid Build Coastguard Worker     if (Shr->getOpcode() == Instruction::AShr &&
1364*9880d681SAndroid Build Coastguard Worker         (!Shr->isExact() || ShAmtVal == TypeBits - 1))
1365*9880d681SAndroid Build Coastguard Worker       return nullptr;
1366*9880d681SAndroid Build Coastguard Worker 
1367*9880d681SAndroid Build Coastguard Worker     // Revisit the shift (to delete it).
1368*9880d681SAndroid Build Coastguard Worker     Worklist.Add(Shr);
1369*9880d681SAndroid Build Coastguard Worker 
1370*9880d681SAndroid Build Coastguard Worker     Constant *DivCst =
1371*9880d681SAndroid Build Coastguard Worker       ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
1372*9880d681SAndroid Build Coastguard Worker 
1373*9880d681SAndroid Build Coastguard Worker     Value *Tmp =
1374*9880d681SAndroid Build Coastguard Worker       Shr->getOpcode() == Instruction::AShr ?
1375*9880d681SAndroid Build Coastguard Worker       Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1376*9880d681SAndroid Build Coastguard Worker       Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
1377*9880d681SAndroid Build Coastguard Worker 
1378*9880d681SAndroid Build Coastguard Worker     ICI.setOperand(0, Tmp);
1379*9880d681SAndroid Build Coastguard Worker 
1380*9880d681SAndroid Build Coastguard Worker     // If the builder folded the binop, just return it.
1381*9880d681SAndroid Build Coastguard Worker     BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1382*9880d681SAndroid Build Coastguard Worker     if (!TheDiv)
1383*9880d681SAndroid Build Coastguard Worker       return &ICI;
1384*9880d681SAndroid Build Coastguard Worker 
1385*9880d681SAndroid Build Coastguard Worker     // Otherwise, fold this div/compare.
1386*9880d681SAndroid Build Coastguard Worker     assert(TheDiv->getOpcode() == Instruction::SDiv ||
1387*9880d681SAndroid Build Coastguard Worker            TheDiv->getOpcode() == Instruction::UDiv);
1388*9880d681SAndroid Build Coastguard Worker 
1389*9880d681SAndroid Build Coastguard Worker     Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1390*9880d681SAndroid Build Coastguard Worker     assert(Res && "This div/cst should have folded!");
1391*9880d681SAndroid Build Coastguard Worker     return Res;
1392*9880d681SAndroid Build Coastguard Worker   }
1393*9880d681SAndroid Build Coastguard Worker 
1394*9880d681SAndroid Build Coastguard Worker   // If we are comparing against bits always shifted out, the
1395*9880d681SAndroid Build Coastguard Worker   // comparison cannot succeed.
1396*9880d681SAndroid Build Coastguard Worker   APInt Comp = CmpRHSV << ShAmtVal;
1397*9880d681SAndroid Build Coastguard Worker   ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
1398*9880d681SAndroid Build Coastguard Worker   if (Shr->getOpcode() == Instruction::LShr)
1399*9880d681SAndroid Build Coastguard Worker     Comp = Comp.lshr(ShAmtVal);
1400*9880d681SAndroid Build Coastguard Worker   else
1401*9880d681SAndroid Build Coastguard Worker     Comp = Comp.ashr(ShAmtVal);
1402*9880d681SAndroid Build Coastguard Worker 
1403*9880d681SAndroid Build Coastguard Worker   if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1404*9880d681SAndroid Build Coastguard Worker     bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1405*9880d681SAndroid Build Coastguard Worker     Constant *Cst = Builder->getInt1(IsICMP_NE);
1406*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(ICI, Cst);
1407*9880d681SAndroid Build Coastguard Worker   }
1408*9880d681SAndroid Build Coastguard Worker 
1409*9880d681SAndroid Build Coastguard Worker   // Otherwise, check to see if the bits shifted out are known to be zero.
1410*9880d681SAndroid Build Coastguard Worker   // If so, we can compare against the unshifted value:
1411*9880d681SAndroid Build Coastguard Worker   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
1412*9880d681SAndroid Build Coastguard Worker   if (Shr->hasOneUse() && Shr->isExact())
1413*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1414*9880d681SAndroid Build Coastguard Worker 
1415*9880d681SAndroid Build Coastguard Worker   if (Shr->hasOneUse()) {
1416*9880d681SAndroid Build Coastguard Worker     // Otherwise strength reduce the shift into an and.
1417*9880d681SAndroid Build Coastguard Worker     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1418*9880d681SAndroid Build Coastguard Worker     Constant *Mask = Builder->getInt(Val);
1419*9880d681SAndroid Build Coastguard Worker 
1420*9880d681SAndroid Build Coastguard Worker     Value *And = Builder->CreateAnd(Shr->getOperand(0),
1421*9880d681SAndroid Build Coastguard Worker                                     Mask, Shr->getName()+".mask");
1422*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1423*9880d681SAndroid Build Coastguard Worker   }
1424*9880d681SAndroid Build Coastguard Worker   return nullptr;
1425*9880d681SAndroid Build Coastguard Worker }
1426*9880d681SAndroid Build Coastguard Worker 
1427*9880d681SAndroid Build Coastguard Worker /// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1428*9880d681SAndroid Build Coastguard Worker /// (icmp eq/ne A, Log2(const2/const1)) ->
1429*9880d681SAndroid Build Coastguard Worker /// (icmp eq/ne A, Log2(const2) - Log2(const1)).
FoldICmpCstShrCst(ICmpInst & I,Value * Op,Value * A,ConstantInt * CI1,ConstantInt * CI2)1430*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1431*9880d681SAndroid Build Coastguard Worker                                              ConstantInt *CI1,
1432*9880d681SAndroid Build Coastguard Worker                                              ConstantInt *CI2) {
1433*9880d681SAndroid Build Coastguard Worker   assert(I.isEquality() && "Cannot fold icmp gt/lt");
1434*9880d681SAndroid Build Coastguard Worker 
1435*9880d681SAndroid Build Coastguard Worker   auto getConstant = [&I, this](bool IsTrue) {
1436*9880d681SAndroid Build Coastguard Worker     if (I.getPredicate() == I.ICMP_NE)
1437*9880d681SAndroid Build Coastguard Worker       IsTrue = !IsTrue;
1438*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1439*9880d681SAndroid Build Coastguard Worker   };
1440*9880d681SAndroid Build Coastguard Worker 
1441*9880d681SAndroid Build Coastguard Worker   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1442*9880d681SAndroid Build Coastguard Worker     if (I.getPredicate() == I.ICMP_NE)
1443*9880d681SAndroid Build Coastguard Worker       Pred = CmpInst::getInversePredicate(Pred);
1444*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(Pred, LHS, RHS);
1445*9880d681SAndroid Build Coastguard Worker   };
1446*9880d681SAndroid Build Coastguard Worker 
1447*9880d681SAndroid Build Coastguard Worker   const APInt &AP1 = CI1->getValue();
1448*9880d681SAndroid Build Coastguard Worker   const APInt &AP2 = CI2->getValue();
1449*9880d681SAndroid Build Coastguard Worker 
1450*9880d681SAndroid Build Coastguard Worker   // Don't bother doing any work for cases which InstSimplify handles.
1451*9880d681SAndroid Build Coastguard Worker   if (AP2 == 0)
1452*9880d681SAndroid Build Coastguard Worker     return nullptr;
1453*9880d681SAndroid Build Coastguard Worker   bool IsAShr = isa<AShrOperator>(Op);
1454*9880d681SAndroid Build Coastguard Worker   if (IsAShr) {
1455*9880d681SAndroid Build Coastguard Worker     if (AP2.isAllOnesValue())
1456*9880d681SAndroid Build Coastguard Worker       return nullptr;
1457*9880d681SAndroid Build Coastguard Worker     if (AP2.isNegative() != AP1.isNegative())
1458*9880d681SAndroid Build Coastguard Worker       return nullptr;
1459*9880d681SAndroid Build Coastguard Worker     if (AP2.sgt(AP1))
1460*9880d681SAndroid Build Coastguard Worker       return nullptr;
1461*9880d681SAndroid Build Coastguard Worker   }
1462*9880d681SAndroid Build Coastguard Worker 
1463*9880d681SAndroid Build Coastguard Worker   if (!AP1)
1464*9880d681SAndroid Build Coastguard Worker     // 'A' must be large enough to shift out the highest set bit.
1465*9880d681SAndroid Build Coastguard Worker     return getICmp(I.ICMP_UGT, A,
1466*9880d681SAndroid Build Coastguard Worker                    ConstantInt::get(A->getType(), AP2.logBase2()));
1467*9880d681SAndroid Build Coastguard Worker 
1468*9880d681SAndroid Build Coastguard Worker   if (AP1 == AP2)
1469*9880d681SAndroid Build Coastguard Worker     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1470*9880d681SAndroid Build Coastguard Worker 
1471*9880d681SAndroid Build Coastguard Worker   int Shift;
1472*9880d681SAndroid Build Coastguard Worker   if (IsAShr && AP1.isNegative())
1473*9880d681SAndroid Build Coastguard Worker     Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
1474*9880d681SAndroid Build Coastguard Worker   else
1475*9880d681SAndroid Build Coastguard Worker     Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
1476*9880d681SAndroid Build Coastguard Worker 
1477*9880d681SAndroid Build Coastguard Worker   if (Shift > 0) {
1478*9880d681SAndroid Build Coastguard Worker     if (IsAShr && AP1 == AP2.ashr(Shift)) {
1479*9880d681SAndroid Build Coastguard Worker       // There are multiple solutions if we are comparing against -1 and the LHS
1480*9880d681SAndroid Build Coastguard Worker       // of the ashr is not a power of two.
1481*9880d681SAndroid Build Coastguard Worker       if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1482*9880d681SAndroid Build Coastguard Worker         return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1483*9880d681SAndroid Build Coastguard Worker       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1484*9880d681SAndroid Build Coastguard Worker     } else if (AP1 == AP2.lshr(Shift)) {
1485*9880d681SAndroid Build Coastguard Worker       return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1486*9880d681SAndroid Build Coastguard Worker     }
1487*9880d681SAndroid Build Coastguard Worker   }
1488*9880d681SAndroid Build Coastguard Worker   // Shifting const2 will never be equal to const1.
1489*9880d681SAndroid Build Coastguard Worker   return getConstant(false);
1490*9880d681SAndroid Build Coastguard Worker }
1491*9880d681SAndroid Build Coastguard Worker 
1492*9880d681SAndroid Build Coastguard Worker /// Handle "(icmp eq/ne (shl const2, A), const1)" ->
1493*9880d681SAndroid Build Coastguard Worker /// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
FoldICmpCstShlCst(ICmpInst & I,Value * Op,Value * A,ConstantInt * CI1,ConstantInt * CI2)1494*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
1495*9880d681SAndroid Build Coastguard Worker                                              ConstantInt *CI1,
1496*9880d681SAndroid Build Coastguard Worker                                              ConstantInt *CI2) {
1497*9880d681SAndroid Build Coastguard Worker   assert(I.isEquality() && "Cannot fold icmp gt/lt");
1498*9880d681SAndroid Build Coastguard Worker 
1499*9880d681SAndroid Build Coastguard Worker   auto getConstant = [&I, this](bool IsTrue) {
1500*9880d681SAndroid Build Coastguard Worker     if (I.getPredicate() == I.ICMP_NE)
1501*9880d681SAndroid Build Coastguard Worker       IsTrue = !IsTrue;
1502*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1503*9880d681SAndroid Build Coastguard Worker   };
1504*9880d681SAndroid Build Coastguard Worker 
1505*9880d681SAndroid Build Coastguard Worker   auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1506*9880d681SAndroid Build Coastguard Worker     if (I.getPredicate() == I.ICMP_NE)
1507*9880d681SAndroid Build Coastguard Worker       Pred = CmpInst::getInversePredicate(Pred);
1508*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(Pred, LHS, RHS);
1509*9880d681SAndroid Build Coastguard Worker   };
1510*9880d681SAndroid Build Coastguard Worker 
1511*9880d681SAndroid Build Coastguard Worker   const APInt &AP1 = CI1->getValue();
1512*9880d681SAndroid Build Coastguard Worker   const APInt &AP2 = CI2->getValue();
1513*9880d681SAndroid Build Coastguard Worker 
1514*9880d681SAndroid Build Coastguard Worker   // Don't bother doing any work for cases which InstSimplify handles.
1515*9880d681SAndroid Build Coastguard Worker   if (AP2 == 0)
1516*9880d681SAndroid Build Coastguard Worker     return nullptr;
1517*9880d681SAndroid Build Coastguard Worker 
1518*9880d681SAndroid Build Coastguard Worker   unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1519*9880d681SAndroid Build Coastguard Worker 
1520*9880d681SAndroid Build Coastguard Worker   if (!AP1 && AP2TrailingZeros != 0)
1521*9880d681SAndroid Build Coastguard Worker     return getICmp(I.ICMP_UGE, A,
1522*9880d681SAndroid Build Coastguard Worker                    ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1523*9880d681SAndroid Build Coastguard Worker 
1524*9880d681SAndroid Build Coastguard Worker   if (AP1 == AP2)
1525*9880d681SAndroid Build Coastguard Worker     return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1526*9880d681SAndroid Build Coastguard Worker 
1527*9880d681SAndroid Build Coastguard Worker   // Get the distance between the lowest bits that are set.
1528*9880d681SAndroid Build Coastguard Worker   int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1529*9880d681SAndroid Build Coastguard Worker 
1530*9880d681SAndroid Build Coastguard Worker   if (Shift > 0 && AP2.shl(Shift) == AP1)
1531*9880d681SAndroid Build Coastguard Worker     return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1532*9880d681SAndroid Build Coastguard Worker 
1533*9880d681SAndroid Build Coastguard Worker   // Shifting const2 will never be equal to const1.
1534*9880d681SAndroid Build Coastguard Worker   return getConstant(false);
1535*9880d681SAndroid Build Coastguard Worker }
1536*9880d681SAndroid Build Coastguard Worker 
1537*9880d681SAndroid Build Coastguard Worker /// Handle "icmp (instr, intcst)".
visitICmpInstWithInstAndIntCst(ICmpInst & ICI,Instruction * LHSI,ConstantInt * RHS)1538*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1539*9880d681SAndroid Build Coastguard Worker                                                           Instruction *LHSI,
1540*9880d681SAndroid Build Coastguard Worker                                                           ConstantInt *RHS) {
1541*9880d681SAndroid Build Coastguard Worker   const APInt &RHSV = RHS->getValue();
1542*9880d681SAndroid Build Coastguard Worker 
1543*9880d681SAndroid Build Coastguard Worker   switch (LHSI->getOpcode()) {
1544*9880d681SAndroid Build Coastguard Worker   case Instruction::Trunc:
1545*9880d681SAndroid Build Coastguard Worker     if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1546*9880d681SAndroid Build Coastguard Worker       // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1547*9880d681SAndroid Build Coastguard Worker       Value *V = nullptr;
1548*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1549*9880d681SAndroid Build Coastguard Worker           match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1550*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_SLT, V,
1551*9880d681SAndroid Build Coastguard Worker                             ConstantInt::get(V->getType(), 1));
1552*9880d681SAndroid Build Coastguard Worker     }
1553*9880d681SAndroid Build Coastguard Worker     if (ICI.isEquality() && LHSI->hasOneUse()) {
1554*9880d681SAndroid Build Coastguard Worker       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1555*9880d681SAndroid Build Coastguard Worker       // of the high bits truncated out of x are known.
1556*9880d681SAndroid Build Coastguard Worker       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1557*9880d681SAndroid Build Coastguard Worker              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1558*9880d681SAndroid Build Coastguard Worker       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1559*9880d681SAndroid Build Coastguard Worker       computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
1560*9880d681SAndroid Build Coastguard Worker 
1561*9880d681SAndroid Build Coastguard Worker       // If all the high bits are known, we can do this xform.
1562*9880d681SAndroid Build Coastguard Worker       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1563*9880d681SAndroid Build Coastguard Worker         // Pull in the high bits from known-ones set.
1564*9880d681SAndroid Build Coastguard Worker         APInt NewRHS = RHS->getValue().zext(SrcBits);
1565*9880d681SAndroid Build Coastguard Worker         NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1566*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1567*9880d681SAndroid Build Coastguard Worker                             Builder->getInt(NewRHS));
1568*9880d681SAndroid Build Coastguard Worker       }
1569*9880d681SAndroid Build Coastguard Worker     }
1570*9880d681SAndroid Build Coastguard Worker     break;
1571*9880d681SAndroid Build Coastguard Worker 
1572*9880d681SAndroid Build Coastguard Worker   case Instruction::Xor:         // (icmp pred (xor X, XorCst), CI)
1573*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1574*9880d681SAndroid Build Coastguard Worker       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1575*9880d681SAndroid Build Coastguard Worker       // fold the xor.
1576*9880d681SAndroid Build Coastguard Worker       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1577*9880d681SAndroid Build Coastguard Worker           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1578*9880d681SAndroid Build Coastguard Worker         Value *CompareVal = LHSI->getOperand(0);
1579*9880d681SAndroid Build Coastguard Worker 
1580*9880d681SAndroid Build Coastguard Worker         // If the sign bit of the XorCst is not set, there is no change to
1581*9880d681SAndroid Build Coastguard Worker         // the operation, just stop using the Xor.
1582*9880d681SAndroid Build Coastguard Worker         if (!XorCst->isNegative()) {
1583*9880d681SAndroid Build Coastguard Worker           ICI.setOperand(0, CompareVal);
1584*9880d681SAndroid Build Coastguard Worker           Worklist.Add(LHSI);
1585*9880d681SAndroid Build Coastguard Worker           return &ICI;
1586*9880d681SAndroid Build Coastguard Worker         }
1587*9880d681SAndroid Build Coastguard Worker 
1588*9880d681SAndroid Build Coastguard Worker         // Was the old condition true if the operand is positive?
1589*9880d681SAndroid Build Coastguard Worker         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1590*9880d681SAndroid Build Coastguard Worker 
1591*9880d681SAndroid Build Coastguard Worker         // If so, the new one isn't.
1592*9880d681SAndroid Build Coastguard Worker         isTrueIfPositive ^= true;
1593*9880d681SAndroid Build Coastguard Worker 
1594*9880d681SAndroid Build Coastguard Worker         if (isTrueIfPositive)
1595*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1596*9880d681SAndroid Build Coastguard Worker                               SubOne(RHS));
1597*9880d681SAndroid Build Coastguard Worker         else
1598*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1599*9880d681SAndroid Build Coastguard Worker                               AddOne(RHS));
1600*9880d681SAndroid Build Coastguard Worker       }
1601*9880d681SAndroid Build Coastguard Worker 
1602*9880d681SAndroid Build Coastguard Worker       if (LHSI->hasOneUse()) {
1603*9880d681SAndroid Build Coastguard Worker         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1604*9880d681SAndroid Build Coastguard Worker         if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1605*9880d681SAndroid Build Coastguard Worker           const APInt &SignBit = XorCst->getValue();
1606*9880d681SAndroid Build Coastguard Worker           ICmpInst::Predicate Pred = ICI.isSigned()
1607*9880d681SAndroid Build Coastguard Worker                                          ? ICI.getUnsignedPredicate()
1608*9880d681SAndroid Build Coastguard Worker                                          : ICI.getSignedPredicate();
1609*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(Pred, LHSI->getOperand(0),
1610*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(RHSV ^ SignBit));
1611*9880d681SAndroid Build Coastguard Worker         }
1612*9880d681SAndroid Build Coastguard Worker 
1613*9880d681SAndroid Build Coastguard Worker         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1614*9880d681SAndroid Build Coastguard Worker         if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1615*9880d681SAndroid Build Coastguard Worker           const APInt &NotSignBit = XorCst->getValue();
1616*9880d681SAndroid Build Coastguard Worker           ICmpInst::Predicate Pred = ICI.isSigned()
1617*9880d681SAndroid Build Coastguard Worker                                          ? ICI.getUnsignedPredicate()
1618*9880d681SAndroid Build Coastguard Worker                                          : ICI.getSignedPredicate();
1619*9880d681SAndroid Build Coastguard Worker           Pred = ICI.getSwappedPredicate(Pred);
1620*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(Pred, LHSI->getOperand(0),
1621*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(RHSV ^ NotSignBit));
1622*9880d681SAndroid Build Coastguard Worker         }
1623*9880d681SAndroid Build Coastguard Worker       }
1624*9880d681SAndroid Build Coastguard Worker 
1625*9880d681SAndroid Build Coastguard Worker       // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1626*9880d681SAndroid Build Coastguard Worker       //   iff -C is a power of 2
1627*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1628*9880d681SAndroid Build Coastguard Worker           XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1629*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
1630*9880d681SAndroid Build Coastguard Worker 
1631*9880d681SAndroid Build Coastguard Worker       // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1632*9880d681SAndroid Build Coastguard Worker       //   iff -C is a power of 2
1633*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1634*9880d681SAndroid Build Coastguard Worker           XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1635*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
1636*9880d681SAndroid Build Coastguard Worker     }
1637*9880d681SAndroid Build Coastguard Worker     break;
1638*9880d681SAndroid Build Coastguard Worker   case Instruction::And:         // (icmp pred (and X, AndCst), RHS)
1639*9880d681SAndroid Build Coastguard Worker     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1640*9880d681SAndroid Build Coastguard Worker         LHSI->getOperand(0)->hasOneUse()) {
1641*9880d681SAndroid Build Coastguard Worker       ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
1642*9880d681SAndroid Build Coastguard Worker 
1643*9880d681SAndroid Build Coastguard Worker       // If the LHS is an AND of a truncating cast, we can widen the
1644*9880d681SAndroid Build Coastguard Worker       // and/compare to be the input width without changing the value
1645*9880d681SAndroid Build Coastguard Worker       // produced, eliminating a cast.
1646*9880d681SAndroid Build Coastguard Worker       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1647*9880d681SAndroid Build Coastguard Worker         // We can do this transformation if either the AND constant does not
1648*9880d681SAndroid Build Coastguard Worker         // have its sign bit set or if it is an equality comparison.
1649*9880d681SAndroid Build Coastguard Worker         // Extending a relational comparison when we're checking the sign
1650*9880d681SAndroid Build Coastguard Worker         // bit would not work.
1651*9880d681SAndroid Build Coastguard Worker         if (ICI.isEquality() ||
1652*9880d681SAndroid Build Coastguard Worker             (!AndCst->isNegative() && RHSV.isNonNegative())) {
1653*9880d681SAndroid Build Coastguard Worker           Value *NewAnd =
1654*9880d681SAndroid Build Coastguard Worker             Builder->CreateAnd(Cast->getOperand(0),
1655*9880d681SAndroid Build Coastguard Worker                                ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
1656*9880d681SAndroid Build Coastguard Worker           NewAnd->takeName(LHSI);
1657*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICI.getPredicate(), NewAnd,
1658*9880d681SAndroid Build Coastguard Worker                               ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1659*9880d681SAndroid Build Coastguard Worker         }
1660*9880d681SAndroid Build Coastguard Worker       }
1661*9880d681SAndroid Build Coastguard Worker 
1662*9880d681SAndroid Build Coastguard Worker       // If the LHS is an AND of a zext, and we have an equality compare, we can
1663*9880d681SAndroid Build Coastguard Worker       // shrink the and/compare to the smaller type, eliminating the cast.
1664*9880d681SAndroid Build Coastguard Worker       if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1665*9880d681SAndroid Build Coastguard Worker         IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1666*9880d681SAndroid Build Coastguard Worker         // Make sure we don't compare the upper bits, SimplifyDemandedBits
1667*9880d681SAndroid Build Coastguard Worker         // should fold the icmp to true/false in that case.
1668*9880d681SAndroid Build Coastguard Worker         if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1669*9880d681SAndroid Build Coastguard Worker           Value *NewAnd =
1670*9880d681SAndroid Build Coastguard Worker             Builder->CreateAnd(Cast->getOperand(0),
1671*9880d681SAndroid Build Coastguard Worker                                ConstantExpr::getTrunc(AndCst, Ty));
1672*9880d681SAndroid Build Coastguard Worker           NewAnd->takeName(LHSI);
1673*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICI.getPredicate(), NewAnd,
1674*9880d681SAndroid Build Coastguard Worker                               ConstantExpr::getTrunc(RHS, Ty));
1675*9880d681SAndroid Build Coastguard Worker         }
1676*9880d681SAndroid Build Coastguard Worker       }
1677*9880d681SAndroid Build Coastguard Worker 
1678*9880d681SAndroid Build Coastguard Worker       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1679*9880d681SAndroid Build Coastguard Worker       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1680*9880d681SAndroid Build Coastguard Worker       // happens a LOT in code produced by the C front-end, for bitfield
1681*9880d681SAndroid Build Coastguard Worker       // access.
1682*9880d681SAndroid Build Coastguard Worker       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1683*9880d681SAndroid Build Coastguard Worker       if (Shift && !Shift->isShift())
1684*9880d681SAndroid Build Coastguard Worker         Shift = nullptr;
1685*9880d681SAndroid Build Coastguard Worker 
1686*9880d681SAndroid Build Coastguard Worker       ConstantInt *ShAmt;
1687*9880d681SAndroid Build Coastguard Worker       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
1688*9880d681SAndroid Build Coastguard Worker 
1689*9880d681SAndroid Build Coastguard Worker       // This seemingly simple opportunity to fold away a shift turns out to
1690*9880d681SAndroid Build Coastguard Worker       // be rather complicated. See PR17827
1691*9880d681SAndroid Build Coastguard Worker       // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
1692*9880d681SAndroid Build Coastguard Worker       if (ShAmt) {
1693*9880d681SAndroid Build Coastguard Worker         bool CanFold = false;
1694*9880d681SAndroid Build Coastguard Worker         unsigned ShiftOpcode = Shift->getOpcode();
1695*9880d681SAndroid Build Coastguard Worker         if (ShiftOpcode == Instruction::AShr) {
1696*9880d681SAndroid Build Coastguard Worker           // There may be some constraints that make this possible,
1697*9880d681SAndroid Build Coastguard Worker           // but nothing simple has been discovered yet.
1698*9880d681SAndroid Build Coastguard Worker           CanFold = false;
1699*9880d681SAndroid Build Coastguard Worker         } else if (ShiftOpcode == Instruction::Shl) {
1700*9880d681SAndroid Build Coastguard Worker           // For a left shift, we can fold if the comparison is not signed.
1701*9880d681SAndroid Build Coastguard Worker           // We can also fold a signed comparison if the mask value and
1702*9880d681SAndroid Build Coastguard Worker           // comparison value are not negative. These constraints may not be
1703*9880d681SAndroid Build Coastguard Worker           // obvious, but we can prove that they are correct using an SMT
1704*9880d681SAndroid Build Coastguard Worker           // solver.
1705*9880d681SAndroid Build Coastguard Worker           if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
1706*9880d681SAndroid Build Coastguard Worker             CanFold = true;
1707*9880d681SAndroid Build Coastguard Worker         } else if (ShiftOpcode == Instruction::LShr) {
1708*9880d681SAndroid Build Coastguard Worker           // For a logical right shift, we can fold if the comparison is not
1709*9880d681SAndroid Build Coastguard Worker           // signed. We can also fold a signed comparison if the shifted mask
1710*9880d681SAndroid Build Coastguard Worker           // value and the shifted comparison value are not negative.
1711*9880d681SAndroid Build Coastguard Worker           // These constraints may not be obvious, but we can prove that they
1712*9880d681SAndroid Build Coastguard Worker           // are correct using an SMT solver.
1713*9880d681SAndroid Build Coastguard Worker           if (!ICI.isSigned())
1714*9880d681SAndroid Build Coastguard Worker             CanFold = true;
1715*9880d681SAndroid Build Coastguard Worker           else {
1716*9880d681SAndroid Build Coastguard Worker             ConstantInt *ShiftedAndCst =
1717*9880d681SAndroid Build Coastguard Worker               cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1718*9880d681SAndroid Build Coastguard Worker             ConstantInt *ShiftedRHSCst =
1719*9880d681SAndroid Build Coastguard Worker               cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1720*9880d681SAndroid Build Coastguard Worker 
1721*9880d681SAndroid Build Coastguard Worker             if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1722*9880d681SAndroid Build Coastguard Worker               CanFold = true;
1723*9880d681SAndroid Build Coastguard Worker           }
1724*9880d681SAndroid Build Coastguard Worker         }
1725*9880d681SAndroid Build Coastguard Worker 
1726*9880d681SAndroid Build Coastguard Worker         if (CanFold) {
1727*9880d681SAndroid Build Coastguard Worker           Constant *NewCst;
1728*9880d681SAndroid Build Coastguard Worker           if (ShiftOpcode == Instruction::Shl)
1729*9880d681SAndroid Build Coastguard Worker             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1730*9880d681SAndroid Build Coastguard Worker           else
1731*9880d681SAndroid Build Coastguard Worker             NewCst = ConstantExpr::getShl(RHS, ShAmt);
1732*9880d681SAndroid Build Coastguard Worker 
1733*9880d681SAndroid Build Coastguard Worker           // Check to see if we are shifting out any of the bits being
1734*9880d681SAndroid Build Coastguard Worker           // compared.
1735*9880d681SAndroid Build Coastguard Worker           if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1736*9880d681SAndroid Build Coastguard Worker             // If we shifted bits out, the fold is not going to work out.
1737*9880d681SAndroid Build Coastguard Worker             // As a special case, check to see if this means that the
1738*9880d681SAndroid Build Coastguard Worker             // result is always true or false now.
1739*9880d681SAndroid Build Coastguard Worker             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1740*9880d681SAndroid Build Coastguard Worker               return replaceInstUsesWith(ICI, Builder->getFalse());
1741*9880d681SAndroid Build Coastguard Worker             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1742*9880d681SAndroid Build Coastguard Worker               return replaceInstUsesWith(ICI, Builder->getTrue());
1743*9880d681SAndroid Build Coastguard Worker           } else {
1744*9880d681SAndroid Build Coastguard Worker             ICI.setOperand(1, NewCst);
1745*9880d681SAndroid Build Coastguard Worker             Constant *NewAndCst;
1746*9880d681SAndroid Build Coastguard Worker             if (ShiftOpcode == Instruction::Shl)
1747*9880d681SAndroid Build Coastguard Worker               NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1748*9880d681SAndroid Build Coastguard Worker             else
1749*9880d681SAndroid Build Coastguard Worker               NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1750*9880d681SAndroid Build Coastguard Worker             LHSI->setOperand(1, NewAndCst);
1751*9880d681SAndroid Build Coastguard Worker             LHSI->setOperand(0, Shift->getOperand(0));
1752*9880d681SAndroid Build Coastguard Worker             Worklist.Add(Shift); // Shift is dead.
1753*9880d681SAndroid Build Coastguard Worker             return &ICI;
1754*9880d681SAndroid Build Coastguard Worker           }
1755*9880d681SAndroid Build Coastguard Worker         }
1756*9880d681SAndroid Build Coastguard Worker       }
1757*9880d681SAndroid Build Coastguard Worker 
1758*9880d681SAndroid Build Coastguard Worker       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1759*9880d681SAndroid Build Coastguard Worker       // preferable because it allows the C<<Y expression to be hoisted out
1760*9880d681SAndroid Build Coastguard Worker       // of a loop if Y is invariant and X is not.
1761*9880d681SAndroid Build Coastguard Worker       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1762*9880d681SAndroid Build Coastguard Worker           ICI.isEquality() && !Shift->isArithmeticShift() &&
1763*9880d681SAndroid Build Coastguard Worker           !isa<Constant>(Shift->getOperand(0))) {
1764*9880d681SAndroid Build Coastguard Worker         // Compute C << Y.
1765*9880d681SAndroid Build Coastguard Worker         Value *NS;
1766*9880d681SAndroid Build Coastguard Worker         if (Shift->getOpcode() == Instruction::LShr) {
1767*9880d681SAndroid Build Coastguard Worker           NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1768*9880d681SAndroid Build Coastguard Worker         } else {
1769*9880d681SAndroid Build Coastguard Worker           // Insert a logical shift.
1770*9880d681SAndroid Build Coastguard Worker           NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1771*9880d681SAndroid Build Coastguard Worker         }
1772*9880d681SAndroid Build Coastguard Worker 
1773*9880d681SAndroid Build Coastguard Worker         // Compute X & (C << Y).
1774*9880d681SAndroid Build Coastguard Worker         Value *NewAnd =
1775*9880d681SAndroid Build Coastguard Worker           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1776*9880d681SAndroid Build Coastguard Worker 
1777*9880d681SAndroid Build Coastguard Worker         ICI.setOperand(0, NewAnd);
1778*9880d681SAndroid Build Coastguard Worker         return &ICI;
1779*9880d681SAndroid Build Coastguard Worker       }
1780*9880d681SAndroid Build Coastguard Worker 
1781*9880d681SAndroid Build Coastguard Worker       // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1782*9880d681SAndroid Build Coastguard Worker       //    (icmp pred (and X, (or (shl 1, Y), 1), 0))
1783*9880d681SAndroid Build Coastguard Worker       //
1784*9880d681SAndroid Build Coastguard Worker       // iff pred isn't signed
1785*9880d681SAndroid Build Coastguard Worker       {
1786*9880d681SAndroid Build Coastguard Worker         Value *X, *Y, *LShr;
1787*9880d681SAndroid Build Coastguard Worker         if (!ICI.isSigned() && RHSV == 0) {
1788*9880d681SAndroid Build Coastguard Worker           if (match(LHSI->getOperand(1), m_One())) {
1789*9880d681SAndroid Build Coastguard Worker             Constant *One = cast<Constant>(LHSI->getOperand(1));
1790*9880d681SAndroid Build Coastguard Worker             Value *Or = LHSI->getOperand(0);
1791*9880d681SAndroid Build Coastguard Worker             if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1792*9880d681SAndroid Build Coastguard Worker                 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1793*9880d681SAndroid Build Coastguard Worker               unsigned UsesRemoved = 0;
1794*9880d681SAndroid Build Coastguard Worker               if (LHSI->hasOneUse())
1795*9880d681SAndroid Build Coastguard Worker                 ++UsesRemoved;
1796*9880d681SAndroid Build Coastguard Worker               if (Or->hasOneUse())
1797*9880d681SAndroid Build Coastguard Worker                 ++UsesRemoved;
1798*9880d681SAndroid Build Coastguard Worker               if (LShr->hasOneUse())
1799*9880d681SAndroid Build Coastguard Worker                 ++UsesRemoved;
1800*9880d681SAndroid Build Coastguard Worker               Value *NewOr = nullptr;
1801*9880d681SAndroid Build Coastguard Worker               // Compute X & ((1 << Y) | 1)
1802*9880d681SAndroid Build Coastguard Worker               if (auto *C = dyn_cast<Constant>(Y)) {
1803*9880d681SAndroid Build Coastguard Worker                 if (UsesRemoved >= 1)
1804*9880d681SAndroid Build Coastguard Worker                   NewOr =
1805*9880d681SAndroid Build Coastguard Worker                       ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1806*9880d681SAndroid Build Coastguard Worker               } else {
1807*9880d681SAndroid Build Coastguard Worker                 if (UsesRemoved >= 3)
1808*9880d681SAndroid Build Coastguard Worker                   NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1809*9880d681SAndroid Build Coastguard Worker                                                                LShr->getName(),
1810*9880d681SAndroid Build Coastguard Worker                                                                /*HasNUW=*/true),
1811*9880d681SAndroid Build Coastguard Worker                                             One, Or->getName());
1812*9880d681SAndroid Build Coastguard Worker               }
1813*9880d681SAndroid Build Coastguard Worker               if (NewOr) {
1814*9880d681SAndroid Build Coastguard Worker                 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1815*9880d681SAndroid Build Coastguard Worker                 ICI.setOperand(0, NewAnd);
1816*9880d681SAndroid Build Coastguard Worker                 return &ICI;
1817*9880d681SAndroid Build Coastguard Worker               }
1818*9880d681SAndroid Build Coastguard Worker             }
1819*9880d681SAndroid Build Coastguard Worker           }
1820*9880d681SAndroid Build Coastguard Worker         }
1821*9880d681SAndroid Build Coastguard Worker       }
1822*9880d681SAndroid Build Coastguard Worker 
1823*9880d681SAndroid Build Coastguard Worker       // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1824*9880d681SAndroid Build Coastguard Worker       // bit set in (X & AndCst) will produce a result greater than RHSV.
1825*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1826*9880d681SAndroid Build Coastguard Worker         unsigned NTZ = AndCst->getValue().countTrailingZeros();
1827*9880d681SAndroid Build Coastguard Worker         if ((NTZ < AndCst->getBitWidth()) &&
1828*9880d681SAndroid Build Coastguard Worker             APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
1829*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1830*9880d681SAndroid Build Coastguard Worker                               Constant::getNullValue(RHS->getType()));
1831*9880d681SAndroid Build Coastguard Worker       }
1832*9880d681SAndroid Build Coastguard Worker     }
1833*9880d681SAndroid Build Coastguard Worker 
1834*9880d681SAndroid Build Coastguard Worker     // Try to optimize things like "A[i]&42 == 0" to index computations.
1835*9880d681SAndroid Build Coastguard Worker     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1836*9880d681SAndroid Build Coastguard Worker       if (GetElementPtrInst *GEP =
1837*9880d681SAndroid Build Coastguard Worker           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1838*9880d681SAndroid Build Coastguard Worker         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1839*9880d681SAndroid Build Coastguard Worker           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1840*9880d681SAndroid Build Coastguard Worker               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1841*9880d681SAndroid Build Coastguard Worker             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1842*9880d681SAndroid Build Coastguard Worker             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1843*9880d681SAndroid Build Coastguard Worker               return Res;
1844*9880d681SAndroid Build Coastguard Worker           }
1845*9880d681SAndroid Build Coastguard Worker     }
1846*9880d681SAndroid Build Coastguard Worker 
1847*9880d681SAndroid Build Coastguard Worker     // X & -C == -C -> X >  u ~C
1848*9880d681SAndroid Build Coastguard Worker     // X & -C != -C -> X <= u ~C
1849*9880d681SAndroid Build Coastguard Worker     //   iff C is a power of 2
1850*9880d681SAndroid Build Coastguard Worker     if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1851*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(
1852*9880d681SAndroid Build Coastguard Worker           ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1853*9880d681SAndroid Build Coastguard Worker                                                   : ICmpInst::ICMP_ULE,
1854*9880d681SAndroid Build Coastguard Worker           LHSI->getOperand(0), SubOne(RHS));
1855*9880d681SAndroid Build Coastguard Worker 
1856*9880d681SAndroid Build Coastguard Worker     // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1857*9880d681SAndroid Build Coastguard Worker     //   iff C is a power of 2
1858*9880d681SAndroid Build Coastguard Worker     if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1859*9880d681SAndroid Build Coastguard Worker       if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1860*9880d681SAndroid Build Coastguard Worker         const APInt &AI = CI->getValue();
1861*9880d681SAndroid Build Coastguard Worker         int32_t ExactLogBase2 = AI.exactLogBase2();
1862*9880d681SAndroid Build Coastguard Worker         if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1863*9880d681SAndroid Build Coastguard Worker           Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1864*9880d681SAndroid Build Coastguard Worker           Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1865*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1866*9880d681SAndroid Build Coastguard Worker                                   ? ICmpInst::ICMP_SGE
1867*9880d681SAndroid Build Coastguard Worker                                   : ICmpInst::ICMP_SLT,
1868*9880d681SAndroid Build Coastguard Worker                               Trunc, Constant::getNullValue(NTy));
1869*9880d681SAndroid Build Coastguard Worker         }
1870*9880d681SAndroid Build Coastguard Worker       }
1871*9880d681SAndroid Build Coastguard Worker     }
1872*9880d681SAndroid Build Coastguard Worker     break;
1873*9880d681SAndroid Build Coastguard Worker 
1874*9880d681SAndroid Build Coastguard Worker   case Instruction::Or: {
1875*9880d681SAndroid Build Coastguard Worker     if (RHS->isOne()) {
1876*9880d681SAndroid Build Coastguard Worker       // icmp slt signum(V) 1 --> icmp slt V, 1
1877*9880d681SAndroid Build Coastguard Worker       Value *V = nullptr;
1878*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1879*9880d681SAndroid Build Coastguard Worker           match(LHSI, m_Signum(m_Value(V))))
1880*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_SLT, V,
1881*9880d681SAndroid Build Coastguard Worker                             ConstantInt::get(V->getType(), 1));
1882*9880d681SAndroid Build Coastguard Worker     }
1883*9880d681SAndroid Build Coastguard Worker 
1884*9880d681SAndroid Build Coastguard Worker     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1885*9880d681SAndroid Build Coastguard Worker       break;
1886*9880d681SAndroid Build Coastguard Worker     Value *P, *Q;
1887*9880d681SAndroid Build Coastguard Worker     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1888*9880d681SAndroid Build Coastguard Worker       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1889*9880d681SAndroid Build Coastguard Worker       // -> and (icmp eq P, null), (icmp eq Q, null).
1890*9880d681SAndroid Build Coastguard Worker       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1891*9880d681SAndroid Build Coastguard Worker                                         Constant::getNullValue(P->getType()));
1892*9880d681SAndroid Build Coastguard Worker       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1893*9880d681SAndroid Build Coastguard Worker                                         Constant::getNullValue(Q->getType()));
1894*9880d681SAndroid Build Coastguard Worker       Instruction *Op;
1895*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1896*9880d681SAndroid Build Coastguard Worker         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1897*9880d681SAndroid Build Coastguard Worker       else
1898*9880d681SAndroid Build Coastguard Worker         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1899*9880d681SAndroid Build Coastguard Worker       return Op;
1900*9880d681SAndroid Build Coastguard Worker     }
1901*9880d681SAndroid Build Coastguard Worker     break;
1902*9880d681SAndroid Build Coastguard Worker   }
1903*9880d681SAndroid Build Coastguard Worker 
1904*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul: {       // (icmp pred (mul X, Val), CI)
1905*9880d681SAndroid Build Coastguard Worker     ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1906*9880d681SAndroid Build Coastguard Worker     if (!Val) break;
1907*9880d681SAndroid Build Coastguard Worker 
1908*9880d681SAndroid Build Coastguard Worker     // If this is a signed comparison to 0 and the mul is sign preserving,
1909*9880d681SAndroid Build Coastguard Worker     // use the mul LHS operand instead.
1910*9880d681SAndroid Build Coastguard Worker     ICmpInst::Predicate pred = ICI.getPredicate();
1911*9880d681SAndroid Build Coastguard Worker     if (isSignTest(pred, RHS) && !Val->isZero() &&
1912*9880d681SAndroid Build Coastguard Worker         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1913*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Val->isNegative() ?
1914*9880d681SAndroid Build Coastguard Worker                           ICmpInst::getSwappedPredicate(pred) : pred,
1915*9880d681SAndroid Build Coastguard Worker                           LHSI->getOperand(0),
1916*9880d681SAndroid Build Coastguard Worker                           Constant::getNullValue(RHS->getType()));
1917*9880d681SAndroid Build Coastguard Worker 
1918*9880d681SAndroid Build Coastguard Worker     break;
1919*9880d681SAndroid Build Coastguard Worker   }
1920*9880d681SAndroid Build Coastguard Worker 
1921*9880d681SAndroid Build Coastguard Worker   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1922*9880d681SAndroid Build Coastguard Worker     uint32_t TypeBits = RHSV.getBitWidth();
1923*9880d681SAndroid Build Coastguard Worker     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1924*9880d681SAndroid Build Coastguard Worker     if (!ShAmt) {
1925*9880d681SAndroid Build Coastguard Worker       Value *X;
1926*9880d681SAndroid Build Coastguard Worker       // (1 << X) pred P2 -> X pred Log2(P2)
1927*9880d681SAndroid Build Coastguard Worker       if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1928*9880d681SAndroid Build Coastguard Worker         bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1929*9880d681SAndroid Build Coastguard Worker         ICmpInst::Predicate Pred = ICI.getPredicate();
1930*9880d681SAndroid Build Coastguard Worker         if (ICI.isUnsigned()) {
1931*9880d681SAndroid Build Coastguard Worker           if (!RHSVIsPowerOf2) {
1932*9880d681SAndroid Build Coastguard Worker             // (1 << X) <  30 -> X <= 4
1933*9880d681SAndroid Build Coastguard Worker             // (1 << X) <= 30 -> X <= 4
1934*9880d681SAndroid Build Coastguard Worker             // (1 << X) >= 30 -> X >  4
1935*9880d681SAndroid Build Coastguard Worker             // (1 << X) >  30 -> X >  4
1936*9880d681SAndroid Build Coastguard Worker             if (Pred == ICmpInst::ICMP_ULT)
1937*9880d681SAndroid Build Coastguard Worker               Pred = ICmpInst::ICMP_ULE;
1938*9880d681SAndroid Build Coastguard Worker             else if (Pred == ICmpInst::ICMP_UGE)
1939*9880d681SAndroid Build Coastguard Worker               Pred = ICmpInst::ICMP_UGT;
1940*9880d681SAndroid Build Coastguard Worker           }
1941*9880d681SAndroid Build Coastguard Worker           unsigned RHSLog2 = RHSV.logBase2();
1942*9880d681SAndroid Build Coastguard Worker 
1943*9880d681SAndroid Build Coastguard Worker           // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1944*9880d681SAndroid Build Coastguard Worker           // (1 << X) <  2147483648 -> X <  31 -> X != 31
1945*9880d681SAndroid Build Coastguard Worker           if (RHSLog2 == TypeBits-1) {
1946*9880d681SAndroid Build Coastguard Worker             if (Pred == ICmpInst::ICMP_UGE)
1947*9880d681SAndroid Build Coastguard Worker               Pred = ICmpInst::ICMP_EQ;
1948*9880d681SAndroid Build Coastguard Worker             else if (Pred == ICmpInst::ICMP_ULT)
1949*9880d681SAndroid Build Coastguard Worker               Pred = ICmpInst::ICMP_NE;
1950*9880d681SAndroid Build Coastguard Worker           }
1951*9880d681SAndroid Build Coastguard Worker 
1952*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(Pred, X,
1953*9880d681SAndroid Build Coastguard Worker                               ConstantInt::get(RHS->getType(), RHSLog2));
1954*9880d681SAndroid Build Coastguard Worker         } else if (ICI.isSigned()) {
1955*9880d681SAndroid Build Coastguard Worker           if (RHSV.isAllOnesValue()) {
1956*9880d681SAndroid Build Coastguard Worker             // (1 << X) <= -1 -> X == 31
1957*9880d681SAndroid Build Coastguard Worker             if (Pred == ICmpInst::ICMP_SLE)
1958*9880d681SAndroid Build Coastguard Worker               return new ICmpInst(ICmpInst::ICMP_EQ, X,
1959*9880d681SAndroid Build Coastguard Worker                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1960*9880d681SAndroid Build Coastguard Worker 
1961*9880d681SAndroid Build Coastguard Worker             // (1 << X) >  -1 -> X != 31
1962*9880d681SAndroid Build Coastguard Worker             if (Pred == ICmpInst::ICMP_SGT)
1963*9880d681SAndroid Build Coastguard Worker               return new ICmpInst(ICmpInst::ICMP_NE, X,
1964*9880d681SAndroid Build Coastguard Worker                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1965*9880d681SAndroid Build Coastguard Worker           } else if (!RHSV) {
1966*9880d681SAndroid Build Coastguard Worker             // (1 << X) <  0 -> X == 31
1967*9880d681SAndroid Build Coastguard Worker             // (1 << X) <= 0 -> X == 31
1968*9880d681SAndroid Build Coastguard Worker             if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1969*9880d681SAndroid Build Coastguard Worker               return new ICmpInst(ICmpInst::ICMP_EQ, X,
1970*9880d681SAndroid Build Coastguard Worker                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1971*9880d681SAndroid Build Coastguard Worker 
1972*9880d681SAndroid Build Coastguard Worker             // (1 << X) >= 0 -> X != 31
1973*9880d681SAndroid Build Coastguard Worker             // (1 << X) >  0 -> X != 31
1974*9880d681SAndroid Build Coastguard Worker             if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1975*9880d681SAndroid Build Coastguard Worker               return new ICmpInst(ICmpInst::ICMP_NE, X,
1976*9880d681SAndroid Build Coastguard Worker                                   ConstantInt::get(RHS->getType(), TypeBits-1));
1977*9880d681SAndroid Build Coastguard Worker           }
1978*9880d681SAndroid Build Coastguard Worker         } else if (ICI.isEquality()) {
1979*9880d681SAndroid Build Coastguard Worker           if (RHSVIsPowerOf2)
1980*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(
1981*9880d681SAndroid Build Coastguard Worker                 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1982*9880d681SAndroid Build Coastguard Worker         }
1983*9880d681SAndroid Build Coastguard Worker       }
1984*9880d681SAndroid Build Coastguard Worker       break;
1985*9880d681SAndroid Build Coastguard Worker     }
1986*9880d681SAndroid Build Coastguard Worker 
1987*9880d681SAndroid Build Coastguard Worker     // Check that the shift amount is in range.  If not, don't perform
1988*9880d681SAndroid Build Coastguard Worker     // undefined shifts.  When the shift is visited it will be
1989*9880d681SAndroid Build Coastguard Worker     // simplified.
1990*9880d681SAndroid Build Coastguard Worker     if (ShAmt->uge(TypeBits))
1991*9880d681SAndroid Build Coastguard Worker       break;
1992*9880d681SAndroid Build Coastguard Worker 
1993*9880d681SAndroid Build Coastguard Worker     if (ICI.isEquality()) {
1994*9880d681SAndroid Build Coastguard Worker       // If we are comparing against bits always shifted out, the
1995*9880d681SAndroid Build Coastguard Worker       // comparison cannot succeed.
1996*9880d681SAndroid Build Coastguard Worker       Constant *Comp =
1997*9880d681SAndroid Build Coastguard Worker         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1998*9880d681SAndroid Build Coastguard Worker                                                                  ShAmt);
1999*9880d681SAndroid Build Coastguard Worker       if (Comp != RHS) {// Comparing against a bit that we know is zero.
2000*9880d681SAndroid Build Coastguard Worker         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
2001*9880d681SAndroid Build Coastguard Worker         Constant *Cst = Builder->getInt1(IsICMP_NE);
2002*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(ICI, Cst);
2003*9880d681SAndroid Build Coastguard Worker       }
2004*9880d681SAndroid Build Coastguard Worker 
2005*9880d681SAndroid Build Coastguard Worker       // If the shift is NUW, then it is just shifting out zeros, no need for an
2006*9880d681SAndroid Build Coastguard Worker       // AND.
2007*9880d681SAndroid Build Coastguard Worker       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2008*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2009*9880d681SAndroid Build Coastguard Worker                             ConstantExpr::getLShr(RHS, ShAmt));
2010*9880d681SAndroid Build Coastguard Worker 
2011*9880d681SAndroid Build Coastguard Worker       // If the shift is NSW and we compare to 0, then it is just shifting out
2012*9880d681SAndroid Build Coastguard Worker       // sign bits, no need for an AND either.
2013*9880d681SAndroid Build Coastguard Worker       if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
2014*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2015*9880d681SAndroid Build Coastguard Worker                             ConstantExpr::getLShr(RHS, ShAmt));
2016*9880d681SAndroid Build Coastguard Worker 
2017*9880d681SAndroid Build Coastguard Worker       if (LHSI->hasOneUse()) {
2018*9880d681SAndroid Build Coastguard Worker         // Otherwise strength reduce the shift into an and.
2019*9880d681SAndroid Build Coastguard Worker         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
2020*9880d681SAndroid Build Coastguard Worker         Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
2021*9880d681SAndroid Build Coastguard Worker                                                           TypeBits - ShAmtVal));
2022*9880d681SAndroid Build Coastguard Worker 
2023*9880d681SAndroid Build Coastguard Worker         Value *And =
2024*9880d681SAndroid Build Coastguard Worker           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
2025*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICI.getPredicate(), And,
2026*9880d681SAndroid Build Coastguard Worker                             ConstantExpr::getLShr(RHS, ShAmt));
2027*9880d681SAndroid Build Coastguard Worker       }
2028*9880d681SAndroid Build Coastguard Worker     }
2029*9880d681SAndroid Build Coastguard Worker 
2030*9880d681SAndroid Build Coastguard Worker     // If this is a signed comparison to 0 and the shift is sign preserving,
2031*9880d681SAndroid Build Coastguard Worker     // use the shift LHS operand instead.
2032*9880d681SAndroid Build Coastguard Worker     ICmpInst::Predicate pred = ICI.getPredicate();
2033*9880d681SAndroid Build Coastguard Worker     if (isSignTest(pred, RHS) &&
2034*9880d681SAndroid Build Coastguard Worker         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
2035*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(pred,
2036*9880d681SAndroid Build Coastguard Worker                           LHSI->getOperand(0),
2037*9880d681SAndroid Build Coastguard Worker                           Constant::getNullValue(RHS->getType()));
2038*9880d681SAndroid Build Coastguard Worker 
2039*9880d681SAndroid Build Coastguard Worker     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2040*9880d681SAndroid Build Coastguard Worker     bool TrueIfSigned = false;
2041*9880d681SAndroid Build Coastguard Worker     if (LHSI->hasOneUse() &&
2042*9880d681SAndroid Build Coastguard Worker         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2043*9880d681SAndroid Build Coastguard Worker       // (X << 31) <s 0  --> (X&1) != 0
2044*9880d681SAndroid Build Coastguard Worker       Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
2045*9880d681SAndroid Build Coastguard Worker                                         APInt::getOneBitSet(TypeBits,
2046*9880d681SAndroid Build Coastguard Worker                                             TypeBits-ShAmt->getZExtValue()-1));
2047*9880d681SAndroid Build Coastguard Worker       Value *And =
2048*9880d681SAndroid Build Coastguard Worker         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
2049*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2050*9880d681SAndroid Build Coastguard Worker                           And, Constant::getNullValue(And->getType()));
2051*9880d681SAndroid Build Coastguard Worker     }
2052*9880d681SAndroid Build Coastguard Worker 
2053*9880d681SAndroid Build Coastguard Worker     // Transform (icmp pred iM (shl iM %v, N), CI)
2054*9880d681SAndroid Build Coastguard Worker     // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2055*9880d681SAndroid Build Coastguard Worker     // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
2056*9880d681SAndroid Build Coastguard Worker     // This enables to get rid of the shift in favor of a trunc which can be
2057*9880d681SAndroid Build Coastguard Worker     // free on the target. It has the additional benefit of comparing to a
2058*9880d681SAndroid Build Coastguard Worker     // smaller constant, which will be target friendly.
2059*9880d681SAndroid Build Coastguard Worker     unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
2060*9880d681SAndroid Build Coastguard Worker     if (LHSI->hasOneUse() &&
2061*9880d681SAndroid Build Coastguard Worker         Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
2062*9880d681SAndroid Build Coastguard Worker       Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2063*9880d681SAndroid Build Coastguard Worker       Constant *NCI = ConstantExpr::getTrunc(
2064*9880d681SAndroid Build Coastguard Worker                         ConstantExpr::getAShr(RHS,
2065*9880d681SAndroid Build Coastguard Worker                           ConstantInt::get(RHS->getType(), Amt)),
2066*9880d681SAndroid Build Coastguard Worker                         NTy);
2067*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICI.getPredicate(),
2068*9880d681SAndroid Build Coastguard Worker                           Builder->CreateTrunc(LHSI->getOperand(0), NTy),
2069*9880d681SAndroid Build Coastguard Worker                           NCI);
2070*9880d681SAndroid Build Coastguard Worker     }
2071*9880d681SAndroid Build Coastguard Worker 
2072*9880d681SAndroid Build Coastguard Worker     break;
2073*9880d681SAndroid Build Coastguard Worker   }
2074*9880d681SAndroid Build Coastguard Worker 
2075*9880d681SAndroid Build Coastguard Worker   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
2076*9880d681SAndroid Build Coastguard Worker   case Instruction::AShr: {
2077*9880d681SAndroid Build Coastguard Worker     // Handle equality comparisons of shift-by-constant.
2078*9880d681SAndroid Build Coastguard Worker     BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2079*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2080*9880d681SAndroid Build Coastguard Worker       if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
2081*9880d681SAndroid Build Coastguard Worker         return Res;
2082*9880d681SAndroid Build Coastguard Worker     }
2083*9880d681SAndroid Build Coastguard Worker 
2084*9880d681SAndroid Build Coastguard Worker     // Handle exact shr's.
2085*9880d681SAndroid Build Coastguard Worker     if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2086*9880d681SAndroid Build Coastguard Worker       if (RHSV.isMinValue())
2087*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2088*9880d681SAndroid Build Coastguard Worker     }
2089*9880d681SAndroid Build Coastguard Worker     break;
2090*9880d681SAndroid Build Coastguard Worker   }
2091*9880d681SAndroid Build Coastguard Worker 
2092*9880d681SAndroid Build Coastguard Worker   case Instruction::UDiv:
2093*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *DivLHS = dyn_cast<ConstantInt>(LHSI->getOperand(0))) {
2094*9880d681SAndroid Build Coastguard Worker       Value *X = LHSI->getOperand(1);
2095*9880d681SAndroid Build Coastguard Worker       const APInt &C1 = RHS->getValue();
2096*9880d681SAndroid Build Coastguard Worker       const APInt &C2 = DivLHS->getValue();
2097*9880d681SAndroid Build Coastguard Worker       assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2098*9880d681SAndroid Build Coastguard Worker       // (icmp ugt (udiv C2, X), C1) -> (icmp ule X, C2/(C1+1))
2099*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
2100*9880d681SAndroid Build Coastguard Worker         assert(!C1.isMaxValue() &&
2101*9880d681SAndroid Build Coastguard Worker                "icmp ugt X, UINT_MAX should have been simplified already.");
2102*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_ULE, X,
2103*9880d681SAndroid Build Coastguard Worker                             ConstantInt::get(X->getType(), C2.udiv(C1 + 1)));
2104*9880d681SAndroid Build Coastguard Worker       }
2105*9880d681SAndroid Build Coastguard Worker       // (icmp ult (udiv C2, X), C1) -> (icmp ugt X, C2/C1)
2106*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_ULT) {
2107*9880d681SAndroid Build Coastguard Worker         assert(C1 != 0 && "icmp ult X, 0 should have been simplified already.");
2108*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_UGT, X,
2109*9880d681SAndroid Build Coastguard Worker                             ConstantInt::get(X->getType(), C2.udiv(C1)));
2110*9880d681SAndroid Build Coastguard Worker       }
2111*9880d681SAndroid Build Coastguard Worker     }
2112*9880d681SAndroid Build Coastguard Worker   // fall-through
2113*9880d681SAndroid Build Coastguard Worker   case Instruction::SDiv:
2114*9880d681SAndroid Build Coastguard Worker     // Fold: icmp pred ([us]div X, C1), C2 -> range test
2115*9880d681SAndroid Build Coastguard Worker     // Fold this div into the comparison, producing a range check.
2116*9880d681SAndroid Build Coastguard Worker     // Determine, based on the divide type, what the range is being
2117*9880d681SAndroid Build Coastguard Worker     // checked.  If there is an overflow on the low or high side, remember
2118*9880d681SAndroid Build Coastguard Worker     // it, otherwise compute the range [low, hi) bounding the new value.
2119*9880d681SAndroid Build Coastguard Worker     // See: InsertRangeTest above for the kinds of replacements possible.
2120*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
2121*9880d681SAndroid Build Coastguard Worker       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
2122*9880d681SAndroid Build Coastguard Worker                                           DivRHS))
2123*9880d681SAndroid Build Coastguard Worker         return R;
2124*9880d681SAndroid Build Coastguard Worker     break;
2125*9880d681SAndroid Build Coastguard Worker 
2126*9880d681SAndroid Build Coastguard Worker   case Instruction::Sub: {
2127*9880d681SAndroid Build Coastguard Worker     ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
2128*9880d681SAndroid Build Coastguard Worker     if (!LHSC) break;
2129*9880d681SAndroid Build Coastguard Worker     const APInt &LHSV = LHSC->getValue();
2130*9880d681SAndroid Build Coastguard Worker 
2131*9880d681SAndroid Build Coastguard Worker     // C1-X <u C2 -> (X|(C2-1)) == C1
2132*9880d681SAndroid Build Coastguard Worker     //   iff C1 & (C2-1) == C2-1
2133*9880d681SAndroid Build Coastguard Worker     //       C2 is a power of 2
2134*9880d681SAndroid Build Coastguard Worker     if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
2135*9880d681SAndroid Build Coastguard Worker         RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
2136*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmpInst::ICMP_EQ,
2137*9880d681SAndroid Build Coastguard Worker                           Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
2138*9880d681SAndroid Build Coastguard Worker                           LHSC);
2139*9880d681SAndroid Build Coastguard Worker 
2140*9880d681SAndroid Build Coastguard Worker     // C1-X >u C2 -> (X|C2) != C1
2141*9880d681SAndroid Build Coastguard Worker     //   iff C1 & C2 == C2
2142*9880d681SAndroid Build Coastguard Worker     //       C2+1 is a power of 2
2143*9880d681SAndroid Build Coastguard Worker     if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2144*9880d681SAndroid Build Coastguard Worker         (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
2145*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmpInst::ICMP_NE,
2146*9880d681SAndroid Build Coastguard Worker                           Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
2147*9880d681SAndroid Build Coastguard Worker     break;
2148*9880d681SAndroid Build Coastguard Worker   }
2149*9880d681SAndroid Build Coastguard Worker 
2150*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
2151*9880d681SAndroid Build Coastguard Worker     // Fold: icmp pred (add X, C1), C2
2152*9880d681SAndroid Build Coastguard Worker     if (!ICI.isEquality()) {
2153*9880d681SAndroid Build Coastguard Worker       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
2154*9880d681SAndroid Build Coastguard Worker       if (!LHSC) break;
2155*9880d681SAndroid Build Coastguard Worker       const APInt &LHSV = LHSC->getValue();
2156*9880d681SAndroid Build Coastguard Worker 
2157*9880d681SAndroid Build Coastguard Worker       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
2158*9880d681SAndroid Build Coastguard Worker                             .subtract(LHSV);
2159*9880d681SAndroid Build Coastguard Worker 
2160*9880d681SAndroid Build Coastguard Worker       if (ICI.isSigned()) {
2161*9880d681SAndroid Build Coastguard Worker         if (CR.getLower().isSignBit()) {
2162*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
2163*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CR.getUpper()));
2164*9880d681SAndroid Build Coastguard Worker         } else if (CR.getUpper().isSignBit()) {
2165*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
2166*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CR.getLower()));
2167*9880d681SAndroid Build Coastguard Worker         }
2168*9880d681SAndroid Build Coastguard Worker       } else {
2169*9880d681SAndroid Build Coastguard Worker         if (CR.getLower().isMinValue()) {
2170*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
2171*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CR.getUpper()));
2172*9880d681SAndroid Build Coastguard Worker         } else if (CR.getUpper().isMinValue()) {
2173*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
2174*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CR.getLower()));
2175*9880d681SAndroid Build Coastguard Worker         }
2176*9880d681SAndroid Build Coastguard Worker       }
2177*9880d681SAndroid Build Coastguard Worker 
2178*9880d681SAndroid Build Coastguard Worker       // X-C1 <u C2 -> (X & -C2) == C1
2179*9880d681SAndroid Build Coastguard Worker       //   iff C1 & (C2-1) == 0
2180*9880d681SAndroid Build Coastguard Worker       //       C2 is a power of 2
2181*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
2182*9880d681SAndroid Build Coastguard Worker           RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
2183*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_EQ,
2184*9880d681SAndroid Build Coastguard Worker                             Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
2185*9880d681SAndroid Build Coastguard Worker                             ConstantExpr::getNeg(LHSC));
2186*9880d681SAndroid Build Coastguard Worker 
2187*9880d681SAndroid Build Coastguard Worker       // X-C1 >u C2 -> (X & ~C2) != C1
2188*9880d681SAndroid Build Coastguard Worker       //   iff C1 & C2 == 0
2189*9880d681SAndroid Build Coastguard Worker       //       C2+1 is a power of 2
2190*9880d681SAndroid Build Coastguard Worker       if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2191*9880d681SAndroid Build Coastguard Worker           (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
2192*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_NE,
2193*9880d681SAndroid Build Coastguard Worker                             Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
2194*9880d681SAndroid Build Coastguard Worker                             ConstantExpr::getNeg(LHSC));
2195*9880d681SAndroid Build Coastguard Worker     }
2196*9880d681SAndroid Build Coastguard Worker     break;
2197*9880d681SAndroid Build Coastguard Worker   }
2198*9880d681SAndroid Build Coastguard Worker 
2199*9880d681SAndroid Build Coastguard Worker   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
2200*9880d681SAndroid Build Coastguard Worker   if (ICI.isEquality()) {
2201*9880d681SAndroid Build Coastguard Worker     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
2202*9880d681SAndroid Build Coastguard Worker 
2203*9880d681SAndroid Build Coastguard Worker     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
2204*9880d681SAndroid Build Coastguard Worker     // the second operand is a constant, simplify a bit.
2205*9880d681SAndroid Build Coastguard Worker     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
2206*9880d681SAndroid Build Coastguard Worker       switch (BO->getOpcode()) {
2207*9880d681SAndroid Build Coastguard Worker       case Instruction::SRem:
2208*9880d681SAndroid Build Coastguard Worker         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2209*9880d681SAndroid Build Coastguard Worker         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
2210*9880d681SAndroid Build Coastguard Worker           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
2211*9880d681SAndroid Build Coastguard Worker           if (V.sgt(1) && V.isPowerOf2()) {
2212*9880d681SAndroid Build Coastguard Worker             Value *NewRem =
2213*9880d681SAndroid Build Coastguard Worker               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
2214*9880d681SAndroid Build Coastguard Worker                                   BO->getName());
2215*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), NewRem,
2216*9880d681SAndroid Build Coastguard Worker                                 Constant::getNullValue(BO->getType()));
2217*9880d681SAndroid Build Coastguard Worker           }
2218*9880d681SAndroid Build Coastguard Worker         }
2219*9880d681SAndroid Build Coastguard Worker         break;
2220*9880d681SAndroid Build Coastguard Worker       case Instruction::Add:
2221*9880d681SAndroid Build Coastguard Worker         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2222*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2223*9880d681SAndroid Build Coastguard Worker           if (BO->hasOneUse())
2224*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2225*9880d681SAndroid Build Coastguard Worker                                 ConstantExpr::getSub(RHS, BOp1C));
2226*9880d681SAndroid Build Coastguard Worker         } else if (RHSV == 0) {
2227*9880d681SAndroid Build Coastguard Worker           // Replace ((add A, B) != 0) with (A != -B) if A or B is
2228*9880d681SAndroid Build Coastguard Worker           // efficiently invertible, or if the add has just this one use.
2229*9880d681SAndroid Build Coastguard Worker           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2230*9880d681SAndroid Build Coastguard Worker 
2231*9880d681SAndroid Build Coastguard Worker           if (Value *NegVal = dyn_castNegVal(BOp1))
2232*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
2233*9880d681SAndroid Build Coastguard Worker           if (Value *NegVal = dyn_castNegVal(BOp0))
2234*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
2235*9880d681SAndroid Build Coastguard Worker           if (BO->hasOneUse()) {
2236*9880d681SAndroid Build Coastguard Worker             Value *Neg = Builder->CreateNeg(BOp1);
2237*9880d681SAndroid Build Coastguard Worker             Neg->takeName(BO);
2238*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2239*9880d681SAndroid Build Coastguard Worker           }
2240*9880d681SAndroid Build Coastguard Worker         }
2241*9880d681SAndroid Build Coastguard Worker         break;
2242*9880d681SAndroid Build Coastguard Worker       case Instruction::Xor:
2243*9880d681SAndroid Build Coastguard Worker         if (BO->hasOneUse()) {
2244*9880d681SAndroid Build Coastguard Worker           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2245*9880d681SAndroid Build Coastguard Worker             // For the xor case, we can xor two constants together, eliminating
2246*9880d681SAndroid Build Coastguard Worker             // the explicit xor.
2247*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2248*9880d681SAndroid Build Coastguard Worker                 ConstantExpr::getXor(RHS, BOC));
2249*9880d681SAndroid Build Coastguard Worker           } else if (RHSV == 0) {
2250*9880d681SAndroid Build Coastguard Worker             // Replace ((xor A, B) != 0) with (A != B)
2251*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2252*9880d681SAndroid Build Coastguard Worker                 BO->getOperand(1));
2253*9880d681SAndroid Build Coastguard Worker           }
2254*9880d681SAndroid Build Coastguard Worker         }
2255*9880d681SAndroid Build Coastguard Worker         break;
2256*9880d681SAndroid Build Coastguard Worker       case Instruction::Sub:
2257*9880d681SAndroid Build Coastguard Worker         if (BO->hasOneUse()) {
2258*9880d681SAndroid Build Coastguard Worker           if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
2259*9880d681SAndroid Build Coastguard Worker             // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
2260*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
2261*9880d681SAndroid Build Coastguard Worker                 ConstantExpr::getSub(BOp0C, RHS));
2262*9880d681SAndroid Build Coastguard Worker           } else if (RHSV == 0) {
2263*9880d681SAndroid Build Coastguard Worker             // Replace ((sub A, B) != 0) with (A != B)
2264*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2265*9880d681SAndroid Build Coastguard Worker                 BO->getOperand(1));
2266*9880d681SAndroid Build Coastguard Worker           }
2267*9880d681SAndroid Build Coastguard Worker         }
2268*9880d681SAndroid Build Coastguard Worker         break;
2269*9880d681SAndroid Build Coastguard Worker       case Instruction::Or:
2270*9880d681SAndroid Build Coastguard Worker         // If bits are being or'd in that are not present in the constant we
2271*9880d681SAndroid Build Coastguard Worker         // are comparing against, then the comparison could never succeed!
2272*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2273*9880d681SAndroid Build Coastguard Worker           Constant *NotCI = ConstantExpr::getNot(RHS);
2274*9880d681SAndroid Build Coastguard Worker           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2275*9880d681SAndroid Build Coastguard Worker             return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
2276*9880d681SAndroid Build Coastguard Worker 
2277*9880d681SAndroid Build Coastguard Worker           // Comparing if all bits outside of a constant mask are set?
2278*9880d681SAndroid Build Coastguard Worker           // Replace (X | C) == -1 with (X & ~C) == ~C.
2279*9880d681SAndroid Build Coastguard Worker           // This removes the -1 constant.
2280*9880d681SAndroid Build Coastguard Worker           if (BO->hasOneUse() && RHS->isAllOnesValue()) {
2281*9880d681SAndroid Build Coastguard Worker             Constant *NotBOC = ConstantExpr::getNot(BOC);
2282*9880d681SAndroid Build Coastguard Worker             Value *And = Builder->CreateAnd(BO->getOperand(0), NotBOC);
2283*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICI.getPredicate(), And, NotBOC);
2284*9880d681SAndroid Build Coastguard Worker           }
2285*9880d681SAndroid Build Coastguard Worker         }
2286*9880d681SAndroid Build Coastguard Worker         break;
2287*9880d681SAndroid Build Coastguard Worker 
2288*9880d681SAndroid Build Coastguard Worker       case Instruction::And:
2289*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2290*9880d681SAndroid Build Coastguard Worker           // If bits are being compared against that are and'd out, then the
2291*9880d681SAndroid Build Coastguard Worker           // comparison can never succeed!
2292*9880d681SAndroid Build Coastguard Worker           if ((RHSV & ~BOC->getValue()) != 0)
2293*9880d681SAndroid Build Coastguard Worker             return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
2294*9880d681SAndroid Build Coastguard Worker 
2295*9880d681SAndroid Build Coastguard Worker           // If we have ((X & C) == C), turn it into ((X & C) != 0).
2296*9880d681SAndroid Build Coastguard Worker           if (RHS == BOC && RHSV.isPowerOf2())
2297*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
2298*9880d681SAndroid Build Coastguard Worker                                 ICmpInst::ICMP_NE, LHSI,
2299*9880d681SAndroid Build Coastguard Worker                                 Constant::getNullValue(RHS->getType()));
2300*9880d681SAndroid Build Coastguard Worker 
2301*9880d681SAndroid Build Coastguard Worker           // Don't perform the following transforms if the AND has multiple uses
2302*9880d681SAndroid Build Coastguard Worker           if (!BO->hasOneUse())
2303*9880d681SAndroid Build Coastguard Worker             break;
2304*9880d681SAndroid Build Coastguard Worker 
2305*9880d681SAndroid Build Coastguard Worker           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
2306*9880d681SAndroid Build Coastguard Worker           if (BOC->getValue().isSignBit()) {
2307*9880d681SAndroid Build Coastguard Worker             Value *X = BO->getOperand(0);
2308*9880d681SAndroid Build Coastguard Worker             Constant *Zero = Constant::getNullValue(X->getType());
2309*9880d681SAndroid Build Coastguard Worker             ICmpInst::Predicate pred = isICMP_NE ?
2310*9880d681SAndroid Build Coastguard Worker               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2311*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(pred, X, Zero);
2312*9880d681SAndroid Build Coastguard Worker           }
2313*9880d681SAndroid Build Coastguard Worker 
2314*9880d681SAndroid Build Coastguard Worker           // ((X & ~7) == 0) --> X < 8
2315*9880d681SAndroid Build Coastguard Worker           if (RHSV == 0 && isHighOnes(BOC)) {
2316*9880d681SAndroid Build Coastguard Worker             Value *X = BO->getOperand(0);
2317*9880d681SAndroid Build Coastguard Worker             Constant *NegX = ConstantExpr::getNeg(BOC);
2318*9880d681SAndroid Build Coastguard Worker             ICmpInst::Predicate pred = isICMP_NE ?
2319*9880d681SAndroid Build Coastguard Worker               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2320*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(pred, X, NegX);
2321*9880d681SAndroid Build Coastguard Worker           }
2322*9880d681SAndroid Build Coastguard Worker         }
2323*9880d681SAndroid Build Coastguard Worker         break;
2324*9880d681SAndroid Build Coastguard Worker       case Instruction::Mul:
2325*9880d681SAndroid Build Coastguard Worker         if (RHSV == 0 && BO->hasNoSignedWrap()) {
2326*9880d681SAndroid Build Coastguard Worker           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2327*9880d681SAndroid Build Coastguard Worker             // The trivial case (mul X, 0) is handled by InstSimplify
2328*9880d681SAndroid Build Coastguard Worker             // General case : (mul X, C) != 0 iff X != 0
2329*9880d681SAndroid Build Coastguard Worker             //                (mul X, C) == 0 iff X == 0
2330*9880d681SAndroid Build Coastguard Worker             if (!BOC->isZero())
2331*9880d681SAndroid Build Coastguard Worker               return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2332*9880d681SAndroid Build Coastguard Worker                                   Constant::getNullValue(RHS->getType()));
2333*9880d681SAndroid Build Coastguard Worker           }
2334*9880d681SAndroid Build Coastguard Worker         }
2335*9880d681SAndroid Build Coastguard Worker         break;
2336*9880d681SAndroid Build Coastguard Worker       default: break;
2337*9880d681SAndroid Build Coastguard Worker       }
2338*9880d681SAndroid Build Coastguard Worker     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
2339*9880d681SAndroid Build Coastguard Worker       // Handle icmp {eq|ne} <intrinsic>, intcst.
2340*9880d681SAndroid Build Coastguard Worker       switch (II->getIntrinsicID()) {
2341*9880d681SAndroid Build Coastguard Worker       case Intrinsic::bswap:
2342*9880d681SAndroid Build Coastguard Worker         Worklist.Add(II);
2343*9880d681SAndroid Build Coastguard Worker         ICI.setOperand(0, II->getArgOperand(0));
2344*9880d681SAndroid Build Coastguard Worker         ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
2345*9880d681SAndroid Build Coastguard Worker         return &ICI;
2346*9880d681SAndroid Build Coastguard Worker       case Intrinsic::ctlz:
2347*9880d681SAndroid Build Coastguard Worker       case Intrinsic::cttz:
2348*9880d681SAndroid Build Coastguard Worker         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
2349*9880d681SAndroid Build Coastguard Worker         if (RHSV == RHS->getType()->getBitWidth()) {
2350*9880d681SAndroid Build Coastguard Worker           Worklist.Add(II);
2351*9880d681SAndroid Build Coastguard Worker           ICI.setOperand(0, II->getArgOperand(0));
2352*9880d681SAndroid Build Coastguard Worker           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
2353*9880d681SAndroid Build Coastguard Worker           return &ICI;
2354*9880d681SAndroid Build Coastguard Worker         }
2355*9880d681SAndroid Build Coastguard Worker         break;
2356*9880d681SAndroid Build Coastguard Worker       case Intrinsic::ctpop:
2357*9880d681SAndroid Build Coastguard Worker         // popcount(A) == 0  ->  A == 0 and likewise for !=
2358*9880d681SAndroid Build Coastguard Worker         if (RHS->isZero()) {
2359*9880d681SAndroid Build Coastguard Worker           Worklist.Add(II);
2360*9880d681SAndroid Build Coastguard Worker           ICI.setOperand(0, II->getArgOperand(0));
2361*9880d681SAndroid Build Coastguard Worker           ICI.setOperand(1, RHS);
2362*9880d681SAndroid Build Coastguard Worker           return &ICI;
2363*9880d681SAndroid Build Coastguard Worker         }
2364*9880d681SAndroid Build Coastguard Worker         break;
2365*9880d681SAndroid Build Coastguard Worker       default:
2366*9880d681SAndroid Build Coastguard Worker         break;
2367*9880d681SAndroid Build Coastguard Worker       }
2368*9880d681SAndroid Build Coastguard Worker     }
2369*9880d681SAndroid Build Coastguard Worker   }
2370*9880d681SAndroid Build Coastguard Worker   return nullptr;
2371*9880d681SAndroid Build Coastguard Worker }
2372*9880d681SAndroid Build Coastguard Worker 
2373*9880d681SAndroid Build Coastguard Worker /// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2374*9880d681SAndroid Build Coastguard Worker /// far.
visitICmpInstWithCastAndCast(ICmpInst & ICmp)2375*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICmp) {
2376*9880d681SAndroid Build Coastguard Worker   const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
2377*9880d681SAndroid Build Coastguard Worker   Value *LHSCIOp        = LHSCI->getOperand(0);
2378*9880d681SAndroid Build Coastguard Worker   Type *SrcTy     = LHSCIOp->getType();
2379*9880d681SAndroid Build Coastguard Worker   Type *DestTy    = LHSCI->getType();
2380*9880d681SAndroid Build Coastguard Worker   Value *RHSCIOp;
2381*9880d681SAndroid Build Coastguard Worker 
2382*9880d681SAndroid Build Coastguard Worker   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
2383*9880d681SAndroid Build Coastguard Worker   // integer type is the same size as the pointer type.
2384*9880d681SAndroid Build Coastguard Worker   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2385*9880d681SAndroid Build Coastguard Worker       DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
2386*9880d681SAndroid Build Coastguard Worker     Value *RHSOp = nullptr;
2387*9880d681SAndroid Build Coastguard Worker     if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
2388*9880d681SAndroid Build Coastguard Worker       Value *RHSCIOp = RHSC->getOperand(0);
2389*9880d681SAndroid Build Coastguard Worker       if (RHSCIOp->getType()->getPointerAddressSpace() ==
2390*9880d681SAndroid Build Coastguard Worker           LHSCIOp->getType()->getPointerAddressSpace()) {
2391*9880d681SAndroid Build Coastguard Worker         RHSOp = RHSC->getOperand(0);
2392*9880d681SAndroid Build Coastguard Worker         // If the pointer types don't match, insert a bitcast.
2393*9880d681SAndroid Build Coastguard Worker         if (LHSCIOp->getType() != RHSOp->getType())
2394*9880d681SAndroid Build Coastguard Worker           RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2395*9880d681SAndroid Build Coastguard Worker       }
2396*9880d681SAndroid Build Coastguard Worker     } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
2397*9880d681SAndroid Build Coastguard Worker       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
2398*9880d681SAndroid Build Coastguard Worker     }
2399*9880d681SAndroid Build Coastguard Worker 
2400*9880d681SAndroid Build Coastguard Worker     if (RHSOp)
2401*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
2402*9880d681SAndroid Build Coastguard Worker   }
2403*9880d681SAndroid Build Coastguard Worker 
2404*9880d681SAndroid Build Coastguard Worker   // The code below only handles extension cast instructions, so far.
2405*9880d681SAndroid Build Coastguard Worker   // Enforce this.
2406*9880d681SAndroid Build Coastguard Worker   if (LHSCI->getOpcode() != Instruction::ZExt &&
2407*9880d681SAndroid Build Coastguard Worker       LHSCI->getOpcode() != Instruction::SExt)
2408*9880d681SAndroid Build Coastguard Worker     return nullptr;
2409*9880d681SAndroid Build Coastguard Worker 
2410*9880d681SAndroid Build Coastguard Worker   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
2411*9880d681SAndroid Build Coastguard Worker   bool isSignedCmp = ICmp.isSigned();
2412*9880d681SAndroid Build Coastguard Worker 
2413*9880d681SAndroid Build Coastguard Worker   if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
2414*9880d681SAndroid Build Coastguard Worker     // Not an extension from the same type?
2415*9880d681SAndroid Build Coastguard Worker     RHSCIOp = CI->getOperand(0);
2416*9880d681SAndroid Build Coastguard Worker     if (RHSCIOp->getType() != LHSCIOp->getType())
2417*9880d681SAndroid Build Coastguard Worker       return nullptr;
2418*9880d681SAndroid Build Coastguard Worker 
2419*9880d681SAndroid Build Coastguard Worker     // If the signedness of the two casts doesn't agree (i.e. one is a sext
2420*9880d681SAndroid Build Coastguard Worker     // and the other is a zext), then we can't handle this.
2421*9880d681SAndroid Build Coastguard Worker     if (CI->getOpcode() != LHSCI->getOpcode())
2422*9880d681SAndroid Build Coastguard Worker       return nullptr;
2423*9880d681SAndroid Build Coastguard Worker 
2424*9880d681SAndroid Build Coastguard Worker     // Deal with equality cases early.
2425*9880d681SAndroid Build Coastguard Worker     if (ICmp.isEquality())
2426*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
2427*9880d681SAndroid Build Coastguard Worker 
2428*9880d681SAndroid Build Coastguard Worker     // A signed comparison of sign extended values simplifies into a
2429*9880d681SAndroid Build Coastguard Worker     // signed comparison.
2430*9880d681SAndroid Build Coastguard Worker     if (isSignedCmp && isSignedExt)
2431*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
2432*9880d681SAndroid Build Coastguard Worker 
2433*9880d681SAndroid Build Coastguard Worker     // The other three cases all fold into an unsigned comparison.
2434*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
2435*9880d681SAndroid Build Coastguard Worker   }
2436*9880d681SAndroid Build Coastguard Worker 
2437*9880d681SAndroid Build Coastguard Worker   // If we aren't dealing with a constant on the RHS, exit early.
2438*9880d681SAndroid Build Coastguard Worker   auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2439*9880d681SAndroid Build Coastguard Worker   if (!C)
2440*9880d681SAndroid Build Coastguard Worker     return nullptr;
2441*9880d681SAndroid Build Coastguard Worker 
2442*9880d681SAndroid Build Coastguard Worker   // Compute the constant that would happen if we truncated to SrcTy then
2443*9880d681SAndroid Build Coastguard Worker   // re-extended to DestTy.
2444*9880d681SAndroid Build Coastguard Worker   Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
2445*9880d681SAndroid Build Coastguard Worker   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
2446*9880d681SAndroid Build Coastguard Worker 
2447*9880d681SAndroid Build Coastguard Worker   // If the re-extended constant didn't change...
2448*9880d681SAndroid Build Coastguard Worker   if (Res2 == C) {
2449*9880d681SAndroid Build Coastguard Worker     // Deal with equality cases early.
2450*9880d681SAndroid Build Coastguard Worker     if (ICmp.isEquality())
2451*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
2452*9880d681SAndroid Build Coastguard Worker 
2453*9880d681SAndroid Build Coastguard Worker     // A signed comparison of sign extended values simplifies into a
2454*9880d681SAndroid Build Coastguard Worker     // signed comparison.
2455*9880d681SAndroid Build Coastguard Worker     if (isSignedExt && isSignedCmp)
2456*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
2457*9880d681SAndroid Build Coastguard Worker 
2458*9880d681SAndroid Build Coastguard Worker     // The other three cases all fold into an unsigned comparison.
2459*9880d681SAndroid Build Coastguard Worker     return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
2460*9880d681SAndroid Build Coastguard Worker   }
2461*9880d681SAndroid Build Coastguard Worker 
2462*9880d681SAndroid Build Coastguard Worker   // The re-extended constant changed, partly changed (in the case of a vector),
2463*9880d681SAndroid Build Coastguard Worker   // or could not be determined to be equal (in the case of a constant
2464*9880d681SAndroid Build Coastguard Worker   // expression), so the constant cannot be represented in the shorter type.
2465*9880d681SAndroid Build Coastguard Worker   // Consequently, we cannot emit a simple comparison.
2466*9880d681SAndroid Build Coastguard Worker   // All the cases that fold to true or false will have already been handled
2467*9880d681SAndroid Build Coastguard Worker   // by SimplifyICmpInst, so only deal with the tricky case.
2468*9880d681SAndroid Build Coastguard Worker 
2469*9880d681SAndroid Build Coastguard Worker   if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
2470*9880d681SAndroid Build Coastguard Worker     return nullptr;
2471*9880d681SAndroid Build Coastguard Worker 
2472*9880d681SAndroid Build Coastguard Worker   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2473*9880d681SAndroid Build Coastguard Worker   // should have been folded away previously and not enter in here.
2474*9880d681SAndroid Build Coastguard Worker 
2475*9880d681SAndroid Build Coastguard Worker   // We're performing an unsigned comp with a sign extended value.
2476*9880d681SAndroid Build Coastguard Worker   // This is true if the input is >= 0. [aka >s -1]
2477*9880d681SAndroid Build Coastguard Worker   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
2478*9880d681SAndroid Build Coastguard Worker   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
2479*9880d681SAndroid Build Coastguard Worker 
2480*9880d681SAndroid Build Coastguard Worker   // Finally, return the value computed.
2481*9880d681SAndroid Build Coastguard Worker   if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2482*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(ICmp, Result);
2483*9880d681SAndroid Build Coastguard Worker 
2484*9880d681SAndroid Build Coastguard Worker   assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
2485*9880d681SAndroid Build Coastguard Worker   return BinaryOperator::CreateNot(Result);
2486*9880d681SAndroid Build Coastguard Worker }
2487*9880d681SAndroid Build Coastguard Worker 
2488*9880d681SAndroid Build Coastguard Worker /// The caller has matched a pattern of the form:
2489*9880d681SAndroid Build Coastguard Worker ///   I = icmp ugt (add (add A, B), CI2), CI1
2490*9880d681SAndroid Build Coastguard Worker /// If this is of the form:
2491*9880d681SAndroid Build Coastguard Worker ///   sum = a + b
2492*9880d681SAndroid Build Coastguard Worker ///   if (sum+128 >u 255)
2493*9880d681SAndroid Build Coastguard Worker /// Then replace it with llvm.sadd.with.overflow.i8.
2494*9880d681SAndroid Build Coastguard Worker ///
ProcessUGT_ADDCST_ADD(ICmpInst & I,Value * A,Value * B,ConstantInt * CI2,ConstantInt * CI1,InstCombiner & IC)2495*9880d681SAndroid Build Coastguard Worker static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2496*9880d681SAndroid Build Coastguard Worker                                           ConstantInt *CI2, ConstantInt *CI1,
2497*9880d681SAndroid Build Coastguard Worker                                           InstCombiner &IC) {
2498*9880d681SAndroid Build Coastguard Worker   // The transformation we're trying to do here is to transform this into an
2499*9880d681SAndroid Build Coastguard Worker   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
2500*9880d681SAndroid Build Coastguard Worker   // with a narrower add, and discard the add-with-constant that is part of the
2501*9880d681SAndroid Build Coastguard Worker   // range check (if we can't eliminate it, this isn't profitable).
2502*9880d681SAndroid Build Coastguard Worker 
2503*9880d681SAndroid Build Coastguard Worker   // In order to eliminate the add-with-constant, the compare can be its only
2504*9880d681SAndroid Build Coastguard Worker   // use.
2505*9880d681SAndroid Build Coastguard Worker   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
2506*9880d681SAndroid Build Coastguard Worker   if (!AddWithCst->hasOneUse()) return nullptr;
2507*9880d681SAndroid Build Coastguard Worker 
2508*9880d681SAndroid Build Coastguard Worker   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
2509*9880d681SAndroid Build Coastguard Worker   if (!CI2->getValue().isPowerOf2()) return nullptr;
2510*9880d681SAndroid Build Coastguard Worker   unsigned NewWidth = CI2->getValue().countTrailingZeros();
2511*9880d681SAndroid Build Coastguard Worker   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
2512*9880d681SAndroid Build Coastguard Worker 
2513*9880d681SAndroid Build Coastguard Worker   // The width of the new add formed is 1 more than the bias.
2514*9880d681SAndroid Build Coastguard Worker   ++NewWidth;
2515*9880d681SAndroid Build Coastguard Worker 
2516*9880d681SAndroid Build Coastguard Worker   // Check to see that CI1 is an all-ones value with NewWidth bits.
2517*9880d681SAndroid Build Coastguard Worker   if (CI1->getBitWidth() == NewWidth ||
2518*9880d681SAndroid Build Coastguard Worker       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
2519*9880d681SAndroid Build Coastguard Worker     return nullptr;
2520*9880d681SAndroid Build Coastguard Worker 
2521*9880d681SAndroid Build Coastguard Worker   // This is only really a signed overflow check if the inputs have been
2522*9880d681SAndroid Build Coastguard Worker   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2523*9880d681SAndroid Build Coastguard Worker   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2524*9880d681SAndroid Build Coastguard Worker   unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
2525*9880d681SAndroid Build Coastguard Worker   if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2526*9880d681SAndroid Build Coastguard Worker       IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
2527*9880d681SAndroid Build Coastguard Worker     return nullptr;
2528*9880d681SAndroid Build Coastguard Worker 
2529*9880d681SAndroid Build Coastguard Worker   // In order to replace the original add with a narrower
2530*9880d681SAndroid Build Coastguard Worker   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2531*9880d681SAndroid Build Coastguard Worker   // and truncates that discard the high bits of the add.  Verify that this is
2532*9880d681SAndroid Build Coastguard Worker   // the case.
2533*9880d681SAndroid Build Coastguard Worker   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
2534*9880d681SAndroid Build Coastguard Worker   for (User *U : OrigAdd->users()) {
2535*9880d681SAndroid Build Coastguard Worker     if (U == AddWithCst) continue;
2536*9880d681SAndroid Build Coastguard Worker 
2537*9880d681SAndroid Build Coastguard Worker     // Only accept truncates for now.  We would really like a nice recursive
2538*9880d681SAndroid Build Coastguard Worker     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2539*9880d681SAndroid Build Coastguard Worker     // chain to see which bits of a value are actually demanded.  If the
2540*9880d681SAndroid Build Coastguard Worker     // original add had another add which was then immediately truncated, we
2541*9880d681SAndroid Build Coastguard Worker     // could still do the transformation.
2542*9880d681SAndroid Build Coastguard Worker     TruncInst *TI = dyn_cast<TruncInst>(U);
2543*9880d681SAndroid Build Coastguard Worker     if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2544*9880d681SAndroid Build Coastguard Worker       return nullptr;
2545*9880d681SAndroid Build Coastguard Worker   }
2546*9880d681SAndroid Build Coastguard Worker 
2547*9880d681SAndroid Build Coastguard Worker   // If the pattern matches, truncate the inputs to the narrower type and
2548*9880d681SAndroid Build Coastguard Worker   // use the sadd_with_overflow intrinsic to efficiently compute both the
2549*9880d681SAndroid Build Coastguard Worker   // result and the overflow bit.
2550*9880d681SAndroid Build Coastguard Worker   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
2551*9880d681SAndroid Build Coastguard Worker   Value *F = Intrinsic::getDeclaration(I.getModule(),
2552*9880d681SAndroid Build Coastguard Worker                                        Intrinsic::sadd_with_overflow, NewType);
2553*9880d681SAndroid Build Coastguard Worker 
2554*9880d681SAndroid Build Coastguard Worker   InstCombiner::BuilderTy *Builder = IC.Builder;
2555*9880d681SAndroid Build Coastguard Worker 
2556*9880d681SAndroid Build Coastguard Worker   // Put the new code above the original add, in case there are any uses of the
2557*9880d681SAndroid Build Coastguard Worker   // add between the add and the compare.
2558*9880d681SAndroid Build Coastguard Worker   Builder->SetInsertPoint(OrigAdd);
2559*9880d681SAndroid Build Coastguard Worker 
2560*9880d681SAndroid Build Coastguard Worker   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2561*9880d681SAndroid Build Coastguard Worker   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
2562*9880d681SAndroid Build Coastguard Worker   CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
2563*9880d681SAndroid Build Coastguard Worker   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2564*9880d681SAndroid Build Coastguard Worker   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
2565*9880d681SAndroid Build Coastguard Worker 
2566*9880d681SAndroid Build Coastguard Worker   // The inner add was the result of the narrow add, zero extended to the
2567*9880d681SAndroid Build Coastguard Worker   // wider type.  Replace it with the result computed by the intrinsic.
2568*9880d681SAndroid Build Coastguard Worker   IC.replaceInstUsesWith(*OrigAdd, ZExt);
2569*9880d681SAndroid Build Coastguard Worker 
2570*9880d681SAndroid Build Coastguard Worker   // The original icmp gets replaced with the overflow value.
2571*9880d681SAndroid Build Coastguard Worker   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
2572*9880d681SAndroid Build Coastguard Worker }
2573*9880d681SAndroid Build Coastguard Worker 
OptimizeOverflowCheck(OverflowCheckFlavor OCF,Value * LHS,Value * RHS,Instruction & OrigI,Value * & Result,Constant * & Overflow)2574*9880d681SAndroid Build Coastguard Worker bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2575*9880d681SAndroid Build Coastguard Worker                                          Value *RHS, Instruction &OrigI,
2576*9880d681SAndroid Build Coastguard Worker                                          Value *&Result, Constant *&Overflow) {
2577*9880d681SAndroid Build Coastguard Worker   if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2578*9880d681SAndroid Build Coastguard Worker     std::swap(LHS, RHS);
2579*9880d681SAndroid Build Coastguard Worker 
2580*9880d681SAndroid Build Coastguard Worker   auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2581*9880d681SAndroid Build Coastguard Worker     Result = OpResult;
2582*9880d681SAndroid Build Coastguard Worker     Overflow = OverflowVal;
2583*9880d681SAndroid Build Coastguard Worker     if (ReuseName)
2584*9880d681SAndroid Build Coastguard Worker       Result->takeName(&OrigI);
2585*9880d681SAndroid Build Coastguard Worker     return true;
2586*9880d681SAndroid Build Coastguard Worker   };
2587*9880d681SAndroid Build Coastguard Worker 
2588*9880d681SAndroid Build Coastguard Worker   // If the overflow check was an add followed by a compare, the insertion point
2589*9880d681SAndroid Build Coastguard Worker   // may be pointing to the compare.  We want to insert the new instructions
2590*9880d681SAndroid Build Coastguard Worker   // before the add in case there are uses of the add between the add and the
2591*9880d681SAndroid Build Coastguard Worker   // compare.
2592*9880d681SAndroid Build Coastguard Worker   Builder->SetInsertPoint(&OrigI);
2593*9880d681SAndroid Build Coastguard Worker 
2594*9880d681SAndroid Build Coastguard Worker   switch (OCF) {
2595*9880d681SAndroid Build Coastguard Worker   case OCF_INVALID:
2596*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("bad overflow check kind!");
2597*9880d681SAndroid Build Coastguard Worker 
2598*9880d681SAndroid Build Coastguard Worker   case OCF_UNSIGNED_ADD: {
2599*9880d681SAndroid Build Coastguard Worker     OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2600*9880d681SAndroid Build Coastguard Worker     if (OR == OverflowResult::NeverOverflows)
2601*9880d681SAndroid Build Coastguard Worker       return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2602*9880d681SAndroid Build Coastguard Worker                        true);
2603*9880d681SAndroid Build Coastguard Worker 
2604*9880d681SAndroid Build Coastguard Worker     if (OR == OverflowResult::AlwaysOverflows)
2605*9880d681SAndroid Build Coastguard Worker       return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2606*9880d681SAndroid Build Coastguard Worker   }
2607*9880d681SAndroid Build Coastguard Worker   // FALL THROUGH uadd into sadd
2608*9880d681SAndroid Build Coastguard Worker   case OCF_SIGNED_ADD: {
2609*9880d681SAndroid Build Coastguard Worker     // X + 0 -> {X, false}
2610*9880d681SAndroid Build Coastguard Worker     if (match(RHS, m_Zero()))
2611*9880d681SAndroid Build Coastguard Worker       return SetResult(LHS, Builder->getFalse(), false);
2612*9880d681SAndroid Build Coastguard Worker 
2613*9880d681SAndroid Build Coastguard Worker     // We can strength reduce this signed add into a regular add if we can prove
2614*9880d681SAndroid Build Coastguard Worker     // that it will never overflow.
2615*9880d681SAndroid Build Coastguard Worker     if (OCF == OCF_SIGNED_ADD)
2616*9880d681SAndroid Build Coastguard Worker       if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2617*9880d681SAndroid Build Coastguard Worker         return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2618*9880d681SAndroid Build Coastguard Worker                          true);
2619*9880d681SAndroid Build Coastguard Worker     break;
2620*9880d681SAndroid Build Coastguard Worker   }
2621*9880d681SAndroid Build Coastguard Worker 
2622*9880d681SAndroid Build Coastguard Worker   case OCF_UNSIGNED_SUB:
2623*9880d681SAndroid Build Coastguard Worker   case OCF_SIGNED_SUB: {
2624*9880d681SAndroid Build Coastguard Worker     // X - 0 -> {X, false}
2625*9880d681SAndroid Build Coastguard Worker     if (match(RHS, m_Zero()))
2626*9880d681SAndroid Build Coastguard Worker       return SetResult(LHS, Builder->getFalse(), false);
2627*9880d681SAndroid Build Coastguard Worker 
2628*9880d681SAndroid Build Coastguard Worker     if (OCF == OCF_SIGNED_SUB) {
2629*9880d681SAndroid Build Coastguard Worker       if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2630*9880d681SAndroid Build Coastguard Worker         return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2631*9880d681SAndroid Build Coastguard Worker                          true);
2632*9880d681SAndroid Build Coastguard Worker     } else {
2633*9880d681SAndroid Build Coastguard Worker       if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2634*9880d681SAndroid Build Coastguard Worker         return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2635*9880d681SAndroid Build Coastguard Worker                          true);
2636*9880d681SAndroid Build Coastguard Worker     }
2637*9880d681SAndroid Build Coastguard Worker     break;
2638*9880d681SAndroid Build Coastguard Worker   }
2639*9880d681SAndroid Build Coastguard Worker 
2640*9880d681SAndroid Build Coastguard Worker   case OCF_UNSIGNED_MUL: {
2641*9880d681SAndroid Build Coastguard Worker     OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2642*9880d681SAndroid Build Coastguard Worker     if (OR == OverflowResult::NeverOverflows)
2643*9880d681SAndroid Build Coastguard Worker       return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2644*9880d681SAndroid Build Coastguard Worker                        true);
2645*9880d681SAndroid Build Coastguard Worker     if (OR == OverflowResult::AlwaysOverflows)
2646*9880d681SAndroid Build Coastguard Worker       return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2647*9880d681SAndroid Build Coastguard Worker   } // FALL THROUGH
2648*9880d681SAndroid Build Coastguard Worker   case OCF_SIGNED_MUL:
2649*9880d681SAndroid Build Coastguard Worker     // X * undef -> undef
2650*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(RHS))
2651*9880d681SAndroid Build Coastguard Worker       return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
2652*9880d681SAndroid Build Coastguard Worker 
2653*9880d681SAndroid Build Coastguard Worker     // X * 0 -> {0, false}
2654*9880d681SAndroid Build Coastguard Worker     if (match(RHS, m_Zero()))
2655*9880d681SAndroid Build Coastguard Worker       return SetResult(RHS, Builder->getFalse(), false);
2656*9880d681SAndroid Build Coastguard Worker 
2657*9880d681SAndroid Build Coastguard Worker     // X * 1 -> {X, false}
2658*9880d681SAndroid Build Coastguard Worker     if (match(RHS, m_One()))
2659*9880d681SAndroid Build Coastguard Worker       return SetResult(LHS, Builder->getFalse(), false);
2660*9880d681SAndroid Build Coastguard Worker 
2661*9880d681SAndroid Build Coastguard Worker     if (OCF == OCF_SIGNED_MUL)
2662*9880d681SAndroid Build Coastguard Worker       if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2663*9880d681SAndroid Build Coastguard Worker         return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2664*9880d681SAndroid Build Coastguard Worker                          true);
2665*9880d681SAndroid Build Coastguard Worker     break;
2666*9880d681SAndroid Build Coastguard Worker   }
2667*9880d681SAndroid Build Coastguard Worker 
2668*9880d681SAndroid Build Coastguard Worker   return false;
2669*9880d681SAndroid Build Coastguard Worker }
2670*9880d681SAndroid Build Coastguard Worker 
2671*9880d681SAndroid Build Coastguard Worker /// \brief Recognize and process idiom involving test for multiplication
2672*9880d681SAndroid Build Coastguard Worker /// overflow.
2673*9880d681SAndroid Build Coastguard Worker ///
2674*9880d681SAndroid Build Coastguard Worker /// The caller has matched a pattern of the form:
2675*9880d681SAndroid Build Coastguard Worker ///   I = cmp u (mul(zext A, zext B), V
2676*9880d681SAndroid Build Coastguard Worker /// The function checks if this is a test for overflow and if so replaces
2677*9880d681SAndroid Build Coastguard Worker /// multiplication with call to 'mul.with.overflow' intrinsic.
2678*9880d681SAndroid Build Coastguard Worker ///
2679*9880d681SAndroid Build Coastguard Worker /// \param I Compare instruction.
2680*9880d681SAndroid Build Coastguard Worker /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
2681*9880d681SAndroid Build Coastguard Worker ///               the compare instruction.  Must be of integer type.
2682*9880d681SAndroid Build Coastguard Worker /// \param OtherVal The other argument of compare instruction.
2683*9880d681SAndroid Build Coastguard Worker /// \returns Instruction which must replace the compare instruction, NULL if no
2684*9880d681SAndroid Build Coastguard Worker ///          replacement required.
ProcessUMulZExtIdiom(ICmpInst & I,Value * MulVal,Value * OtherVal,InstCombiner & IC)2685*9880d681SAndroid Build Coastguard Worker static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2686*9880d681SAndroid Build Coastguard Worker                                          Value *OtherVal, InstCombiner &IC) {
2687*9880d681SAndroid Build Coastguard Worker   // Don't bother doing this transformation for pointers, don't do it for
2688*9880d681SAndroid Build Coastguard Worker   // vectors.
2689*9880d681SAndroid Build Coastguard Worker   if (!isa<IntegerType>(MulVal->getType()))
2690*9880d681SAndroid Build Coastguard Worker     return nullptr;
2691*9880d681SAndroid Build Coastguard Worker 
2692*9880d681SAndroid Build Coastguard Worker   assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2693*9880d681SAndroid Build Coastguard Worker   assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
2694*9880d681SAndroid Build Coastguard Worker   auto *MulInstr = dyn_cast<Instruction>(MulVal);
2695*9880d681SAndroid Build Coastguard Worker   if (!MulInstr)
2696*9880d681SAndroid Build Coastguard Worker     return nullptr;
2697*9880d681SAndroid Build Coastguard Worker   assert(MulInstr->getOpcode() == Instruction::Mul);
2698*9880d681SAndroid Build Coastguard Worker 
2699*9880d681SAndroid Build Coastguard Worker   auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2700*9880d681SAndroid Build Coastguard Worker        *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
2701*9880d681SAndroid Build Coastguard Worker   assert(LHS->getOpcode() == Instruction::ZExt);
2702*9880d681SAndroid Build Coastguard Worker   assert(RHS->getOpcode() == Instruction::ZExt);
2703*9880d681SAndroid Build Coastguard Worker   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2704*9880d681SAndroid Build Coastguard Worker 
2705*9880d681SAndroid Build Coastguard Worker   // Calculate type and width of the result produced by mul.with.overflow.
2706*9880d681SAndroid Build Coastguard Worker   Type *TyA = A->getType(), *TyB = B->getType();
2707*9880d681SAndroid Build Coastguard Worker   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2708*9880d681SAndroid Build Coastguard Worker            WidthB = TyB->getPrimitiveSizeInBits();
2709*9880d681SAndroid Build Coastguard Worker   unsigned MulWidth;
2710*9880d681SAndroid Build Coastguard Worker   Type *MulType;
2711*9880d681SAndroid Build Coastguard Worker   if (WidthB > WidthA) {
2712*9880d681SAndroid Build Coastguard Worker     MulWidth = WidthB;
2713*9880d681SAndroid Build Coastguard Worker     MulType = TyB;
2714*9880d681SAndroid Build Coastguard Worker   } else {
2715*9880d681SAndroid Build Coastguard Worker     MulWidth = WidthA;
2716*9880d681SAndroid Build Coastguard Worker     MulType = TyA;
2717*9880d681SAndroid Build Coastguard Worker   }
2718*9880d681SAndroid Build Coastguard Worker 
2719*9880d681SAndroid Build Coastguard Worker   // In order to replace the original mul with a narrower mul.with.overflow,
2720*9880d681SAndroid Build Coastguard Worker   // all uses must ignore upper bits of the product.  The number of used low
2721*9880d681SAndroid Build Coastguard Worker   // bits must be not greater than the width of mul.with.overflow.
2722*9880d681SAndroid Build Coastguard Worker   if (MulVal->hasNUsesOrMore(2))
2723*9880d681SAndroid Build Coastguard Worker     for (User *U : MulVal->users()) {
2724*9880d681SAndroid Build Coastguard Worker       if (U == &I)
2725*9880d681SAndroid Build Coastguard Worker         continue;
2726*9880d681SAndroid Build Coastguard Worker       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2727*9880d681SAndroid Build Coastguard Worker         // Check if truncation ignores bits above MulWidth.
2728*9880d681SAndroid Build Coastguard Worker         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2729*9880d681SAndroid Build Coastguard Worker         if (TruncWidth > MulWidth)
2730*9880d681SAndroid Build Coastguard Worker           return nullptr;
2731*9880d681SAndroid Build Coastguard Worker       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2732*9880d681SAndroid Build Coastguard Worker         // Check if AND ignores bits above MulWidth.
2733*9880d681SAndroid Build Coastguard Worker         if (BO->getOpcode() != Instruction::And)
2734*9880d681SAndroid Build Coastguard Worker           return nullptr;
2735*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2736*9880d681SAndroid Build Coastguard Worker           const APInt &CVal = CI->getValue();
2737*9880d681SAndroid Build Coastguard Worker           if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
2738*9880d681SAndroid Build Coastguard Worker             return nullptr;
2739*9880d681SAndroid Build Coastguard Worker         }
2740*9880d681SAndroid Build Coastguard Worker       } else {
2741*9880d681SAndroid Build Coastguard Worker         // Other uses prohibit this transformation.
2742*9880d681SAndroid Build Coastguard Worker         return nullptr;
2743*9880d681SAndroid Build Coastguard Worker       }
2744*9880d681SAndroid Build Coastguard Worker     }
2745*9880d681SAndroid Build Coastguard Worker 
2746*9880d681SAndroid Build Coastguard Worker   // Recognize patterns
2747*9880d681SAndroid Build Coastguard Worker   switch (I.getPredicate()) {
2748*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_EQ:
2749*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_NE:
2750*9880d681SAndroid Build Coastguard Worker     // Recognize pattern:
2751*9880d681SAndroid Build Coastguard Worker     //   mulval = mul(zext A, zext B)
2752*9880d681SAndroid Build Coastguard Worker     //   cmp eq/neq mulval, zext trunc mulval
2753*9880d681SAndroid Build Coastguard Worker     if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2754*9880d681SAndroid Build Coastguard Worker       if (Zext->hasOneUse()) {
2755*9880d681SAndroid Build Coastguard Worker         Value *ZextArg = Zext->getOperand(0);
2756*9880d681SAndroid Build Coastguard Worker         if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2757*9880d681SAndroid Build Coastguard Worker           if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2758*9880d681SAndroid Build Coastguard Worker             break; //Recognized
2759*9880d681SAndroid Build Coastguard Worker       }
2760*9880d681SAndroid Build Coastguard Worker 
2761*9880d681SAndroid Build Coastguard Worker     // Recognize pattern:
2762*9880d681SAndroid Build Coastguard Worker     //   mulval = mul(zext A, zext B)
2763*9880d681SAndroid Build Coastguard Worker     //   cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2764*9880d681SAndroid Build Coastguard Worker     ConstantInt *CI;
2765*9880d681SAndroid Build Coastguard Worker     Value *ValToMask;
2766*9880d681SAndroid Build Coastguard Worker     if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2767*9880d681SAndroid Build Coastguard Worker       if (ValToMask != MulVal)
2768*9880d681SAndroid Build Coastguard Worker         return nullptr;
2769*9880d681SAndroid Build Coastguard Worker       const APInt &CVal = CI->getValue() + 1;
2770*9880d681SAndroid Build Coastguard Worker       if (CVal.isPowerOf2()) {
2771*9880d681SAndroid Build Coastguard Worker         unsigned MaskWidth = CVal.logBase2();
2772*9880d681SAndroid Build Coastguard Worker         if (MaskWidth == MulWidth)
2773*9880d681SAndroid Build Coastguard Worker           break; // Recognized
2774*9880d681SAndroid Build Coastguard Worker       }
2775*9880d681SAndroid Build Coastguard Worker     }
2776*9880d681SAndroid Build Coastguard Worker     return nullptr;
2777*9880d681SAndroid Build Coastguard Worker 
2778*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGT:
2779*9880d681SAndroid Build Coastguard Worker     // Recognize pattern:
2780*9880d681SAndroid Build Coastguard Worker     //   mulval = mul(zext A, zext B)
2781*9880d681SAndroid Build Coastguard Worker     //   cmp ugt mulval, max
2782*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2783*9880d681SAndroid Build Coastguard Worker       APInt MaxVal = APInt::getMaxValue(MulWidth);
2784*9880d681SAndroid Build Coastguard Worker       MaxVal = MaxVal.zext(CI->getBitWidth());
2785*9880d681SAndroid Build Coastguard Worker       if (MaxVal.eq(CI->getValue()))
2786*9880d681SAndroid Build Coastguard Worker         break; // Recognized
2787*9880d681SAndroid Build Coastguard Worker     }
2788*9880d681SAndroid Build Coastguard Worker     return nullptr;
2789*9880d681SAndroid Build Coastguard Worker 
2790*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGE:
2791*9880d681SAndroid Build Coastguard Worker     // Recognize pattern:
2792*9880d681SAndroid Build Coastguard Worker     //   mulval = mul(zext A, zext B)
2793*9880d681SAndroid Build Coastguard Worker     //   cmp uge mulval, max+1
2794*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2795*9880d681SAndroid Build Coastguard Worker       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2796*9880d681SAndroid Build Coastguard Worker       if (MaxVal.eq(CI->getValue()))
2797*9880d681SAndroid Build Coastguard Worker         break; // Recognized
2798*9880d681SAndroid Build Coastguard Worker     }
2799*9880d681SAndroid Build Coastguard Worker     return nullptr;
2800*9880d681SAndroid Build Coastguard Worker 
2801*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULE:
2802*9880d681SAndroid Build Coastguard Worker     // Recognize pattern:
2803*9880d681SAndroid Build Coastguard Worker     //   mulval = mul(zext A, zext B)
2804*9880d681SAndroid Build Coastguard Worker     //   cmp ule mulval, max
2805*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2806*9880d681SAndroid Build Coastguard Worker       APInt MaxVal = APInt::getMaxValue(MulWidth);
2807*9880d681SAndroid Build Coastguard Worker       MaxVal = MaxVal.zext(CI->getBitWidth());
2808*9880d681SAndroid Build Coastguard Worker       if (MaxVal.eq(CI->getValue()))
2809*9880d681SAndroid Build Coastguard Worker         break; // Recognized
2810*9880d681SAndroid Build Coastguard Worker     }
2811*9880d681SAndroid Build Coastguard Worker     return nullptr;
2812*9880d681SAndroid Build Coastguard Worker 
2813*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULT:
2814*9880d681SAndroid Build Coastguard Worker     // Recognize pattern:
2815*9880d681SAndroid Build Coastguard Worker     //   mulval = mul(zext A, zext B)
2816*9880d681SAndroid Build Coastguard Worker     //   cmp ule mulval, max + 1
2817*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2818*9880d681SAndroid Build Coastguard Worker       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2819*9880d681SAndroid Build Coastguard Worker       if (MaxVal.eq(CI->getValue()))
2820*9880d681SAndroid Build Coastguard Worker         break; // Recognized
2821*9880d681SAndroid Build Coastguard Worker     }
2822*9880d681SAndroid Build Coastguard Worker     return nullptr;
2823*9880d681SAndroid Build Coastguard Worker 
2824*9880d681SAndroid Build Coastguard Worker   default:
2825*9880d681SAndroid Build Coastguard Worker     return nullptr;
2826*9880d681SAndroid Build Coastguard Worker   }
2827*9880d681SAndroid Build Coastguard Worker 
2828*9880d681SAndroid Build Coastguard Worker   InstCombiner::BuilderTy *Builder = IC.Builder;
2829*9880d681SAndroid Build Coastguard Worker   Builder->SetInsertPoint(MulInstr);
2830*9880d681SAndroid Build Coastguard Worker 
2831*9880d681SAndroid Build Coastguard Worker   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2832*9880d681SAndroid Build Coastguard Worker   Value *MulA = A, *MulB = B;
2833*9880d681SAndroid Build Coastguard Worker   if (WidthA < MulWidth)
2834*9880d681SAndroid Build Coastguard Worker     MulA = Builder->CreateZExt(A, MulType);
2835*9880d681SAndroid Build Coastguard Worker   if (WidthB < MulWidth)
2836*9880d681SAndroid Build Coastguard Worker     MulB = Builder->CreateZExt(B, MulType);
2837*9880d681SAndroid Build Coastguard Worker   Value *F = Intrinsic::getDeclaration(I.getModule(),
2838*9880d681SAndroid Build Coastguard Worker                                        Intrinsic::umul_with_overflow, MulType);
2839*9880d681SAndroid Build Coastguard Worker   CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
2840*9880d681SAndroid Build Coastguard Worker   IC.Worklist.Add(MulInstr);
2841*9880d681SAndroid Build Coastguard Worker 
2842*9880d681SAndroid Build Coastguard Worker   // If there are uses of mul result other than the comparison, we know that
2843*9880d681SAndroid Build Coastguard Worker   // they are truncation or binary AND. Change them to use result of
2844*9880d681SAndroid Build Coastguard Worker   // mul.with.overflow and adjust properly mask/size.
2845*9880d681SAndroid Build Coastguard Worker   if (MulVal->hasNUsesOrMore(2)) {
2846*9880d681SAndroid Build Coastguard Worker     Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2847*9880d681SAndroid Build Coastguard Worker     for (User *U : MulVal->users()) {
2848*9880d681SAndroid Build Coastguard Worker       if (U == &I || U == OtherVal)
2849*9880d681SAndroid Build Coastguard Worker         continue;
2850*9880d681SAndroid Build Coastguard Worker       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2851*9880d681SAndroid Build Coastguard Worker         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
2852*9880d681SAndroid Build Coastguard Worker           IC.replaceInstUsesWith(*TI, Mul);
2853*9880d681SAndroid Build Coastguard Worker         else
2854*9880d681SAndroid Build Coastguard Worker           TI->setOperand(0, Mul);
2855*9880d681SAndroid Build Coastguard Worker       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2856*9880d681SAndroid Build Coastguard Worker         assert(BO->getOpcode() == Instruction::And);
2857*9880d681SAndroid Build Coastguard Worker         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2858*9880d681SAndroid Build Coastguard Worker         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2859*9880d681SAndroid Build Coastguard Worker         APInt ShortMask = CI->getValue().trunc(MulWidth);
2860*9880d681SAndroid Build Coastguard Worker         Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2861*9880d681SAndroid Build Coastguard Worker         Instruction *Zext =
2862*9880d681SAndroid Build Coastguard Worker             cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2863*9880d681SAndroid Build Coastguard Worker         IC.Worklist.Add(Zext);
2864*9880d681SAndroid Build Coastguard Worker         IC.replaceInstUsesWith(*BO, Zext);
2865*9880d681SAndroid Build Coastguard Worker       } else {
2866*9880d681SAndroid Build Coastguard Worker         llvm_unreachable("Unexpected Binary operation");
2867*9880d681SAndroid Build Coastguard Worker       }
2868*9880d681SAndroid Build Coastguard Worker       IC.Worklist.Add(cast<Instruction>(U));
2869*9880d681SAndroid Build Coastguard Worker     }
2870*9880d681SAndroid Build Coastguard Worker   }
2871*9880d681SAndroid Build Coastguard Worker   if (isa<Instruction>(OtherVal))
2872*9880d681SAndroid Build Coastguard Worker     IC.Worklist.Add(cast<Instruction>(OtherVal));
2873*9880d681SAndroid Build Coastguard Worker 
2874*9880d681SAndroid Build Coastguard Worker   // The original icmp gets replaced with the overflow value, maybe inverted
2875*9880d681SAndroid Build Coastguard Worker   // depending on predicate.
2876*9880d681SAndroid Build Coastguard Worker   bool Inverse = false;
2877*9880d681SAndroid Build Coastguard Worker   switch (I.getPredicate()) {
2878*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_NE:
2879*9880d681SAndroid Build Coastguard Worker     break;
2880*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_EQ:
2881*9880d681SAndroid Build Coastguard Worker     Inverse = true;
2882*9880d681SAndroid Build Coastguard Worker     break;
2883*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGT:
2884*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGE:
2885*9880d681SAndroid Build Coastguard Worker     if (I.getOperand(0) == MulVal)
2886*9880d681SAndroid Build Coastguard Worker       break;
2887*9880d681SAndroid Build Coastguard Worker     Inverse = true;
2888*9880d681SAndroid Build Coastguard Worker     break;
2889*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULT:
2890*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULE:
2891*9880d681SAndroid Build Coastguard Worker     if (I.getOperand(1) == MulVal)
2892*9880d681SAndroid Build Coastguard Worker       break;
2893*9880d681SAndroid Build Coastguard Worker     Inverse = true;
2894*9880d681SAndroid Build Coastguard Worker     break;
2895*9880d681SAndroid Build Coastguard Worker   default:
2896*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unexpected predicate");
2897*9880d681SAndroid Build Coastguard Worker   }
2898*9880d681SAndroid Build Coastguard Worker   if (Inverse) {
2899*9880d681SAndroid Build Coastguard Worker     Value *Res = Builder->CreateExtractValue(Call, 1);
2900*9880d681SAndroid Build Coastguard Worker     return BinaryOperator::CreateNot(Res);
2901*9880d681SAndroid Build Coastguard Worker   }
2902*9880d681SAndroid Build Coastguard Worker 
2903*9880d681SAndroid Build Coastguard Worker   return ExtractValueInst::Create(Call, 1);
2904*9880d681SAndroid Build Coastguard Worker }
2905*9880d681SAndroid Build Coastguard Worker 
2906*9880d681SAndroid Build Coastguard Worker /// When performing a comparison against a constant, it is possible that not all
2907*9880d681SAndroid Build Coastguard Worker /// the bits in the LHS are demanded. This helper method computes the mask that
2908*9880d681SAndroid Build Coastguard Worker /// IS demanded.
DemandedBitsLHSMask(ICmpInst & I,unsigned BitWidth,bool isSignCheck)2909*9880d681SAndroid Build Coastguard Worker static APInt DemandedBitsLHSMask(ICmpInst &I,
2910*9880d681SAndroid Build Coastguard Worker                                  unsigned BitWidth, bool isSignCheck) {
2911*9880d681SAndroid Build Coastguard Worker   if (isSignCheck)
2912*9880d681SAndroid Build Coastguard Worker     return APInt::getSignBit(BitWidth);
2913*9880d681SAndroid Build Coastguard Worker 
2914*9880d681SAndroid Build Coastguard Worker   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2915*9880d681SAndroid Build Coastguard Worker   if (!CI) return APInt::getAllOnesValue(BitWidth);
2916*9880d681SAndroid Build Coastguard Worker   const APInt &RHS = CI->getValue();
2917*9880d681SAndroid Build Coastguard Worker 
2918*9880d681SAndroid Build Coastguard Worker   switch (I.getPredicate()) {
2919*9880d681SAndroid Build Coastguard Worker   // For a UGT comparison, we don't care about any bits that
2920*9880d681SAndroid Build Coastguard Worker   // correspond to the trailing ones of the comparand.  The value of these
2921*9880d681SAndroid Build Coastguard Worker   // bits doesn't impact the outcome of the comparison, because any value
2922*9880d681SAndroid Build Coastguard Worker   // greater than the RHS must differ in a bit higher than these due to carry.
2923*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_UGT: {
2924*9880d681SAndroid Build Coastguard Worker     unsigned trailingOnes = RHS.countTrailingOnes();
2925*9880d681SAndroid Build Coastguard Worker     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2926*9880d681SAndroid Build Coastguard Worker     return ~lowBitsSet;
2927*9880d681SAndroid Build Coastguard Worker   }
2928*9880d681SAndroid Build Coastguard Worker 
2929*9880d681SAndroid Build Coastguard Worker   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2930*9880d681SAndroid Build Coastguard Worker   // Any value less than the RHS must differ in a higher bit because of carries.
2931*9880d681SAndroid Build Coastguard Worker   case ICmpInst::ICMP_ULT: {
2932*9880d681SAndroid Build Coastguard Worker     unsigned trailingZeros = RHS.countTrailingZeros();
2933*9880d681SAndroid Build Coastguard Worker     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2934*9880d681SAndroid Build Coastguard Worker     return ~lowBitsSet;
2935*9880d681SAndroid Build Coastguard Worker   }
2936*9880d681SAndroid Build Coastguard Worker 
2937*9880d681SAndroid Build Coastguard Worker   default:
2938*9880d681SAndroid Build Coastguard Worker     return APInt::getAllOnesValue(BitWidth);
2939*9880d681SAndroid Build Coastguard Worker   }
2940*9880d681SAndroid Build Coastguard Worker }
2941*9880d681SAndroid Build Coastguard Worker 
2942*9880d681SAndroid Build Coastguard Worker /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2943*9880d681SAndroid Build Coastguard Worker /// should be swapped.
2944*9880d681SAndroid Build Coastguard Worker /// The decision is based on how many times these two operands are reused
2945*9880d681SAndroid Build Coastguard Worker /// as subtract operands and their positions in those instructions.
2946*9880d681SAndroid Build Coastguard Worker /// The rational is that several architectures use the same instruction for
2947*9880d681SAndroid Build Coastguard Worker /// both subtract and cmp, thus it is better if the order of those operands
2948*9880d681SAndroid Build Coastguard Worker /// match.
2949*9880d681SAndroid Build Coastguard Worker /// \return true if Op0 and Op1 should be swapped.
swapMayExposeCSEOpportunities(const Value * Op0,const Value * Op1)2950*9880d681SAndroid Build Coastguard Worker static bool swapMayExposeCSEOpportunities(const Value * Op0,
2951*9880d681SAndroid Build Coastguard Worker                                           const Value * Op1) {
2952*9880d681SAndroid Build Coastguard Worker   // Filter out pointer value as those cannot appears directly in subtract.
2953*9880d681SAndroid Build Coastguard Worker   // FIXME: we may want to go through inttoptrs or bitcasts.
2954*9880d681SAndroid Build Coastguard Worker   if (Op0->getType()->isPointerTy())
2955*9880d681SAndroid Build Coastguard Worker     return false;
2956*9880d681SAndroid Build Coastguard Worker   // Count every uses of both Op0 and Op1 in a subtract.
2957*9880d681SAndroid Build Coastguard Worker   // Each time Op0 is the first operand, count -1: swapping is bad, the
2958*9880d681SAndroid Build Coastguard Worker   // subtract has already the same layout as the compare.
2959*9880d681SAndroid Build Coastguard Worker   // Each time Op0 is the second operand, count +1: swapping is good, the
2960*9880d681SAndroid Build Coastguard Worker   // subtract has a different layout as the compare.
2961*9880d681SAndroid Build Coastguard Worker   // At the end, if the benefit is greater than 0, Op0 should come second to
2962*9880d681SAndroid Build Coastguard Worker   // expose more CSE opportunities.
2963*9880d681SAndroid Build Coastguard Worker   int GlobalSwapBenefits = 0;
2964*9880d681SAndroid Build Coastguard Worker   for (const User *U : Op0->users()) {
2965*9880d681SAndroid Build Coastguard Worker     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
2966*9880d681SAndroid Build Coastguard Worker     if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2967*9880d681SAndroid Build Coastguard Worker       continue;
2968*9880d681SAndroid Build Coastguard Worker     // If Op0 is the first argument, this is not beneficial to swap the
2969*9880d681SAndroid Build Coastguard Worker     // arguments.
2970*9880d681SAndroid Build Coastguard Worker     int LocalSwapBenefits = -1;
2971*9880d681SAndroid Build Coastguard Worker     unsigned Op1Idx = 1;
2972*9880d681SAndroid Build Coastguard Worker     if (BinOp->getOperand(Op1Idx) == Op0) {
2973*9880d681SAndroid Build Coastguard Worker       Op1Idx = 0;
2974*9880d681SAndroid Build Coastguard Worker       LocalSwapBenefits = 1;
2975*9880d681SAndroid Build Coastguard Worker     }
2976*9880d681SAndroid Build Coastguard Worker     if (BinOp->getOperand(Op1Idx) != Op1)
2977*9880d681SAndroid Build Coastguard Worker       continue;
2978*9880d681SAndroid Build Coastguard Worker     GlobalSwapBenefits += LocalSwapBenefits;
2979*9880d681SAndroid Build Coastguard Worker   }
2980*9880d681SAndroid Build Coastguard Worker   return GlobalSwapBenefits > 0;
2981*9880d681SAndroid Build Coastguard Worker }
2982*9880d681SAndroid Build Coastguard Worker 
2983*9880d681SAndroid Build Coastguard Worker /// \brief Check that one use is in the same block as the definition and all
2984*9880d681SAndroid Build Coastguard Worker /// other uses are in blocks dominated by a given block
2985*9880d681SAndroid Build Coastguard Worker ///
2986*9880d681SAndroid Build Coastguard Worker /// \param DI Definition
2987*9880d681SAndroid Build Coastguard Worker /// \param UI Use
2988*9880d681SAndroid Build Coastguard Worker /// \param DB Block that must dominate all uses of \p DI outside
2989*9880d681SAndroid Build Coastguard Worker ///           the parent block
2990*9880d681SAndroid Build Coastguard Worker /// \return true when \p UI is the only use of \p DI in the parent block
2991*9880d681SAndroid Build Coastguard Worker /// and all other uses of \p DI are in blocks dominated by \p DB.
2992*9880d681SAndroid Build Coastguard Worker ///
dominatesAllUses(const Instruction * DI,const Instruction * UI,const BasicBlock * DB) const2993*9880d681SAndroid Build Coastguard Worker bool InstCombiner::dominatesAllUses(const Instruction *DI,
2994*9880d681SAndroid Build Coastguard Worker                                     const Instruction *UI,
2995*9880d681SAndroid Build Coastguard Worker                                     const BasicBlock *DB) const {
2996*9880d681SAndroid Build Coastguard Worker   assert(DI && UI && "Instruction not defined\n");
2997*9880d681SAndroid Build Coastguard Worker   // ignore incomplete definitions
2998*9880d681SAndroid Build Coastguard Worker   if (!DI->getParent())
2999*9880d681SAndroid Build Coastguard Worker     return false;
3000*9880d681SAndroid Build Coastguard Worker   // DI and UI must be in the same block
3001*9880d681SAndroid Build Coastguard Worker   if (DI->getParent() != UI->getParent())
3002*9880d681SAndroid Build Coastguard Worker     return false;
3003*9880d681SAndroid Build Coastguard Worker   // Protect from self-referencing blocks
3004*9880d681SAndroid Build Coastguard Worker   if (DI->getParent() == DB)
3005*9880d681SAndroid Build Coastguard Worker     return false;
3006*9880d681SAndroid Build Coastguard Worker   // DominatorTree available?
3007*9880d681SAndroid Build Coastguard Worker   if (!DT)
3008*9880d681SAndroid Build Coastguard Worker     return false;
3009*9880d681SAndroid Build Coastguard Worker   for (const User *U : DI->users()) {
3010*9880d681SAndroid Build Coastguard Worker     auto *Usr = cast<Instruction>(U);
3011*9880d681SAndroid Build Coastguard Worker     if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
3012*9880d681SAndroid Build Coastguard Worker       return false;
3013*9880d681SAndroid Build Coastguard Worker   }
3014*9880d681SAndroid Build Coastguard Worker   return true;
3015*9880d681SAndroid Build Coastguard Worker }
3016*9880d681SAndroid Build Coastguard Worker 
3017*9880d681SAndroid Build Coastguard Worker /// Return true when the instruction sequence within a block is select-cmp-br.
isChainSelectCmpBranch(const SelectInst * SI)3018*9880d681SAndroid Build Coastguard Worker static bool isChainSelectCmpBranch(const SelectInst *SI) {
3019*9880d681SAndroid Build Coastguard Worker   const BasicBlock *BB = SI->getParent();
3020*9880d681SAndroid Build Coastguard Worker   if (!BB)
3021*9880d681SAndroid Build Coastguard Worker     return false;
3022*9880d681SAndroid Build Coastguard Worker   auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3023*9880d681SAndroid Build Coastguard Worker   if (!BI || BI->getNumSuccessors() != 2)
3024*9880d681SAndroid Build Coastguard Worker     return false;
3025*9880d681SAndroid Build Coastguard Worker   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3026*9880d681SAndroid Build Coastguard Worker   if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3027*9880d681SAndroid Build Coastguard Worker     return false;
3028*9880d681SAndroid Build Coastguard Worker   return true;
3029*9880d681SAndroid Build Coastguard Worker }
3030*9880d681SAndroid Build Coastguard Worker 
3031*9880d681SAndroid Build Coastguard Worker /// \brief True when a select result is replaced by one of its operands
3032*9880d681SAndroid Build Coastguard Worker /// in select-icmp sequence. This will eventually result in the elimination
3033*9880d681SAndroid Build Coastguard Worker /// of the select.
3034*9880d681SAndroid Build Coastguard Worker ///
3035*9880d681SAndroid Build Coastguard Worker /// \param SI    Select instruction
3036*9880d681SAndroid Build Coastguard Worker /// \param Icmp  Compare instruction
3037*9880d681SAndroid Build Coastguard Worker /// \param SIOpd Operand that replaces the select
3038*9880d681SAndroid Build Coastguard Worker ///
3039*9880d681SAndroid Build Coastguard Worker /// Notes:
3040*9880d681SAndroid Build Coastguard Worker /// - The replacement is global and requires dominator information
3041*9880d681SAndroid Build Coastguard Worker /// - The caller is responsible for the actual replacement
3042*9880d681SAndroid Build Coastguard Worker ///
3043*9880d681SAndroid Build Coastguard Worker /// Example:
3044*9880d681SAndroid Build Coastguard Worker ///
3045*9880d681SAndroid Build Coastguard Worker /// entry:
3046*9880d681SAndroid Build Coastguard Worker ///  %4 = select i1 %3, %C* %0, %C* null
3047*9880d681SAndroid Build Coastguard Worker ///  %5 = icmp eq %C* %4, null
3048*9880d681SAndroid Build Coastguard Worker ///  br i1 %5, label %9, label %7
3049*9880d681SAndroid Build Coastguard Worker ///  ...
3050*9880d681SAndroid Build Coastguard Worker ///  ; <label>:7                                       ; preds = %entry
3051*9880d681SAndroid Build Coastguard Worker ///  %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3052*9880d681SAndroid Build Coastguard Worker ///  ...
3053*9880d681SAndroid Build Coastguard Worker ///
3054*9880d681SAndroid Build Coastguard Worker /// can be transformed to
3055*9880d681SAndroid Build Coastguard Worker ///
3056*9880d681SAndroid Build Coastguard Worker ///  %5 = icmp eq %C* %0, null
3057*9880d681SAndroid Build Coastguard Worker ///  %6 = select i1 %3, i1 %5, i1 true
3058*9880d681SAndroid Build Coastguard Worker ///  br i1 %6, label %9, label %7
3059*9880d681SAndroid Build Coastguard Worker ///  ...
3060*9880d681SAndroid Build Coastguard Worker ///  ; <label>:7                                       ; preds = %entry
3061*9880d681SAndroid Build Coastguard Worker ///  %8 = getelementptr inbounds %C* %0, i64 0, i32 0  // replace by %0!
3062*9880d681SAndroid Build Coastguard Worker ///
3063*9880d681SAndroid Build Coastguard Worker /// Similar when the first operand of the select is a constant or/and
3064*9880d681SAndroid Build Coastguard Worker /// the compare is for not equal rather than equal.
3065*9880d681SAndroid Build Coastguard Worker ///
3066*9880d681SAndroid Build Coastguard Worker /// NOTE: The function is only called when the select and compare constants
3067*9880d681SAndroid Build Coastguard Worker /// are equal, the optimization can work only for EQ predicates. This is not a
3068*9880d681SAndroid Build Coastguard Worker /// major restriction since a NE compare should be 'normalized' to an equal
3069*9880d681SAndroid Build Coastguard Worker /// compare, which usually happens in the combiner and test case
3070*9880d681SAndroid Build Coastguard Worker /// select-cmp-br.ll
3071*9880d681SAndroid Build Coastguard Worker /// checks for it.
replacedSelectWithOperand(SelectInst * SI,const ICmpInst * Icmp,const unsigned SIOpd)3072*9880d681SAndroid Build Coastguard Worker bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3073*9880d681SAndroid Build Coastguard Worker                                              const ICmpInst *Icmp,
3074*9880d681SAndroid Build Coastguard Worker                                              const unsigned SIOpd) {
3075*9880d681SAndroid Build Coastguard Worker   assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
3076*9880d681SAndroid Build Coastguard Worker   if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3077*9880d681SAndroid Build Coastguard Worker     BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3078*9880d681SAndroid Build Coastguard Worker     // The check for the unique predecessor is not the best that can be
3079*9880d681SAndroid Build Coastguard Worker     // done. But it protects efficiently against cases like  when SI's
3080*9880d681SAndroid Build Coastguard Worker     // home block has two successors, Succ and Succ1, and Succ1 predecessor
3081*9880d681SAndroid Build Coastguard Worker     // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3082*9880d681SAndroid Build Coastguard Worker     // replaced can be reached on either path. So the uniqueness check
3083*9880d681SAndroid Build Coastguard Worker     // guarantees that the path all uses of SI (outside SI's parent) are on
3084*9880d681SAndroid Build Coastguard Worker     // is disjoint from all other paths out of SI. But that information
3085*9880d681SAndroid Build Coastguard Worker     // is more expensive to compute, and the trade-off here is in favor
3086*9880d681SAndroid Build Coastguard Worker     // of compile-time.
3087*9880d681SAndroid Build Coastguard Worker     if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3088*9880d681SAndroid Build Coastguard Worker       NumSel++;
3089*9880d681SAndroid Build Coastguard Worker       SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3090*9880d681SAndroid Build Coastguard Worker       return true;
3091*9880d681SAndroid Build Coastguard Worker     }
3092*9880d681SAndroid Build Coastguard Worker   }
3093*9880d681SAndroid Build Coastguard Worker   return false;
3094*9880d681SAndroid Build Coastguard Worker }
3095*9880d681SAndroid Build Coastguard Worker 
3096*9880d681SAndroid Build Coastguard Worker /// If we have an icmp le or icmp ge instruction with a constant operand, turn
3097*9880d681SAndroid Build Coastguard Worker /// it into the appropriate icmp lt or icmp gt instruction. This transform
3098*9880d681SAndroid Build Coastguard Worker /// allows them to be folded in visitICmpInst.
canonicalizeCmpWithConstant(ICmpInst & I)3099*9880d681SAndroid Build Coastguard Worker static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3100*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate Pred = I.getPredicate();
3101*9880d681SAndroid Build Coastguard Worker   if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3102*9880d681SAndroid Build Coastguard Worker       Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3103*9880d681SAndroid Build Coastguard Worker     return nullptr;
3104*9880d681SAndroid Build Coastguard Worker 
3105*9880d681SAndroid Build Coastguard Worker   Value *Op0 = I.getOperand(0);
3106*9880d681SAndroid Build Coastguard Worker   Value *Op1 = I.getOperand(1);
3107*9880d681SAndroid Build Coastguard Worker   auto *Op1C = dyn_cast<Constant>(Op1);
3108*9880d681SAndroid Build Coastguard Worker   if (!Op1C)
3109*9880d681SAndroid Build Coastguard Worker     return nullptr;
3110*9880d681SAndroid Build Coastguard Worker 
3111*9880d681SAndroid Build Coastguard Worker   // Check if the constant operand can be safely incremented/decremented without
3112*9880d681SAndroid Build Coastguard Worker   // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3113*9880d681SAndroid Build Coastguard Worker   // the edge cases for us, so we just assert on them. For vectors, we must
3114*9880d681SAndroid Build Coastguard Worker   // handle the edge cases.
3115*9880d681SAndroid Build Coastguard Worker   Type *Op1Type = Op1->getType();
3116*9880d681SAndroid Build Coastguard Worker   bool IsSigned = I.isSigned();
3117*9880d681SAndroid Build Coastguard Worker   bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
3118*9880d681SAndroid Build Coastguard Worker   auto *CI = dyn_cast<ConstantInt>(Op1C);
3119*9880d681SAndroid Build Coastguard Worker   if (CI) {
3120*9880d681SAndroid Build Coastguard Worker     // A <= MAX -> TRUE ; A >= MIN -> TRUE
3121*9880d681SAndroid Build Coastguard Worker     assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3122*9880d681SAndroid Build Coastguard Worker   } else if (Op1Type->isVectorTy()) {
3123*9880d681SAndroid Build Coastguard Worker     // TODO? If the edge cases for vectors were guaranteed to be handled as they
3124*9880d681SAndroid Build Coastguard Worker     // are for scalar, we could remove the min/max checks. However, to do that,
3125*9880d681SAndroid Build Coastguard Worker     // we would have to use insertelement/shufflevector to replace edge values.
3126*9880d681SAndroid Build Coastguard Worker     unsigned NumElts = Op1Type->getVectorNumElements();
3127*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0; i != NumElts; ++i) {
3128*9880d681SAndroid Build Coastguard Worker       Constant *Elt = Op1C->getAggregateElement(i);
3129*9880d681SAndroid Build Coastguard Worker       if (!Elt)
3130*9880d681SAndroid Build Coastguard Worker         return nullptr;
3131*9880d681SAndroid Build Coastguard Worker 
3132*9880d681SAndroid Build Coastguard Worker       if (isa<UndefValue>(Elt))
3133*9880d681SAndroid Build Coastguard Worker         continue;
3134*9880d681SAndroid Build Coastguard Worker       // Bail out if we can't determine if this constant is min/max or if we
3135*9880d681SAndroid Build Coastguard Worker       // know that this constant is min/max.
3136*9880d681SAndroid Build Coastguard Worker       auto *CI = dyn_cast<ConstantInt>(Elt);
3137*9880d681SAndroid Build Coastguard Worker       if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3138*9880d681SAndroid Build Coastguard Worker         return nullptr;
3139*9880d681SAndroid Build Coastguard Worker     }
3140*9880d681SAndroid Build Coastguard Worker   } else {
3141*9880d681SAndroid Build Coastguard Worker     // ConstantExpr?
3142*9880d681SAndroid Build Coastguard Worker     return nullptr;
3143*9880d681SAndroid Build Coastguard Worker   }
3144*9880d681SAndroid Build Coastguard Worker 
3145*9880d681SAndroid Build Coastguard Worker   // Increment or decrement the constant and set the new comparison predicate:
3146*9880d681SAndroid Build Coastguard Worker   // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
3147*9880d681SAndroid Build Coastguard Worker   Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
3148*9880d681SAndroid Build Coastguard Worker   CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3149*9880d681SAndroid Build Coastguard Worker   NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3150*9880d681SAndroid Build Coastguard Worker   return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
3151*9880d681SAndroid Build Coastguard Worker }
3152*9880d681SAndroid Build Coastguard Worker 
visitICmpInst(ICmpInst & I)3153*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3154*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
3155*9880d681SAndroid Build Coastguard Worker   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3156*9880d681SAndroid Build Coastguard Worker   unsigned Op0Cplxity = getComplexity(Op0);
3157*9880d681SAndroid Build Coastguard Worker   unsigned Op1Cplxity = getComplexity(Op1);
3158*9880d681SAndroid Build Coastguard Worker 
3159*9880d681SAndroid Build Coastguard Worker   /// Orders the operands of the compare so that they are listed from most
3160*9880d681SAndroid Build Coastguard Worker   /// complex to least complex.  This puts constants before unary operators,
3161*9880d681SAndroid Build Coastguard Worker   /// before binary operators.
3162*9880d681SAndroid Build Coastguard Worker   if (Op0Cplxity < Op1Cplxity ||
3163*9880d681SAndroid Build Coastguard Worker       (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
3164*9880d681SAndroid Build Coastguard Worker     I.swapOperands();
3165*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
3166*9880d681SAndroid Build Coastguard Worker     Changed = true;
3167*9880d681SAndroid Build Coastguard Worker   }
3168*9880d681SAndroid Build Coastguard Worker 
3169*9880d681SAndroid Build Coastguard Worker   if (Value *V =
3170*9880d681SAndroid Build Coastguard Worker           SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
3171*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(I, V);
3172*9880d681SAndroid Build Coastguard Worker 
3173*9880d681SAndroid Build Coastguard Worker   // comparing -val or val with non-zero is the same as just comparing val
3174*9880d681SAndroid Build Coastguard Worker   // ie, abs(val) != 0 -> val != 0
3175*9880d681SAndroid Build Coastguard Worker   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
3176*9880d681SAndroid Build Coastguard Worker     Value *Cond, *SelectTrue, *SelectFalse;
3177*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
3178*9880d681SAndroid Build Coastguard Worker                             m_Value(SelectFalse)))) {
3179*9880d681SAndroid Build Coastguard Worker       if (Value *V = dyn_castNegVal(SelectTrue)) {
3180*9880d681SAndroid Build Coastguard Worker         if (V == SelectFalse)
3181*9880d681SAndroid Build Coastguard Worker           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3182*9880d681SAndroid Build Coastguard Worker       }
3183*9880d681SAndroid Build Coastguard Worker       else if (Value *V = dyn_castNegVal(SelectFalse)) {
3184*9880d681SAndroid Build Coastguard Worker         if (V == SelectTrue)
3185*9880d681SAndroid Build Coastguard Worker           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3186*9880d681SAndroid Build Coastguard Worker       }
3187*9880d681SAndroid Build Coastguard Worker     }
3188*9880d681SAndroid Build Coastguard Worker   }
3189*9880d681SAndroid Build Coastguard Worker 
3190*9880d681SAndroid Build Coastguard Worker   Type *Ty = Op0->getType();
3191*9880d681SAndroid Build Coastguard Worker 
3192*9880d681SAndroid Build Coastguard Worker   // icmp's with boolean values can always be turned into bitwise operations
3193*9880d681SAndroid Build Coastguard Worker   if (Ty->getScalarType()->isIntegerTy(1)) {
3194*9880d681SAndroid Build Coastguard Worker     switch (I.getPredicate()) {
3195*9880d681SAndroid Build Coastguard Worker     default: llvm_unreachable("Invalid icmp instruction!");
3196*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_EQ: {                // icmp eq i1 A, B -> ~(A^B)
3197*9880d681SAndroid Build Coastguard Worker       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
3198*9880d681SAndroid Build Coastguard Worker       return BinaryOperator::CreateNot(Xor);
3199*9880d681SAndroid Build Coastguard Worker     }
3200*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_NE:                  // icmp ne i1 A, B -> A^B
3201*9880d681SAndroid Build Coastguard Worker       return BinaryOperator::CreateXor(Op0, Op1);
3202*9880d681SAndroid Build Coastguard Worker 
3203*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGT:
3204*9880d681SAndroid Build Coastguard Worker       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
3205*9880d681SAndroid Build Coastguard Worker       // FALL THROUGH
3206*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULT:{                // icmp ult i1 A, B -> ~A & B
3207*9880d681SAndroid Build Coastguard Worker       Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
3208*9880d681SAndroid Build Coastguard Worker       return BinaryOperator::CreateAnd(Not, Op1);
3209*9880d681SAndroid Build Coastguard Worker     }
3210*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGT:
3211*9880d681SAndroid Build Coastguard Worker       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
3212*9880d681SAndroid Build Coastguard Worker       // FALL THROUGH
3213*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
3214*9880d681SAndroid Build Coastguard Worker       Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
3215*9880d681SAndroid Build Coastguard Worker       return BinaryOperator::CreateAnd(Not, Op0);
3216*9880d681SAndroid Build Coastguard Worker     }
3217*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGE:
3218*9880d681SAndroid Build Coastguard Worker       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
3219*9880d681SAndroid Build Coastguard Worker       // FALL THROUGH
3220*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULE: {               // icmp ule i1 A, B -> ~A | B
3221*9880d681SAndroid Build Coastguard Worker       Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
3222*9880d681SAndroid Build Coastguard Worker       return BinaryOperator::CreateOr(Not, Op1);
3223*9880d681SAndroid Build Coastguard Worker     }
3224*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGE:
3225*9880d681SAndroid Build Coastguard Worker       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
3226*9880d681SAndroid Build Coastguard Worker       // FALL THROUGH
3227*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLE: {               // icmp sle i1 A, B -> A | ~B
3228*9880d681SAndroid Build Coastguard Worker       Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
3229*9880d681SAndroid Build Coastguard Worker       return BinaryOperator::CreateOr(Not, Op0);
3230*9880d681SAndroid Build Coastguard Worker     }
3231*9880d681SAndroid Build Coastguard Worker     }
3232*9880d681SAndroid Build Coastguard Worker   }
3233*9880d681SAndroid Build Coastguard Worker 
3234*9880d681SAndroid Build Coastguard Worker   if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
3235*9880d681SAndroid Build Coastguard Worker     return NewICmp;
3236*9880d681SAndroid Build Coastguard Worker 
3237*9880d681SAndroid Build Coastguard Worker   unsigned BitWidth = 0;
3238*9880d681SAndroid Build Coastguard Worker   if (Ty->isIntOrIntVectorTy())
3239*9880d681SAndroid Build Coastguard Worker     BitWidth = Ty->getScalarSizeInBits();
3240*9880d681SAndroid Build Coastguard Worker   else // Get pointer size.
3241*9880d681SAndroid Build Coastguard Worker     BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
3242*9880d681SAndroid Build Coastguard Worker 
3243*9880d681SAndroid Build Coastguard Worker   bool isSignBit = false;
3244*9880d681SAndroid Build Coastguard Worker 
3245*9880d681SAndroid Build Coastguard Worker   // See if we are doing a comparison with a constant.
3246*9880d681SAndroid Build Coastguard Worker   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3247*9880d681SAndroid Build Coastguard Worker     Value *A = nullptr, *B = nullptr;
3248*9880d681SAndroid Build Coastguard Worker 
3249*9880d681SAndroid Build Coastguard Worker     // Match the following pattern, which is a common idiom when writing
3250*9880d681SAndroid Build Coastguard Worker     // overflow-safe integer arithmetic function.  The source performs an
3251*9880d681SAndroid Build Coastguard Worker     // addition in wider type, and explicitly checks for overflow using
3252*9880d681SAndroid Build Coastguard Worker     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
3253*9880d681SAndroid Build Coastguard Worker     // sadd_with_overflow intrinsic.
3254*9880d681SAndroid Build Coastguard Worker     //
3255*9880d681SAndroid Build Coastguard Worker     // TODO: This could probably be generalized to handle other overflow-safe
3256*9880d681SAndroid Build Coastguard Worker     // operations if we worked out the formulas to compute the appropriate
3257*9880d681SAndroid Build Coastguard Worker     // magic constants.
3258*9880d681SAndroid Build Coastguard Worker     //
3259*9880d681SAndroid Build Coastguard Worker     // sum = a + b
3260*9880d681SAndroid Build Coastguard Worker     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
3261*9880d681SAndroid Build Coastguard Worker     {
3262*9880d681SAndroid Build Coastguard Worker     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
3263*9880d681SAndroid Build Coastguard Worker     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
3264*9880d681SAndroid Build Coastguard Worker         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
3265*9880d681SAndroid Build Coastguard Worker       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
3266*9880d681SAndroid Build Coastguard Worker         return Res;
3267*9880d681SAndroid Build Coastguard Worker     }
3268*9880d681SAndroid Build Coastguard Worker 
3269*9880d681SAndroid Build Coastguard Worker     // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3270*9880d681SAndroid Build Coastguard Worker     if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3271*9880d681SAndroid Build Coastguard Worker       if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3272*9880d681SAndroid Build Coastguard Worker         SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3273*9880d681SAndroid Build Coastguard Worker         if (SPR.Flavor == SPF_SMIN) {
3274*9880d681SAndroid Build Coastguard Worker           if (isKnownPositive(A, DL))
3275*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(I.getPredicate(), B, CI);
3276*9880d681SAndroid Build Coastguard Worker           if (isKnownPositive(B, DL))
3277*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(I.getPredicate(), A, CI);
3278*9880d681SAndroid Build Coastguard Worker         }
3279*9880d681SAndroid Build Coastguard Worker       }
3280*9880d681SAndroid Build Coastguard Worker 
3281*9880d681SAndroid Build Coastguard Worker 
3282*9880d681SAndroid Build Coastguard Worker     // The following transforms are only 'worth it' if the only user of the
3283*9880d681SAndroid Build Coastguard Worker     // subtraction is the icmp.
3284*9880d681SAndroid Build Coastguard Worker     if (Op0->hasOneUse()) {
3285*9880d681SAndroid Build Coastguard Worker       // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3286*9880d681SAndroid Build Coastguard Worker       if (I.isEquality() && CI->isZero() &&
3287*9880d681SAndroid Build Coastguard Worker           match(Op0, m_Sub(m_Value(A), m_Value(B))))
3288*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), A, B);
3289*9880d681SAndroid Build Coastguard Worker 
3290*9880d681SAndroid Build Coastguard Worker       // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3291*9880d681SAndroid Build Coastguard Worker       if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3292*9880d681SAndroid Build Coastguard Worker           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3293*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3294*9880d681SAndroid Build Coastguard Worker 
3295*9880d681SAndroid Build Coastguard Worker       // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3296*9880d681SAndroid Build Coastguard Worker       if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3297*9880d681SAndroid Build Coastguard Worker           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3298*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3299*9880d681SAndroid Build Coastguard Worker 
3300*9880d681SAndroid Build Coastguard Worker       // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3301*9880d681SAndroid Build Coastguard Worker       if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3302*9880d681SAndroid Build Coastguard Worker           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3303*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3304*9880d681SAndroid Build Coastguard Worker 
3305*9880d681SAndroid Build Coastguard Worker       // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3306*9880d681SAndroid Build Coastguard Worker       if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3307*9880d681SAndroid Build Coastguard Worker           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3308*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
3309*9880d681SAndroid Build Coastguard Worker     }
3310*9880d681SAndroid Build Coastguard Worker 
3311*9880d681SAndroid Build Coastguard Worker     if (I.isEquality()) {
3312*9880d681SAndroid Build Coastguard Worker       ConstantInt *CI2;
3313*9880d681SAndroid Build Coastguard Worker       if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3314*9880d681SAndroid Build Coastguard Worker           match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
3315*9880d681SAndroid Build Coastguard Worker         // (icmp eq/ne (ashr/lshr const2, A), const1)
3316*9880d681SAndroid Build Coastguard Worker         if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
3317*9880d681SAndroid Build Coastguard Worker           return Inst;
3318*9880d681SAndroid Build Coastguard Worker       }
3319*9880d681SAndroid Build Coastguard Worker       if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3320*9880d681SAndroid Build Coastguard Worker         // (icmp eq/ne (shl const2, A), const1)
3321*9880d681SAndroid Build Coastguard Worker         if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
3322*9880d681SAndroid Build Coastguard Worker           return Inst;
3323*9880d681SAndroid Build Coastguard Worker       }
3324*9880d681SAndroid Build Coastguard Worker     }
3325*9880d681SAndroid Build Coastguard Worker 
3326*9880d681SAndroid Build Coastguard Worker     // If this comparison is a normal comparison, it demands all
3327*9880d681SAndroid Build Coastguard Worker     // bits, if it is a sign bit comparison, it only demands the sign bit.
3328*9880d681SAndroid Build Coastguard Worker     bool UnusedBit;
3329*9880d681SAndroid Build Coastguard Worker     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
3330*9880d681SAndroid Build Coastguard Worker 
3331*9880d681SAndroid Build Coastguard Worker     // Canonicalize icmp instructions based on dominating conditions.
3332*9880d681SAndroid Build Coastguard Worker     BasicBlock *Parent = I.getParent();
3333*9880d681SAndroid Build Coastguard Worker     BasicBlock *Dom = Parent->getSinglePredecessor();
3334*9880d681SAndroid Build Coastguard Worker     auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3335*9880d681SAndroid Build Coastguard Worker     ICmpInst::Predicate Pred;
3336*9880d681SAndroid Build Coastguard Worker     BasicBlock *TrueBB, *FalseBB;
3337*9880d681SAndroid Build Coastguard Worker     ConstantInt *CI2;
3338*9880d681SAndroid Build Coastguard Worker     if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3339*9880d681SAndroid Build Coastguard Worker                              TrueBB, FalseBB)) &&
3340*9880d681SAndroid Build Coastguard Worker         TrueBB != FalseBB) {
3341*9880d681SAndroid Build Coastguard Worker       ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3342*9880d681SAndroid Build Coastguard Worker                                                               CI->getValue());
3343*9880d681SAndroid Build Coastguard Worker       ConstantRange DominatingCR =
3344*9880d681SAndroid Build Coastguard Worker           (Parent == TrueBB)
3345*9880d681SAndroid Build Coastguard Worker               ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3346*9880d681SAndroid Build Coastguard Worker               : ConstantRange::makeExactICmpRegion(
3347*9880d681SAndroid Build Coastguard Worker                     CmpInst::getInversePredicate(Pred), CI2->getValue());
3348*9880d681SAndroid Build Coastguard Worker       ConstantRange Intersection = DominatingCR.intersectWith(CR);
3349*9880d681SAndroid Build Coastguard Worker       ConstantRange Difference = DominatingCR.difference(CR);
3350*9880d681SAndroid Build Coastguard Worker       if (Intersection.isEmptySet())
3351*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getFalse());
3352*9880d681SAndroid Build Coastguard Worker       if (Difference.isEmptySet())
3353*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getTrue());
3354*9880d681SAndroid Build Coastguard Worker       // Canonicalizing a sign bit comparison that gets used in a branch,
3355*9880d681SAndroid Build Coastguard Worker       // pessimizes codegen by generating branch on zero instruction instead
3356*9880d681SAndroid Build Coastguard Worker       // of a test and branch. So we avoid canonicalizing in such situations
3357*9880d681SAndroid Build Coastguard Worker       // because test and branch instruction has better branch displacement
3358*9880d681SAndroid Build Coastguard Worker       // than compare and branch instruction.
3359*9880d681SAndroid Build Coastguard Worker       if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3360*9880d681SAndroid Build Coastguard Worker         if (auto *AI = Intersection.getSingleElement())
3361*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3362*9880d681SAndroid Build Coastguard Worker         if (auto *AD = Difference.getSingleElement())
3363*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3364*9880d681SAndroid Build Coastguard Worker       }
3365*9880d681SAndroid Build Coastguard Worker     }
3366*9880d681SAndroid Build Coastguard Worker   }
3367*9880d681SAndroid Build Coastguard Worker 
3368*9880d681SAndroid Build Coastguard Worker   // See if we can fold the comparison based on range information we can get
3369*9880d681SAndroid Build Coastguard Worker   // by checking whether bits are known to be zero or one in the input.
3370*9880d681SAndroid Build Coastguard Worker   if (BitWidth != 0) {
3371*9880d681SAndroid Build Coastguard Worker     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3372*9880d681SAndroid Build Coastguard Worker     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3373*9880d681SAndroid Build Coastguard Worker 
3374*9880d681SAndroid Build Coastguard Worker     if (SimplifyDemandedBits(I.getOperandUse(0),
3375*9880d681SAndroid Build Coastguard Worker                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
3376*9880d681SAndroid Build Coastguard Worker                              Op0KnownZero, Op0KnownOne, 0))
3377*9880d681SAndroid Build Coastguard Worker       return &I;
3378*9880d681SAndroid Build Coastguard Worker     if (SimplifyDemandedBits(I.getOperandUse(1),
3379*9880d681SAndroid Build Coastguard Worker                              APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3380*9880d681SAndroid Build Coastguard Worker                              Op1KnownOne, 0))
3381*9880d681SAndroid Build Coastguard Worker       return &I;
3382*9880d681SAndroid Build Coastguard Worker 
3383*9880d681SAndroid Build Coastguard Worker     // Given the known and unknown bits, compute a range that the LHS could be
3384*9880d681SAndroid Build Coastguard Worker     // in.  Compute the Min, Max and RHS values based on the known bits. For the
3385*9880d681SAndroid Build Coastguard Worker     // EQ and NE we use unsigned values.
3386*9880d681SAndroid Build Coastguard Worker     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3387*9880d681SAndroid Build Coastguard Worker     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3388*9880d681SAndroid Build Coastguard Worker     if (I.isSigned()) {
3389*9880d681SAndroid Build Coastguard Worker       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3390*9880d681SAndroid Build Coastguard Worker                                              Op0Min, Op0Max);
3391*9880d681SAndroid Build Coastguard Worker       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3392*9880d681SAndroid Build Coastguard Worker                                              Op1Min, Op1Max);
3393*9880d681SAndroid Build Coastguard Worker     } else {
3394*9880d681SAndroid Build Coastguard Worker       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3395*9880d681SAndroid Build Coastguard Worker                                                Op0Min, Op0Max);
3396*9880d681SAndroid Build Coastguard Worker       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3397*9880d681SAndroid Build Coastguard Worker                                                Op1Min, Op1Max);
3398*9880d681SAndroid Build Coastguard Worker     }
3399*9880d681SAndroid Build Coastguard Worker 
3400*9880d681SAndroid Build Coastguard Worker     // If Min and Max are known to be the same, then SimplifyDemandedBits
3401*9880d681SAndroid Build Coastguard Worker     // figured out that the LHS is a constant.  Just constant fold this now so
3402*9880d681SAndroid Build Coastguard Worker     // that code below can assume that Min != Max.
3403*9880d681SAndroid Build Coastguard Worker     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3404*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(I.getPredicate(),
3405*9880d681SAndroid Build Coastguard Worker                           ConstantInt::get(Op0->getType(), Op0Min), Op1);
3406*9880d681SAndroid Build Coastguard Worker     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3407*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(I.getPredicate(), Op0,
3408*9880d681SAndroid Build Coastguard Worker                           ConstantInt::get(Op1->getType(), Op1Min));
3409*9880d681SAndroid Build Coastguard Worker 
3410*9880d681SAndroid Build Coastguard Worker     // Based on the range information we know about the LHS, see if we can
3411*9880d681SAndroid Build Coastguard Worker     // simplify this comparison.  For example, (x&4) < 8 is always true.
3412*9880d681SAndroid Build Coastguard Worker     switch (I.getPredicate()) {
3413*9880d681SAndroid Build Coastguard Worker     default: llvm_unreachable("Unknown icmp opcode!");
3414*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_EQ: {
3415*9880d681SAndroid Build Coastguard Worker       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
3416*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3417*9880d681SAndroid Build Coastguard Worker 
3418*9880d681SAndroid Build Coastguard Worker       // If all bits are known zero except for one, then we know at most one
3419*9880d681SAndroid Build Coastguard Worker       // bit is set.   If the comparison is against zero, then this is a check
3420*9880d681SAndroid Build Coastguard Worker       // to see if *that* bit is set.
3421*9880d681SAndroid Build Coastguard Worker       APInt Op0KnownZeroInverted = ~Op0KnownZero;
3422*9880d681SAndroid Build Coastguard Worker       if (~Op1KnownZero == 0) {
3423*9880d681SAndroid Build Coastguard Worker         // If the LHS is an AND with the same constant, look through it.
3424*9880d681SAndroid Build Coastguard Worker         Value *LHS = nullptr;
3425*9880d681SAndroid Build Coastguard Worker         ConstantInt *LHSC = nullptr;
3426*9880d681SAndroid Build Coastguard Worker         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3427*9880d681SAndroid Build Coastguard Worker             LHSC->getValue() != Op0KnownZeroInverted)
3428*9880d681SAndroid Build Coastguard Worker           LHS = Op0;
3429*9880d681SAndroid Build Coastguard Worker 
3430*9880d681SAndroid Build Coastguard Worker         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
3431*9880d681SAndroid Build Coastguard Worker         // then turn "((1 << x)&8) == 0" into "x != 3".
3432*9880d681SAndroid Build Coastguard Worker         // or turn "((1 << x)&7) == 0" into "x > 2".
3433*9880d681SAndroid Build Coastguard Worker         Value *X = nullptr;
3434*9880d681SAndroid Build Coastguard Worker         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
3435*9880d681SAndroid Build Coastguard Worker           APInt ValToCheck = Op0KnownZeroInverted;
3436*9880d681SAndroid Build Coastguard Worker           if (ValToCheck.isPowerOf2()) {
3437*9880d681SAndroid Build Coastguard Worker             unsigned CmpVal = ValToCheck.countTrailingZeros();
3438*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICmpInst::ICMP_NE, X,
3439*9880d681SAndroid Build Coastguard Worker                                 ConstantInt::get(X->getType(), CmpVal));
3440*9880d681SAndroid Build Coastguard Worker           } else if ((++ValToCheck).isPowerOf2()) {
3441*9880d681SAndroid Build Coastguard Worker             unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3442*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICmpInst::ICMP_UGT, X,
3443*9880d681SAndroid Build Coastguard Worker                                 ConstantInt::get(X->getType(), CmpVal));
3444*9880d681SAndroid Build Coastguard Worker           }
3445*9880d681SAndroid Build Coastguard Worker         }
3446*9880d681SAndroid Build Coastguard Worker 
3447*9880d681SAndroid Build Coastguard Worker         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
3448*9880d681SAndroid Build Coastguard Worker         // then turn "((8 >>u x)&1) == 0" into "x != 3".
3449*9880d681SAndroid Build Coastguard Worker         const APInt *CI;
3450*9880d681SAndroid Build Coastguard Worker         if (Op0KnownZeroInverted == 1 &&
3451*9880d681SAndroid Build Coastguard Worker             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
3452*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_NE, X,
3453*9880d681SAndroid Build Coastguard Worker                               ConstantInt::get(X->getType(),
3454*9880d681SAndroid Build Coastguard Worker                                                CI->countTrailingZeros()));
3455*9880d681SAndroid Build Coastguard Worker       }
3456*9880d681SAndroid Build Coastguard Worker       break;
3457*9880d681SAndroid Build Coastguard Worker     }
3458*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_NE: {
3459*9880d681SAndroid Build Coastguard Worker       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
3460*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3461*9880d681SAndroid Build Coastguard Worker 
3462*9880d681SAndroid Build Coastguard Worker       // If all bits are known zero except for one, then we know at most one
3463*9880d681SAndroid Build Coastguard Worker       // bit is set.   If the comparison is against zero, then this is a check
3464*9880d681SAndroid Build Coastguard Worker       // to see if *that* bit is set.
3465*9880d681SAndroid Build Coastguard Worker       APInt Op0KnownZeroInverted = ~Op0KnownZero;
3466*9880d681SAndroid Build Coastguard Worker       if (~Op1KnownZero == 0) {
3467*9880d681SAndroid Build Coastguard Worker         // If the LHS is an AND with the same constant, look through it.
3468*9880d681SAndroid Build Coastguard Worker         Value *LHS = nullptr;
3469*9880d681SAndroid Build Coastguard Worker         ConstantInt *LHSC = nullptr;
3470*9880d681SAndroid Build Coastguard Worker         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3471*9880d681SAndroid Build Coastguard Worker             LHSC->getValue() != Op0KnownZeroInverted)
3472*9880d681SAndroid Build Coastguard Worker           LHS = Op0;
3473*9880d681SAndroid Build Coastguard Worker 
3474*9880d681SAndroid Build Coastguard Worker         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
3475*9880d681SAndroid Build Coastguard Worker         // then turn "((1 << x)&8) != 0" into "x == 3".
3476*9880d681SAndroid Build Coastguard Worker         // or turn "((1 << x)&7) != 0" into "x < 3".
3477*9880d681SAndroid Build Coastguard Worker         Value *X = nullptr;
3478*9880d681SAndroid Build Coastguard Worker         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
3479*9880d681SAndroid Build Coastguard Worker           APInt ValToCheck = Op0KnownZeroInverted;
3480*9880d681SAndroid Build Coastguard Worker           if (ValToCheck.isPowerOf2()) {
3481*9880d681SAndroid Build Coastguard Worker             unsigned CmpVal = ValToCheck.countTrailingZeros();
3482*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICmpInst::ICMP_EQ, X,
3483*9880d681SAndroid Build Coastguard Worker                                 ConstantInt::get(X->getType(), CmpVal));
3484*9880d681SAndroid Build Coastguard Worker           } else if ((++ValToCheck).isPowerOf2()) {
3485*9880d681SAndroid Build Coastguard Worker             unsigned CmpVal = ValToCheck.countTrailingZeros();
3486*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(ICmpInst::ICMP_ULT, X,
3487*9880d681SAndroid Build Coastguard Worker                                 ConstantInt::get(X->getType(), CmpVal));
3488*9880d681SAndroid Build Coastguard Worker           }
3489*9880d681SAndroid Build Coastguard Worker         }
3490*9880d681SAndroid Build Coastguard Worker 
3491*9880d681SAndroid Build Coastguard Worker         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
3492*9880d681SAndroid Build Coastguard Worker         // then turn "((8 >>u x)&1) != 0" into "x == 3".
3493*9880d681SAndroid Build Coastguard Worker         const APInt *CI;
3494*9880d681SAndroid Build Coastguard Worker         if (Op0KnownZeroInverted == 1 &&
3495*9880d681SAndroid Build Coastguard Worker             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
3496*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_EQ, X,
3497*9880d681SAndroid Build Coastguard Worker                               ConstantInt::get(X->getType(),
3498*9880d681SAndroid Build Coastguard Worker                                                CI->countTrailingZeros()));
3499*9880d681SAndroid Build Coastguard Worker       }
3500*9880d681SAndroid Build Coastguard Worker       break;
3501*9880d681SAndroid Build Coastguard Worker     }
3502*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULT:
3503*9880d681SAndroid Build Coastguard Worker       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
3504*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3505*9880d681SAndroid Build Coastguard Worker       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
3506*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3507*9880d681SAndroid Build Coastguard Worker       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
3508*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3509*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3510*9880d681SAndroid Build Coastguard Worker         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
3511*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3512*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CI->getValue()-1));
3513*9880d681SAndroid Build Coastguard Worker 
3514*9880d681SAndroid Build Coastguard Worker         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
3515*9880d681SAndroid Build Coastguard Worker         if (CI->isMinValue(true))
3516*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3517*9880d681SAndroid Build Coastguard Worker                            Constant::getAllOnesValue(Op0->getType()));
3518*9880d681SAndroid Build Coastguard Worker       }
3519*9880d681SAndroid Build Coastguard Worker       break;
3520*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGT:
3521*9880d681SAndroid Build Coastguard Worker       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
3522*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3523*9880d681SAndroid Build Coastguard Worker       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
3524*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3525*9880d681SAndroid Build Coastguard Worker 
3526*9880d681SAndroid Build Coastguard Worker       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
3527*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3528*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3529*9880d681SAndroid Build Coastguard Worker         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
3530*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3531*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CI->getValue()+1));
3532*9880d681SAndroid Build Coastguard Worker 
3533*9880d681SAndroid Build Coastguard Worker         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
3534*9880d681SAndroid Build Coastguard Worker         if (CI->isMaxValue(true))
3535*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3536*9880d681SAndroid Build Coastguard Worker                               Constant::getNullValue(Op0->getType()));
3537*9880d681SAndroid Build Coastguard Worker       }
3538*9880d681SAndroid Build Coastguard Worker       break;
3539*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLT:
3540*9880d681SAndroid Build Coastguard Worker       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
3541*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3542*9880d681SAndroid Build Coastguard Worker       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
3543*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3544*9880d681SAndroid Build Coastguard Worker       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
3545*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3546*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3547*9880d681SAndroid Build Coastguard Worker         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
3548*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3549*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CI->getValue()-1));
3550*9880d681SAndroid Build Coastguard Worker       }
3551*9880d681SAndroid Build Coastguard Worker       break;
3552*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGT:
3553*9880d681SAndroid Build Coastguard Worker       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
3554*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3555*9880d681SAndroid Build Coastguard Worker       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
3556*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3557*9880d681SAndroid Build Coastguard Worker 
3558*9880d681SAndroid Build Coastguard Worker       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
3559*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3560*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3561*9880d681SAndroid Build Coastguard Worker         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
3562*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3563*9880d681SAndroid Build Coastguard Worker                               Builder->getInt(CI->getValue()+1));
3564*9880d681SAndroid Build Coastguard Worker       }
3565*9880d681SAndroid Build Coastguard Worker       break;
3566*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGE:
3567*9880d681SAndroid Build Coastguard Worker       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3568*9880d681SAndroid Build Coastguard Worker       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
3569*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3570*9880d681SAndroid Build Coastguard Worker       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
3571*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3572*9880d681SAndroid Build Coastguard Worker       break;
3573*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLE:
3574*9880d681SAndroid Build Coastguard Worker       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3575*9880d681SAndroid Build Coastguard Worker       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
3576*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3577*9880d681SAndroid Build Coastguard Worker       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
3578*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3579*9880d681SAndroid Build Coastguard Worker       break;
3580*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGE:
3581*9880d681SAndroid Build Coastguard Worker       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3582*9880d681SAndroid Build Coastguard Worker       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
3583*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3584*9880d681SAndroid Build Coastguard Worker       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
3585*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3586*9880d681SAndroid Build Coastguard Worker       break;
3587*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULE:
3588*9880d681SAndroid Build Coastguard Worker       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3589*9880d681SAndroid Build Coastguard Worker       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
3590*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3591*9880d681SAndroid Build Coastguard Worker       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
3592*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3593*9880d681SAndroid Build Coastguard Worker       break;
3594*9880d681SAndroid Build Coastguard Worker     }
3595*9880d681SAndroid Build Coastguard Worker 
3596*9880d681SAndroid Build Coastguard Worker     // Turn a signed comparison into an unsigned one if both operands
3597*9880d681SAndroid Build Coastguard Worker     // are known to have the same sign.
3598*9880d681SAndroid Build Coastguard Worker     if (I.isSigned() &&
3599*9880d681SAndroid Build Coastguard Worker         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3600*9880d681SAndroid Build Coastguard Worker          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3601*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3602*9880d681SAndroid Build Coastguard Worker   }
3603*9880d681SAndroid Build Coastguard Worker 
3604*9880d681SAndroid Build Coastguard Worker   // Test if the ICmpInst instruction is used exclusively by a select as
3605*9880d681SAndroid Build Coastguard Worker   // part of a minimum or maximum operation. If so, refrain from doing
3606*9880d681SAndroid Build Coastguard Worker   // any other folding. This helps out other analyses which understand
3607*9880d681SAndroid Build Coastguard Worker   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3608*9880d681SAndroid Build Coastguard Worker   // and CodeGen. And in this case, at least one of the comparison
3609*9880d681SAndroid Build Coastguard Worker   // operands has at least one user besides the compare (the select),
3610*9880d681SAndroid Build Coastguard Worker   // which would often largely negate the benefit of folding anyway.
3611*9880d681SAndroid Build Coastguard Worker   if (I.hasOneUse())
3612*9880d681SAndroid Build Coastguard Worker     if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
3613*9880d681SAndroid Build Coastguard Worker       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3614*9880d681SAndroid Build Coastguard Worker           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
3615*9880d681SAndroid Build Coastguard Worker         return nullptr;
3616*9880d681SAndroid Build Coastguard Worker 
3617*9880d681SAndroid Build Coastguard Worker   // See if we are doing a comparison between a constant and an instruction that
3618*9880d681SAndroid Build Coastguard Worker   // can be folded into the comparison.
3619*9880d681SAndroid Build Coastguard Worker   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3620*9880d681SAndroid Build Coastguard Worker     Value *A = nullptr, *B = nullptr;
3621*9880d681SAndroid Build Coastguard Worker     // Since the RHS is a ConstantInt (CI), if the left hand side is an
3622*9880d681SAndroid Build Coastguard Worker     // instruction, see if that instruction also has constants so that the
3623*9880d681SAndroid Build Coastguard Worker     // instruction can be folded into the icmp
3624*9880d681SAndroid Build Coastguard Worker     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3625*9880d681SAndroid Build Coastguard Worker       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3626*9880d681SAndroid Build Coastguard Worker         return Res;
3627*9880d681SAndroid Build Coastguard Worker 
3628*9880d681SAndroid Build Coastguard Worker     // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3629*9880d681SAndroid Build Coastguard Worker     if (I.isEquality() && CI->isZero() &&
3630*9880d681SAndroid Build Coastguard Worker         match(Op0, m_UDiv(m_Value(A), m_Value(B)))) {
3631*9880d681SAndroid Build Coastguard Worker       ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_EQ
3632*9880d681SAndroid Build Coastguard Worker                                      ? ICmpInst::ICMP_UGT
3633*9880d681SAndroid Build Coastguard Worker                                      : ICmpInst::ICMP_ULE;
3634*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, B, A);
3635*9880d681SAndroid Build Coastguard Worker     }
3636*9880d681SAndroid Build Coastguard Worker   }
3637*9880d681SAndroid Build Coastguard Worker 
3638*9880d681SAndroid Build Coastguard Worker   // Handle icmp with constant (but not simple integer constant) RHS
3639*9880d681SAndroid Build Coastguard Worker   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3640*9880d681SAndroid Build Coastguard Worker     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3641*9880d681SAndroid Build Coastguard Worker       switch (LHSI->getOpcode()) {
3642*9880d681SAndroid Build Coastguard Worker       case Instruction::GetElementPtr:
3643*9880d681SAndroid Build Coastguard Worker           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3644*9880d681SAndroid Build Coastguard Worker         if (RHSC->isNullValue() &&
3645*9880d681SAndroid Build Coastguard Worker             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3646*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3647*9880d681SAndroid Build Coastguard Worker                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
3648*9880d681SAndroid Build Coastguard Worker         break;
3649*9880d681SAndroid Build Coastguard Worker       case Instruction::PHI:
3650*9880d681SAndroid Build Coastguard Worker         // Only fold icmp into the PHI if the phi and icmp are in the same
3651*9880d681SAndroid Build Coastguard Worker         // block.  If in the same block, we're encouraging jump threading.  If
3652*9880d681SAndroid Build Coastguard Worker         // not, we are just pessimizing the code by making an i1 phi.
3653*9880d681SAndroid Build Coastguard Worker         if (LHSI->getParent() == I.getParent())
3654*9880d681SAndroid Build Coastguard Worker           if (Instruction *NV = FoldOpIntoPhi(I))
3655*9880d681SAndroid Build Coastguard Worker             return NV;
3656*9880d681SAndroid Build Coastguard Worker         break;
3657*9880d681SAndroid Build Coastguard Worker       case Instruction::Select: {
3658*9880d681SAndroid Build Coastguard Worker         // If either operand of the select is a constant, we can fold the
3659*9880d681SAndroid Build Coastguard Worker         // comparison into the select arms, which will cause one to be
3660*9880d681SAndroid Build Coastguard Worker         // constant folded and the select turned into a bitwise or.
3661*9880d681SAndroid Build Coastguard Worker         Value *Op1 = nullptr, *Op2 = nullptr;
3662*9880d681SAndroid Build Coastguard Worker         ConstantInt *CI = nullptr;
3663*9880d681SAndroid Build Coastguard Worker         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3664*9880d681SAndroid Build Coastguard Worker           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3665*9880d681SAndroid Build Coastguard Worker           CI = dyn_cast<ConstantInt>(Op1);
3666*9880d681SAndroid Build Coastguard Worker         }
3667*9880d681SAndroid Build Coastguard Worker         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3668*9880d681SAndroid Build Coastguard Worker           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
3669*9880d681SAndroid Build Coastguard Worker           CI = dyn_cast<ConstantInt>(Op2);
3670*9880d681SAndroid Build Coastguard Worker         }
3671*9880d681SAndroid Build Coastguard Worker 
3672*9880d681SAndroid Build Coastguard Worker         // We only want to perform this transformation if it will not lead to
3673*9880d681SAndroid Build Coastguard Worker         // additional code. This is true if either both sides of the select
3674*9880d681SAndroid Build Coastguard Worker         // fold to a constant (in which case the icmp is replaced with a select
3675*9880d681SAndroid Build Coastguard Worker         // which will usually simplify) or this is the only user of the
3676*9880d681SAndroid Build Coastguard Worker         // select (in which case we are trading a select+icmp for a simpler
3677*9880d681SAndroid Build Coastguard Worker         // select+icmp) or all uses of the select can be replaced based on
3678*9880d681SAndroid Build Coastguard Worker         // dominance information ("Global cases").
3679*9880d681SAndroid Build Coastguard Worker         bool Transform = false;
3680*9880d681SAndroid Build Coastguard Worker         if (Op1 && Op2)
3681*9880d681SAndroid Build Coastguard Worker           Transform = true;
3682*9880d681SAndroid Build Coastguard Worker         else if (Op1 || Op2) {
3683*9880d681SAndroid Build Coastguard Worker           // Local case
3684*9880d681SAndroid Build Coastguard Worker           if (LHSI->hasOneUse())
3685*9880d681SAndroid Build Coastguard Worker             Transform = true;
3686*9880d681SAndroid Build Coastguard Worker           // Global cases
3687*9880d681SAndroid Build Coastguard Worker           else if (CI && !CI->isZero())
3688*9880d681SAndroid Build Coastguard Worker             // When Op1 is constant try replacing select with second operand.
3689*9880d681SAndroid Build Coastguard Worker             // Otherwise Op2 is constant and try replacing select with first
3690*9880d681SAndroid Build Coastguard Worker             // operand.
3691*9880d681SAndroid Build Coastguard Worker             Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3692*9880d681SAndroid Build Coastguard Worker                                                   Op1 ? 2 : 1);
3693*9880d681SAndroid Build Coastguard Worker         }
3694*9880d681SAndroid Build Coastguard Worker         if (Transform) {
3695*9880d681SAndroid Build Coastguard Worker           if (!Op1)
3696*9880d681SAndroid Build Coastguard Worker             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3697*9880d681SAndroid Build Coastguard Worker                                       RHSC, I.getName());
3698*9880d681SAndroid Build Coastguard Worker           if (!Op2)
3699*9880d681SAndroid Build Coastguard Worker             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3700*9880d681SAndroid Build Coastguard Worker                                       RHSC, I.getName());
3701*9880d681SAndroid Build Coastguard Worker           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3702*9880d681SAndroid Build Coastguard Worker         }
3703*9880d681SAndroid Build Coastguard Worker         break;
3704*9880d681SAndroid Build Coastguard Worker       }
3705*9880d681SAndroid Build Coastguard Worker       case Instruction::IntToPtr:
3706*9880d681SAndroid Build Coastguard Worker         // icmp pred inttoptr(X), null -> icmp pred X, 0
3707*9880d681SAndroid Build Coastguard Worker         if (RHSC->isNullValue() &&
3708*9880d681SAndroid Build Coastguard Worker             DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3709*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3710*9880d681SAndroid Build Coastguard Worker                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
3711*9880d681SAndroid Build Coastguard Worker         break;
3712*9880d681SAndroid Build Coastguard Worker 
3713*9880d681SAndroid Build Coastguard Worker       case Instruction::Load:
3714*9880d681SAndroid Build Coastguard Worker         // Try to optimize things like "A[i] > 4" to index computations.
3715*9880d681SAndroid Build Coastguard Worker         if (GetElementPtrInst *GEP =
3716*9880d681SAndroid Build Coastguard Worker               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3717*9880d681SAndroid Build Coastguard Worker           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3718*9880d681SAndroid Build Coastguard Worker             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3719*9880d681SAndroid Build Coastguard Worker                 !cast<LoadInst>(LHSI)->isVolatile())
3720*9880d681SAndroid Build Coastguard Worker               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3721*9880d681SAndroid Build Coastguard Worker                 return Res;
3722*9880d681SAndroid Build Coastguard Worker         }
3723*9880d681SAndroid Build Coastguard Worker         break;
3724*9880d681SAndroid Build Coastguard Worker       }
3725*9880d681SAndroid Build Coastguard Worker   }
3726*9880d681SAndroid Build Coastguard Worker 
3727*9880d681SAndroid Build Coastguard Worker   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3728*9880d681SAndroid Build Coastguard Worker   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3729*9880d681SAndroid Build Coastguard Worker     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3730*9880d681SAndroid Build Coastguard Worker       return NI;
3731*9880d681SAndroid Build Coastguard Worker   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3732*9880d681SAndroid Build Coastguard Worker     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3733*9880d681SAndroid Build Coastguard Worker                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3734*9880d681SAndroid Build Coastguard Worker       return NI;
3735*9880d681SAndroid Build Coastguard Worker 
3736*9880d681SAndroid Build Coastguard Worker   // Try to optimize equality comparisons against alloca-based pointers.
3737*9880d681SAndroid Build Coastguard Worker   if (Op0->getType()->isPointerTy() && I.isEquality()) {
3738*9880d681SAndroid Build Coastguard Worker     assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3739*9880d681SAndroid Build Coastguard Worker     if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
3740*9880d681SAndroid Build Coastguard Worker       if (Instruction *New = FoldAllocaCmp(I, Alloca, Op1))
3741*9880d681SAndroid Build Coastguard Worker         return New;
3742*9880d681SAndroid Build Coastguard Worker     if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
3743*9880d681SAndroid Build Coastguard Worker       if (Instruction *New = FoldAllocaCmp(I, Alloca, Op0))
3744*9880d681SAndroid Build Coastguard Worker         return New;
3745*9880d681SAndroid Build Coastguard Worker   }
3746*9880d681SAndroid Build Coastguard Worker 
3747*9880d681SAndroid Build Coastguard Worker   // Test to see if the operands of the icmp are casted versions of other
3748*9880d681SAndroid Build Coastguard Worker   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
3749*9880d681SAndroid Build Coastguard Worker   // now.
3750*9880d681SAndroid Build Coastguard Worker   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
3751*9880d681SAndroid Build Coastguard Worker     if (Op0->getType()->isPointerTy() &&
3752*9880d681SAndroid Build Coastguard Worker         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
3753*9880d681SAndroid Build Coastguard Worker       // We keep moving the cast from the left operand over to the right
3754*9880d681SAndroid Build Coastguard Worker       // operand, where it can often be eliminated completely.
3755*9880d681SAndroid Build Coastguard Worker       Op0 = CI->getOperand(0);
3756*9880d681SAndroid Build Coastguard Worker 
3757*9880d681SAndroid Build Coastguard Worker       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3758*9880d681SAndroid Build Coastguard Worker       // so eliminate it as well.
3759*9880d681SAndroid Build Coastguard Worker       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3760*9880d681SAndroid Build Coastguard Worker         Op1 = CI2->getOperand(0);
3761*9880d681SAndroid Build Coastguard Worker 
3762*9880d681SAndroid Build Coastguard Worker       // If Op1 is a constant, we can fold the cast into the constant.
3763*9880d681SAndroid Build Coastguard Worker       if (Op0->getType() != Op1->getType()) {
3764*9880d681SAndroid Build Coastguard Worker         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3765*9880d681SAndroid Build Coastguard Worker           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3766*9880d681SAndroid Build Coastguard Worker         } else {
3767*9880d681SAndroid Build Coastguard Worker           // Otherwise, cast the RHS right before the icmp
3768*9880d681SAndroid Build Coastguard Worker           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3769*9880d681SAndroid Build Coastguard Worker         }
3770*9880d681SAndroid Build Coastguard Worker       }
3771*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(I.getPredicate(), Op0, Op1);
3772*9880d681SAndroid Build Coastguard Worker     }
3773*9880d681SAndroid Build Coastguard Worker   }
3774*9880d681SAndroid Build Coastguard Worker 
3775*9880d681SAndroid Build Coastguard Worker   if (isa<CastInst>(Op0)) {
3776*9880d681SAndroid Build Coastguard Worker     // Handle the special case of: icmp (cast bool to X), <cst>
3777*9880d681SAndroid Build Coastguard Worker     // This comes up when you have code like
3778*9880d681SAndroid Build Coastguard Worker     //   int X = A < B;
3779*9880d681SAndroid Build Coastguard Worker     //   if (X) ...
3780*9880d681SAndroid Build Coastguard Worker     // For generality, we handle any zero-extension of any operand comparison
3781*9880d681SAndroid Build Coastguard Worker     // with a constant or another cast from the same type.
3782*9880d681SAndroid Build Coastguard Worker     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3783*9880d681SAndroid Build Coastguard Worker       if (Instruction *R = visitICmpInstWithCastAndCast(I))
3784*9880d681SAndroid Build Coastguard Worker         return R;
3785*9880d681SAndroid Build Coastguard Worker   }
3786*9880d681SAndroid Build Coastguard Worker 
3787*9880d681SAndroid Build Coastguard Worker   // Special logic for binary operators.
3788*9880d681SAndroid Build Coastguard Worker   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3789*9880d681SAndroid Build Coastguard Worker   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3790*9880d681SAndroid Build Coastguard Worker   if (BO0 || BO1) {
3791*9880d681SAndroid Build Coastguard Worker     CmpInst::Predicate Pred = I.getPredicate();
3792*9880d681SAndroid Build Coastguard Worker     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3793*9880d681SAndroid Build Coastguard Worker     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3794*9880d681SAndroid Build Coastguard Worker       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3795*9880d681SAndroid Build Coastguard Worker         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3796*9880d681SAndroid Build Coastguard Worker         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3797*9880d681SAndroid Build Coastguard Worker     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3798*9880d681SAndroid Build Coastguard Worker       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3799*9880d681SAndroid Build Coastguard Worker         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3800*9880d681SAndroid Build Coastguard Worker         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3801*9880d681SAndroid Build Coastguard Worker 
3802*9880d681SAndroid Build Coastguard Worker     // Analyze the case when either Op0 or Op1 is an add instruction.
3803*9880d681SAndroid Build Coastguard Worker     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
3804*9880d681SAndroid Build Coastguard Worker     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3805*9880d681SAndroid Build Coastguard Worker     if (BO0 && BO0->getOpcode() == Instruction::Add) {
3806*9880d681SAndroid Build Coastguard Worker       A = BO0->getOperand(0);
3807*9880d681SAndroid Build Coastguard Worker       B = BO0->getOperand(1);
3808*9880d681SAndroid Build Coastguard Worker     }
3809*9880d681SAndroid Build Coastguard Worker     if (BO1 && BO1->getOpcode() == Instruction::Add) {
3810*9880d681SAndroid Build Coastguard Worker       C = BO1->getOperand(0);
3811*9880d681SAndroid Build Coastguard Worker       D = BO1->getOperand(1);
3812*9880d681SAndroid Build Coastguard Worker     }
3813*9880d681SAndroid Build Coastguard Worker 
3814*9880d681SAndroid Build Coastguard Worker     // icmp (X+cst) < 0 --> X < -cst
3815*9880d681SAndroid Build Coastguard Worker     if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3816*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3817*9880d681SAndroid Build Coastguard Worker         if (!RHSC->isMinValue(/*isSigned=*/true))
3818*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3819*9880d681SAndroid Build Coastguard Worker 
3820*9880d681SAndroid Build Coastguard Worker     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3821*9880d681SAndroid Build Coastguard Worker     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3822*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, A == Op1 ? B : A,
3823*9880d681SAndroid Build Coastguard Worker                           Constant::getNullValue(Op1->getType()));
3824*9880d681SAndroid Build Coastguard Worker 
3825*9880d681SAndroid Build Coastguard Worker     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3826*9880d681SAndroid Build Coastguard Worker     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3827*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3828*9880d681SAndroid Build Coastguard Worker                           C == Op0 ? D : C);
3829*9880d681SAndroid Build Coastguard Worker 
3830*9880d681SAndroid Build Coastguard Worker     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
3831*9880d681SAndroid Build Coastguard Worker     if (A && C && (A == C || A == D || B == C || B == D) &&
3832*9880d681SAndroid Build Coastguard Worker         NoOp0WrapProblem && NoOp1WrapProblem &&
3833*9880d681SAndroid Build Coastguard Worker         // Try not to increase register pressure.
3834*9880d681SAndroid Build Coastguard Worker         BO0->hasOneUse() && BO1->hasOneUse()) {
3835*9880d681SAndroid Build Coastguard Worker       // Determine Y and Z in the form icmp (X+Y), (X+Z).
3836*9880d681SAndroid Build Coastguard Worker       Value *Y, *Z;
3837*9880d681SAndroid Build Coastguard Worker       if (A == C) {
3838*9880d681SAndroid Build Coastguard Worker         // C + B == C + D  ->  B == D
3839*9880d681SAndroid Build Coastguard Worker         Y = B;
3840*9880d681SAndroid Build Coastguard Worker         Z = D;
3841*9880d681SAndroid Build Coastguard Worker       } else if (A == D) {
3842*9880d681SAndroid Build Coastguard Worker         // D + B == C + D  ->  B == C
3843*9880d681SAndroid Build Coastguard Worker         Y = B;
3844*9880d681SAndroid Build Coastguard Worker         Z = C;
3845*9880d681SAndroid Build Coastguard Worker       } else if (B == C) {
3846*9880d681SAndroid Build Coastguard Worker         // A + C == C + D  ->  A == D
3847*9880d681SAndroid Build Coastguard Worker         Y = A;
3848*9880d681SAndroid Build Coastguard Worker         Z = D;
3849*9880d681SAndroid Build Coastguard Worker       } else {
3850*9880d681SAndroid Build Coastguard Worker         assert(B == D);
3851*9880d681SAndroid Build Coastguard Worker         // A + D == C + D  ->  A == C
3852*9880d681SAndroid Build Coastguard Worker         Y = A;
3853*9880d681SAndroid Build Coastguard Worker         Z = C;
3854*9880d681SAndroid Build Coastguard Worker       }
3855*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, Y, Z);
3856*9880d681SAndroid Build Coastguard Worker     }
3857*9880d681SAndroid Build Coastguard Worker 
3858*9880d681SAndroid Build Coastguard Worker     // icmp slt (X + -1), Y -> icmp sle X, Y
3859*9880d681SAndroid Build Coastguard Worker     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3860*9880d681SAndroid Build Coastguard Worker         match(B, m_AllOnes()))
3861*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3862*9880d681SAndroid Build Coastguard Worker 
3863*9880d681SAndroid Build Coastguard Worker     // icmp sge (X + -1), Y -> icmp sgt X, Y
3864*9880d681SAndroid Build Coastguard Worker     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3865*9880d681SAndroid Build Coastguard Worker         match(B, m_AllOnes()))
3866*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3867*9880d681SAndroid Build Coastguard Worker 
3868*9880d681SAndroid Build Coastguard Worker     // icmp sle (X + 1), Y -> icmp slt X, Y
3869*9880d681SAndroid Build Coastguard Worker     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3870*9880d681SAndroid Build Coastguard Worker         match(B, m_One()))
3871*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3872*9880d681SAndroid Build Coastguard Worker 
3873*9880d681SAndroid Build Coastguard Worker     // icmp sgt (X + 1), Y -> icmp sge X, Y
3874*9880d681SAndroid Build Coastguard Worker     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3875*9880d681SAndroid Build Coastguard Worker         match(B, m_One()))
3876*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3877*9880d681SAndroid Build Coastguard Worker 
3878*9880d681SAndroid Build Coastguard Worker     // icmp sgt X, (Y + -1) -> icmp sge X, Y
3879*9880d681SAndroid Build Coastguard Worker     if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3880*9880d681SAndroid Build Coastguard Worker         match(D, m_AllOnes()))
3881*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3882*9880d681SAndroid Build Coastguard Worker 
3883*9880d681SAndroid Build Coastguard Worker     // icmp sle X, (Y + -1) -> icmp slt X, Y
3884*9880d681SAndroid Build Coastguard Worker     if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3885*9880d681SAndroid Build Coastguard Worker         match(D, m_AllOnes()))
3886*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3887*9880d681SAndroid Build Coastguard Worker 
3888*9880d681SAndroid Build Coastguard Worker     // icmp sge X, (Y + 1) -> icmp sgt X, Y
3889*9880d681SAndroid Build Coastguard Worker     if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3890*9880d681SAndroid Build Coastguard Worker         match(D, m_One()))
3891*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3892*9880d681SAndroid Build Coastguard Worker 
3893*9880d681SAndroid Build Coastguard Worker     // icmp slt X, (Y + 1) -> icmp sle X, Y
3894*9880d681SAndroid Build Coastguard Worker     if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3895*9880d681SAndroid Build Coastguard Worker         match(D, m_One()))
3896*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3897*9880d681SAndroid Build Coastguard Worker 
3898*9880d681SAndroid Build Coastguard Worker     // if C1 has greater magnitude than C2:
3899*9880d681SAndroid Build Coastguard Worker     //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3900*9880d681SAndroid Build Coastguard Worker     //  s.t. C3 = C1 - C2
3901*9880d681SAndroid Build Coastguard Worker     //
3902*9880d681SAndroid Build Coastguard Worker     // if C2 has greater magnitude than C1:
3903*9880d681SAndroid Build Coastguard Worker     //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3904*9880d681SAndroid Build Coastguard Worker     //  s.t. C3 = C2 - C1
3905*9880d681SAndroid Build Coastguard Worker     if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3906*9880d681SAndroid Build Coastguard Worker         (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3907*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3908*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3909*9880d681SAndroid Build Coastguard Worker           const APInt &AP1 = C1->getValue();
3910*9880d681SAndroid Build Coastguard Worker           const APInt &AP2 = C2->getValue();
3911*9880d681SAndroid Build Coastguard Worker           if (AP1.isNegative() == AP2.isNegative()) {
3912*9880d681SAndroid Build Coastguard Worker             APInt AP1Abs = C1->getValue().abs();
3913*9880d681SAndroid Build Coastguard Worker             APInt AP2Abs = C2->getValue().abs();
3914*9880d681SAndroid Build Coastguard Worker             if (AP1Abs.uge(AP2Abs)) {
3915*9880d681SAndroid Build Coastguard Worker               ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3916*9880d681SAndroid Build Coastguard Worker               Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3917*9880d681SAndroid Build Coastguard Worker               return new ICmpInst(Pred, NewAdd, C);
3918*9880d681SAndroid Build Coastguard Worker             } else {
3919*9880d681SAndroid Build Coastguard Worker               ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3920*9880d681SAndroid Build Coastguard Worker               Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3921*9880d681SAndroid Build Coastguard Worker               return new ICmpInst(Pred, A, NewAdd);
3922*9880d681SAndroid Build Coastguard Worker             }
3923*9880d681SAndroid Build Coastguard Worker           }
3924*9880d681SAndroid Build Coastguard Worker         }
3925*9880d681SAndroid Build Coastguard Worker 
3926*9880d681SAndroid Build Coastguard Worker 
3927*9880d681SAndroid Build Coastguard Worker     // Analyze the case when either Op0 or Op1 is a sub instruction.
3928*9880d681SAndroid Build Coastguard Worker     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
3929*9880d681SAndroid Build Coastguard Worker     A = nullptr;
3930*9880d681SAndroid Build Coastguard Worker     B = nullptr;
3931*9880d681SAndroid Build Coastguard Worker     C = nullptr;
3932*9880d681SAndroid Build Coastguard Worker     D = nullptr;
3933*9880d681SAndroid Build Coastguard Worker     if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3934*9880d681SAndroid Build Coastguard Worker       A = BO0->getOperand(0);
3935*9880d681SAndroid Build Coastguard Worker       B = BO0->getOperand(1);
3936*9880d681SAndroid Build Coastguard Worker     }
3937*9880d681SAndroid Build Coastguard Worker     if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3938*9880d681SAndroid Build Coastguard Worker       C = BO1->getOperand(0);
3939*9880d681SAndroid Build Coastguard Worker       D = BO1->getOperand(1);
3940*9880d681SAndroid Build Coastguard Worker     }
3941*9880d681SAndroid Build Coastguard Worker 
3942*9880d681SAndroid Build Coastguard Worker     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3943*9880d681SAndroid Build Coastguard Worker     if (A == Op1 && NoOp0WrapProblem)
3944*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3945*9880d681SAndroid Build Coastguard Worker 
3946*9880d681SAndroid Build Coastguard Worker     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3947*9880d681SAndroid Build Coastguard Worker     if (C == Op0 && NoOp1WrapProblem)
3948*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3949*9880d681SAndroid Build Coastguard Worker 
3950*9880d681SAndroid Build Coastguard Worker     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
3951*9880d681SAndroid Build Coastguard Worker     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3952*9880d681SAndroid Build Coastguard Worker         // Try not to increase register pressure.
3953*9880d681SAndroid Build Coastguard Worker         BO0->hasOneUse() && BO1->hasOneUse())
3954*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, A, C);
3955*9880d681SAndroid Build Coastguard Worker 
3956*9880d681SAndroid Build Coastguard Worker     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3957*9880d681SAndroid Build Coastguard Worker     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3958*9880d681SAndroid Build Coastguard Worker         // Try not to increase register pressure.
3959*9880d681SAndroid Build Coastguard Worker         BO0->hasOneUse() && BO1->hasOneUse())
3960*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(Pred, D, B);
3961*9880d681SAndroid Build Coastguard Worker 
3962*9880d681SAndroid Build Coastguard Worker     // icmp (0-X) < cst --> x > -cst
3963*9880d681SAndroid Build Coastguard Worker     if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3964*9880d681SAndroid Build Coastguard Worker       Value *X;
3965*9880d681SAndroid Build Coastguard Worker       if (match(BO0, m_Neg(m_Value(X))))
3966*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3967*9880d681SAndroid Build Coastguard Worker           if (!RHSC->isMinValue(/*isSigned=*/true))
3968*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(I.getSwappedPredicate(), X,
3969*9880d681SAndroid Build Coastguard Worker                                 ConstantExpr::getNeg(RHSC));
3970*9880d681SAndroid Build Coastguard Worker     }
3971*9880d681SAndroid Build Coastguard Worker 
3972*9880d681SAndroid Build Coastguard Worker     BinaryOperator *SRem = nullptr;
3973*9880d681SAndroid Build Coastguard Worker     // icmp (srem X, Y), Y
3974*9880d681SAndroid Build Coastguard Worker     if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3975*9880d681SAndroid Build Coastguard Worker         Op1 == BO0->getOperand(1))
3976*9880d681SAndroid Build Coastguard Worker       SRem = BO0;
3977*9880d681SAndroid Build Coastguard Worker     // icmp Y, (srem X, Y)
3978*9880d681SAndroid Build Coastguard Worker     else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3979*9880d681SAndroid Build Coastguard Worker              Op0 == BO1->getOperand(1))
3980*9880d681SAndroid Build Coastguard Worker       SRem = BO1;
3981*9880d681SAndroid Build Coastguard Worker     if (SRem) {
3982*9880d681SAndroid Build Coastguard Worker       // We don't check hasOneUse to avoid increasing register pressure because
3983*9880d681SAndroid Build Coastguard Worker       // the value we use is the same value this instruction was already using.
3984*9880d681SAndroid Build Coastguard Worker       switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3985*9880d681SAndroid Build Coastguard Worker         default: break;
3986*9880d681SAndroid Build Coastguard Worker         case ICmpInst::ICMP_EQ:
3987*9880d681SAndroid Build Coastguard Worker           return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3988*9880d681SAndroid Build Coastguard Worker         case ICmpInst::ICMP_NE:
3989*9880d681SAndroid Build Coastguard Worker           return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3990*9880d681SAndroid Build Coastguard Worker         case ICmpInst::ICMP_SGT:
3991*9880d681SAndroid Build Coastguard Worker         case ICmpInst::ICMP_SGE:
3992*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3993*9880d681SAndroid Build Coastguard Worker                               Constant::getAllOnesValue(SRem->getType()));
3994*9880d681SAndroid Build Coastguard Worker         case ICmpInst::ICMP_SLT:
3995*9880d681SAndroid Build Coastguard Worker         case ICmpInst::ICMP_SLE:
3996*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3997*9880d681SAndroid Build Coastguard Worker                               Constant::getNullValue(SRem->getType()));
3998*9880d681SAndroid Build Coastguard Worker       }
3999*9880d681SAndroid Build Coastguard Worker     }
4000*9880d681SAndroid Build Coastguard Worker 
4001*9880d681SAndroid Build Coastguard Worker     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4002*9880d681SAndroid Build Coastguard Worker         BO0->hasOneUse() && BO1->hasOneUse() &&
4003*9880d681SAndroid Build Coastguard Worker         BO0->getOperand(1) == BO1->getOperand(1)) {
4004*9880d681SAndroid Build Coastguard Worker       switch (BO0->getOpcode()) {
4005*9880d681SAndroid Build Coastguard Worker       default: break;
4006*9880d681SAndroid Build Coastguard Worker       case Instruction::Add:
4007*9880d681SAndroid Build Coastguard Worker       case Instruction::Sub:
4008*9880d681SAndroid Build Coastguard Worker       case Instruction::Xor:
4009*9880d681SAndroid Build Coastguard Worker         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
4010*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4011*9880d681SAndroid Build Coastguard Worker                               BO1->getOperand(0));
4012*9880d681SAndroid Build Coastguard Worker         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4013*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4014*9880d681SAndroid Build Coastguard Worker           if (CI->getValue().isSignBit()) {
4015*9880d681SAndroid Build Coastguard Worker             ICmpInst::Predicate Pred = I.isSigned()
4016*9880d681SAndroid Build Coastguard Worker                                            ? I.getUnsignedPredicate()
4017*9880d681SAndroid Build Coastguard Worker                                            : I.getSignedPredicate();
4018*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(Pred, BO0->getOperand(0),
4019*9880d681SAndroid Build Coastguard Worker                                 BO1->getOperand(0));
4020*9880d681SAndroid Build Coastguard Worker           }
4021*9880d681SAndroid Build Coastguard Worker 
4022*9880d681SAndroid Build Coastguard Worker           if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
4023*9880d681SAndroid Build Coastguard Worker             ICmpInst::Predicate Pred = I.isSigned()
4024*9880d681SAndroid Build Coastguard Worker                                            ? I.getUnsignedPredicate()
4025*9880d681SAndroid Build Coastguard Worker                                            : I.getSignedPredicate();
4026*9880d681SAndroid Build Coastguard Worker             Pred = I.getSwappedPredicate(Pred);
4027*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(Pred, BO0->getOperand(0),
4028*9880d681SAndroid Build Coastguard Worker                                 BO1->getOperand(0));
4029*9880d681SAndroid Build Coastguard Worker           }
4030*9880d681SAndroid Build Coastguard Worker         }
4031*9880d681SAndroid Build Coastguard Worker         break;
4032*9880d681SAndroid Build Coastguard Worker       case Instruction::Mul:
4033*9880d681SAndroid Build Coastguard Worker         if (!I.isEquality())
4034*9880d681SAndroid Build Coastguard Worker           break;
4035*9880d681SAndroid Build Coastguard Worker 
4036*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4037*9880d681SAndroid Build Coastguard Worker           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4038*9880d681SAndroid Build Coastguard Worker           // Mask = -1 >> count-trailing-zeros(Cst).
4039*9880d681SAndroid Build Coastguard Worker           if (!CI->isZero() && !CI->isOne()) {
4040*9880d681SAndroid Build Coastguard Worker             const APInt &AP = CI->getValue();
4041*9880d681SAndroid Build Coastguard Worker             ConstantInt *Mask = ConstantInt::get(I.getContext(),
4042*9880d681SAndroid Build Coastguard Worker                                     APInt::getLowBitsSet(AP.getBitWidth(),
4043*9880d681SAndroid Build Coastguard Worker                                                          AP.getBitWidth() -
4044*9880d681SAndroid Build Coastguard Worker                                                     AP.countTrailingZeros()));
4045*9880d681SAndroid Build Coastguard Worker             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4046*9880d681SAndroid Build Coastguard Worker             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4047*9880d681SAndroid Build Coastguard Worker             return new ICmpInst(I.getPredicate(), And1, And2);
4048*9880d681SAndroid Build Coastguard Worker           }
4049*9880d681SAndroid Build Coastguard Worker         }
4050*9880d681SAndroid Build Coastguard Worker         break;
4051*9880d681SAndroid Build Coastguard Worker       case Instruction::UDiv:
4052*9880d681SAndroid Build Coastguard Worker       case Instruction::LShr:
4053*9880d681SAndroid Build Coastguard Worker         if (I.isSigned())
4054*9880d681SAndroid Build Coastguard Worker           break;
4055*9880d681SAndroid Build Coastguard Worker         // fall-through
4056*9880d681SAndroid Build Coastguard Worker       case Instruction::SDiv:
4057*9880d681SAndroid Build Coastguard Worker       case Instruction::AShr:
4058*9880d681SAndroid Build Coastguard Worker         if (!BO0->isExact() || !BO1->isExact())
4059*9880d681SAndroid Build Coastguard Worker           break;
4060*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4061*9880d681SAndroid Build Coastguard Worker                             BO1->getOperand(0));
4062*9880d681SAndroid Build Coastguard Worker       case Instruction::Shl: {
4063*9880d681SAndroid Build Coastguard Worker         bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4064*9880d681SAndroid Build Coastguard Worker         bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4065*9880d681SAndroid Build Coastguard Worker         if (!NUW && !NSW)
4066*9880d681SAndroid Build Coastguard Worker           break;
4067*9880d681SAndroid Build Coastguard Worker         if (!NSW && I.isSigned())
4068*9880d681SAndroid Build Coastguard Worker           break;
4069*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4070*9880d681SAndroid Build Coastguard Worker                             BO1->getOperand(0));
4071*9880d681SAndroid Build Coastguard Worker       }
4072*9880d681SAndroid Build Coastguard Worker       }
4073*9880d681SAndroid Build Coastguard Worker     }
4074*9880d681SAndroid Build Coastguard Worker 
4075*9880d681SAndroid Build Coastguard Worker     if (BO0) {
4076*9880d681SAndroid Build Coastguard Worker       // Transform  A & (L - 1) `ult` L --> L != 0
4077*9880d681SAndroid Build Coastguard Worker       auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4078*9880d681SAndroid Build Coastguard Worker       auto BitwiseAnd =
4079*9880d681SAndroid Build Coastguard Worker           m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4080*9880d681SAndroid Build Coastguard Worker 
4081*9880d681SAndroid Build Coastguard Worker       if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4082*9880d681SAndroid Build Coastguard Worker         auto *Zero = Constant::getNullValue(BO0->getType());
4083*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4084*9880d681SAndroid Build Coastguard Worker       }
4085*9880d681SAndroid Build Coastguard Worker     }
4086*9880d681SAndroid Build Coastguard Worker   }
4087*9880d681SAndroid Build Coastguard Worker 
4088*9880d681SAndroid Build Coastguard Worker   { Value *A, *B;
4089*9880d681SAndroid Build Coastguard Worker     // Transform (A & ~B) == 0 --> (A & B) != 0
4090*9880d681SAndroid Build Coastguard Worker     // and       (A & ~B) != 0 --> (A & B) == 0
4091*9880d681SAndroid Build Coastguard Worker     // if A is a power of 2.
4092*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
4093*9880d681SAndroid Build Coastguard Worker         match(Op1, m_Zero()) &&
4094*9880d681SAndroid Build Coastguard Worker         isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
4095*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(I.getInversePredicate(),
4096*9880d681SAndroid Build Coastguard Worker                           Builder->CreateAnd(A, B),
4097*9880d681SAndroid Build Coastguard Worker                           Op1);
4098*9880d681SAndroid Build Coastguard Worker 
4099*9880d681SAndroid Build Coastguard Worker     // ~x < ~y --> y < x
4100*9880d681SAndroid Build Coastguard Worker     // ~x < cst --> ~cst < x
4101*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_Not(m_Value(A)))) {
4102*9880d681SAndroid Build Coastguard Worker       if (match(Op1, m_Not(m_Value(B))))
4103*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), B, A);
4104*9880d681SAndroid Build Coastguard Worker       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
4105*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4106*9880d681SAndroid Build Coastguard Worker     }
4107*9880d681SAndroid Build Coastguard Worker 
4108*9880d681SAndroid Build Coastguard Worker     Instruction *AddI = nullptr;
4109*9880d681SAndroid Build Coastguard Worker     if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4110*9880d681SAndroid Build Coastguard Worker                                      m_Instruction(AddI))) &&
4111*9880d681SAndroid Build Coastguard Worker         isa<IntegerType>(A->getType())) {
4112*9880d681SAndroid Build Coastguard Worker       Value *Result;
4113*9880d681SAndroid Build Coastguard Worker       Constant *Overflow;
4114*9880d681SAndroid Build Coastguard Worker       if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4115*9880d681SAndroid Build Coastguard Worker                                 Overflow)) {
4116*9880d681SAndroid Build Coastguard Worker         replaceInstUsesWith(*AddI, Result);
4117*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Overflow);
4118*9880d681SAndroid Build Coastguard Worker       }
4119*9880d681SAndroid Build Coastguard Worker     }
4120*9880d681SAndroid Build Coastguard Worker 
4121*9880d681SAndroid Build Coastguard Worker     // (zext a) * (zext b)  --> llvm.umul.with.overflow.
4122*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4123*9880d681SAndroid Build Coastguard Worker       if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4124*9880d681SAndroid Build Coastguard Worker         return R;
4125*9880d681SAndroid Build Coastguard Worker     }
4126*9880d681SAndroid Build Coastguard Worker     if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4127*9880d681SAndroid Build Coastguard Worker       if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4128*9880d681SAndroid Build Coastguard Worker         return R;
4129*9880d681SAndroid Build Coastguard Worker     }
4130*9880d681SAndroid Build Coastguard Worker   }
4131*9880d681SAndroid Build Coastguard Worker 
4132*9880d681SAndroid Build Coastguard Worker   if (I.isEquality()) {
4133*9880d681SAndroid Build Coastguard Worker     Value *A, *B, *C, *D;
4134*9880d681SAndroid Build Coastguard Worker 
4135*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4136*9880d681SAndroid Build Coastguard Worker       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
4137*9880d681SAndroid Build Coastguard Worker         Value *OtherVal = A == Op1 ? B : A;
4138*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), OtherVal,
4139*9880d681SAndroid Build Coastguard Worker                             Constant::getNullValue(A->getType()));
4140*9880d681SAndroid Build Coastguard Worker       }
4141*9880d681SAndroid Build Coastguard Worker 
4142*9880d681SAndroid Build Coastguard Worker       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4143*9880d681SAndroid Build Coastguard Worker         // A^c1 == C^c2 --> A == C^(c1^c2)
4144*9880d681SAndroid Build Coastguard Worker         ConstantInt *C1, *C2;
4145*9880d681SAndroid Build Coastguard Worker         if (match(B, m_ConstantInt(C1)) &&
4146*9880d681SAndroid Build Coastguard Worker             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
4147*9880d681SAndroid Build Coastguard Worker           Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
4148*9880d681SAndroid Build Coastguard Worker           Value *Xor = Builder->CreateXor(C, NC);
4149*9880d681SAndroid Build Coastguard Worker           return new ICmpInst(I.getPredicate(), A, Xor);
4150*9880d681SAndroid Build Coastguard Worker         }
4151*9880d681SAndroid Build Coastguard Worker 
4152*9880d681SAndroid Build Coastguard Worker         // A^B == A^D -> B == D
4153*9880d681SAndroid Build Coastguard Worker         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4154*9880d681SAndroid Build Coastguard Worker         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4155*9880d681SAndroid Build Coastguard Worker         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4156*9880d681SAndroid Build Coastguard Worker         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4157*9880d681SAndroid Build Coastguard Worker       }
4158*9880d681SAndroid Build Coastguard Worker     }
4159*9880d681SAndroid Build Coastguard Worker 
4160*9880d681SAndroid Build Coastguard Worker     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4161*9880d681SAndroid Build Coastguard Worker         (A == Op0 || B == Op0)) {
4162*9880d681SAndroid Build Coastguard Worker       // A == (A^B)  ->  B == 0
4163*9880d681SAndroid Build Coastguard Worker       Value *OtherVal = A == Op0 ? B : A;
4164*9880d681SAndroid Build Coastguard Worker       return new ICmpInst(I.getPredicate(), OtherVal,
4165*9880d681SAndroid Build Coastguard Worker                           Constant::getNullValue(A->getType()));
4166*9880d681SAndroid Build Coastguard Worker     }
4167*9880d681SAndroid Build Coastguard Worker 
4168*9880d681SAndroid Build Coastguard Worker     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4169*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
4170*9880d681SAndroid Build Coastguard Worker         match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
4171*9880d681SAndroid Build Coastguard Worker       Value *X = nullptr, *Y = nullptr, *Z = nullptr;
4172*9880d681SAndroid Build Coastguard Worker 
4173*9880d681SAndroid Build Coastguard Worker       if (A == C) {
4174*9880d681SAndroid Build Coastguard Worker         X = B; Y = D; Z = A;
4175*9880d681SAndroid Build Coastguard Worker       } else if (A == D) {
4176*9880d681SAndroid Build Coastguard Worker         X = B; Y = C; Z = A;
4177*9880d681SAndroid Build Coastguard Worker       } else if (B == C) {
4178*9880d681SAndroid Build Coastguard Worker         X = A; Y = D; Z = B;
4179*9880d681SAndroid Build Coastguard Worker       } else if (B == D) {
4180*9880d681SAndroid Build Coastguard Worker         X = A; Y = C; Z = B;
4181*9880d681SAndroid Build Coastguard Worker       }
4182*9880d681SAndroid Build Coastguard Worker 
4183*9880d681SAndroid Build Coastguard Worker       if (X) {   // Build (X^Y) & Z
4184*9880d681SAndroid Build Coastguard Worker         Op1 = Builder->CreateXor(X, Y);
4185*9880d681SAndroid Build Coastguard Worker         Op1 = Builder->CreateAnd(Op1, Z);
4186*9880d681SAndroid Build Coastguard Worker         I.setOperand(0, Op1);
4187*9880d681SAndroid Build Coastguard Worker         I.setOperand(1, Constant::getNullValue(Op1->getType()));
4188*9880d681SAndroid Build Coastguard Worker         return &I;
4189*9880d681SAndroid Build Coastguard Worker       }
4190*9880d681SAndroid Build Coastguard Worker     }
4191*9880d681SAndroid Build Coastguard Worker 
4192*9880d681SAndroid Build Coastguard Worker     // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
4193*9880d681SAndroid Build Coastguard Worker     // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
4194*9880d681SAndroid Build Coastguard Worker     ConstantInt *Cst1;
4195*9880d681SAndroid Build Coastguard Worker     if ((Op0->hasOneUse() &&
4196*9880d681SAndroid Build Coastguard Worker          match(Op0, m_ZExt(m_Value(A))) &&
4197*9880d681SAndroid Build Coastguard Worker          match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4198*9880d681SAndroid Build Coastguard Worker         (Op1->hasOneUse() &&
4199*9880d681SAndroid Build Coastguard Worker          match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4200*9880d681SAndroid Build Coastguard Worker          match(Op1, m_ZExt(m_Value(A))))) {
4201*9880d681SAndroid Build Coastguard Worker       APInt Pow2 = Cst1->getValue() + 1;
4202*9880d681SAndroid Build Coastguard Worker       if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4203*9880d681SAndroid Build Coastguard Worker           Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4204*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), A,
4205*9880d681SAndroid Build Coastguard Worker                             Builder->CreateTrunc(B, A->getType()));
4206*9880d681SAndroid Build Coastguard Worker     }
4207*9880d681SAndroid Build Coastguard Worker 
4208*9880d681SAndroid Build Coastguard Worker     // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4209*9880d681SAndroid Build Coastguard Worker     // For lshr and ashr pairs.
4210*9880d681SAndroid Build Coastguard Worker     if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4211*9880d681SAndroid Build Coastguard Worker          match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4212*9880d681SAndroid Build Coastguard Worker         (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4213*9880d681SAndroid Build Coastguard Worker          match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4214*9880d681SAndroid Build Coastguard Worker       unsigned TypeBits = Cst1->getBitWidth();
4215*9880d681SAndroid Build Coastguard Worker       unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4216*9880d681SAndroid Build Coastguard Worker       if (ShAmt < TypeBits && ShAmt != 0) {
4217*9880d681SAndroid Build Coastguard Worker         ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4218*9880d681SAndroid Build Coastguard Worker                                        ? ICmpInst::ICMP_UGE
4219*9880d681SAndroid Build Coastguard Worker                                        : ICmpInst::ICMP_ULT;
4220*9880d681SAndroid Build Coastguard Worker         Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4221*9880d681SAndroid Build Coastguard Worker         APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4222*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4223*9880d681SAndroid Build Coastguard Worker       }
4224*9880d681SAndroid Build Coastguard Worker     }
4225*9880d681SAndroid Build Coastguard Worker 
4226*9880d681SAndroid Build Coastguard Worker     // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4227*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4228*9880d681SAndroid Build Coastguard Worker         match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4229*9880d681SAndroid Build Coastguard Worker       unsigned TypeBits = Cst1->getBitWidth();
4230*9880d681SAndroid Build Coastguard Worker       unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4231*9880d681SAndroid Build Coastguard Worker       if (ShAmt < TypeBits && ShAmt != 0) {
4232*9880d681SAndroid Build Coastguard Worker         Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4233*9880d681SAndroid Build Coastguard Worker         APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4234*9880d681SAndroid Build Coastguard Worker         Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4235*9880d681SAndroid Build Coastguard Worker                                         I.getName() + ".mask");
4236*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), And,
4237*9880d681SAndroid Build Coastguard Worker                             Constant::getNullValue(Cst1->getType()));
4238*9880d681SAndroid Build Coastguard Worker       }
4239*9880d681SAndroid Build Coastguard Worker     }
4240*9880d681SAndroid Build Coastguard Worker 
4241*9880d681SAndroid Build Coastguard Worker     // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4242*9880d681SAndroid Build Coastguard Worker     // "icmp (and X, mask), cst"
4243*9880d681SAndroid Build Coastguard Worker     uint64_t ShAmt = 0;
4244*9880d681SAndroid Build Coastguard Worker     if (Op0->hasOneUse() &&
4245*9880d681SAndroid Build Coastguard Worker         match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4246*9880d681SAndroid Build Coastguard Worker                                            m_ConstantInt(ShAmt))))) &&
4247*9880d681SAndroid Build Coastguard Worker         match(Op1, m_ConstantInt(Cst1)) &&
4248*9880d681SAndroid Build Coastguard Worker         // Only do this when A has multiple uses.  This is most important to do
4249*9880d681SAndroid Build Coastguard Worker         // when it exposes other optimizations.
4250*9880d681SAndroid Build Coastguard Worker         !A->hasOneUse()) {
4251*9880d681SAndroid Build Coastguard Worker       unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
4252*9880d681SAndroid Build Coastguard Worker 
4253*9880d681SAndroid Build Coastguard Worker       if (ShAmt < ASize) {
4254*9880d681SAndroid Build Coastguard Worker         APInt MaskV =
4255*9880d681SAndroid Build Coastguard Worker           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4256*9880d681SAndroid Build Coastguard Worker         MaskV <<= ShAmt;
4257*9880d681SAndroid Build Coastguard Worker 
4258*9880d681SAndroid Build Coastguard Worker         APInt CmpV = Cst1->getValue().zext(ASize);
4259*9880d681SAndroid Build Coastguard Worker         CmpV <<= ShAmt;
4260*9880d681SAndroid Build Coastguard Worker 
4261*9880d681SAndroid Build Coastguard Worker         Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4262*9880d681SAndroid Build Coastguard Worker         return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4263*9880d681SAndroid Build Coastguard Worker       }
4264*9880d681SAndroid Build Coastguard Worker     }
4265*9880d681SAndroid Build Coastguard Worker   }
4266*9880d681SAndroid Build Coastguard Worker 
4267*9880d681SAndroid Build Coastguard Worker   // The 'cmpxchg' instruction returns an aggregate containing the old value and
4268*9880d681SAndroid Build Coastguard Worker   // an i1 which indicates whether or not we successfully did the swap.
4269*9880d681SAndroid Build Coastguard Worker   //
4270*9880d681SAndroid Build Coastguard Worker   // Replace comparisons between the old value and the expected value with the
4271*9880d681SAndroid Build Coastguard Worker   // indicator that 'cmpxchg' returns.
4272*9880d681SAndroid Build Coastguard Worker   //
4273*9880d681SAndroid Build Coastguard Worker   // N.B.  This transform is only valid when the 'cmpxchg' is not permitted to
4274*9880d681SAndroid Build Coastguard Worker   // spuriously fail.  In those cases, the old value may equal the expected
4275*9880d681SAndroid Build Coastguard Worker   // value but it is possible for the swap to not occur.
4276*9880d681SAndroid Build Coastguard Worker   if (I.getPredicate() == ICmpInst::ICMP_EQ)
4277*9880d681SAndroid Build Coastguard Worker     if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4278*9880d681SAndroid Build Coastguard Worker       if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4279*9880d681SAndroid Build Coastguard Worker         if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4280*9880d681SAndroid Build Coastguard Worker             !ACXI->isWeak())
4281*9880d681SAndroid Build Coastguard Worker           return ExtractValueInst::Create(ACXI, 1);
4282*9880d681SAndroid Build Coastguard Worker 
4283*9880d681SAndroid Build Coastguard Worker   {
4284*9880d681SAndroid Build Coastguard Worker     Value *X; ConstantInt *Cst;
4285*9880d681SAndroid Build Coastguard Worker     // icmp X+Cst, X
4286*9880d681SAndroid Build Coastguard Worker     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
4287*9880d681SAndroid Build Coastguard Worker       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
4288*9880d681SAndroid Build Coastguard Worker 
4289*9880d681SAndroid Build Coastguard Worker     // icmp X, X+Cst
4290*9880d681SAndroid Build Coastguard Worker     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
4291*9880d681SAndroid Build Coastguard Worker       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
4292*9880d681SAndroid Build Coastguard Worker   }
4293*9880d681SAndroid Build Coastguard Worker   return Changed ? &I : nullptr;
4294*9880d681SAndroid Build Coastguard Worker }
4295*9880d681SAndroid Build Coastguard Worker 
4296*9880d681SAndroid Build Coastguard Worker /// Fold fcmp ([us]itofp x, cst) if possible.
FoldFCmp_IntToFP_Cst(FCmpInst & I,Instruction * LHSI,Constant * RHSC)4297*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4298*9880d681SAndroid Build Coastguard Worker                                                 Instruction *LHSI,
4299*9880d681SAndroid Build Coastguard Worker                                                 Constant *RHSC) {
4300*9880d681SAndroid Build Coastguard Worker   if (!isa<ConstantFP>(RHSC)) return nullptr;
4301*9880d681SAndroid Build Coastguard Worker   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4302*9880d681SAndroid Build Coastguard Worker 
4303*9880d681SAndroid Build Coastguard Worker   // Get the width of the mantissa.  We don't want to hack on conversions that
4304*9880d681SAndroid Build Coastguard Worker   // might lose information from the integer, e.g. "i64 -> float"
4305*9880d681SAndroid Build Coastguard Worker   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4306*9880d681SAndroid Build Coastguard Worker   if (MantissaWidth == -1) return nullptr;  // Unknown.
4307*9880d681SAndroid Build Coastguard Worker 
4308*9880d681SAndroid Build Coastguard Worker   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4309*9880d681SAndroid Build Coastguard Worker 
4310*9880d681SAndroid Build Coastguard Worker   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
4311*9880d681SAndroid Build Coastguard Worker 
4312*9880d681SAndroid Build Coastguard Worker   if (I.isEquality()) {
4313*9880d681SAndroid Build Coastguard Worker     FCmpInst::Predicate P = I.getPredicate();
4314*9880d681SAndroid Build Coastguard Worker     bool IsExact = false;
4315*9880d681SAndroid Build Coastguard Worker     APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4316*9880d681SAndroid Build Coastguard Worker     RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4317*9880d681SAndroid Build Coastguard Worker 
4318*9880d681SAndroid Build Coastguard Worker     // If the floating point constant isn't an integer value, we know if we will
4319*9880d681SAndroid Build Coastguard Worker     // ever compare equal / not equal to it.
4320*9880d681SAndroid Build Coastguard Worker     if (!IsExact) {
4321*9880d681SAndroid Build Coastguard Worker       // TODO: Can never be -0.0 and other non-representable values
4322*9880d681SAndroid Build Coastguard Worker       APFloat RHSRoundInt(RHS);
4323*9880d681SAndroid Build Coastguard Worker       RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4324*9880d681SAndroid Build Coastguard Worker       if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4325*9880d681SAndroid Build Coastguard Worker         if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
4326*9880d681SAndroid Build Coastguard Worker           return replaceInstUsesWith(I, Builder->getFalse());
4327*9880d681SAndroid Build Coastguard Worker 
4328*9880d681SAndroid Build Coastguard Worker         assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
4329*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getTrue());
4330*9880d681SAndroid Build Coastguard Worker       }
4331*9880d681SAndroid Build Coastguard Worker     }
4332*9880d681SAndroid Build Coastguard Worker 
4333*9880d681SAndroid Build Coastguard Worker     // TODO: If the constant is exactly representable, is it always OK to do
4334*9880d681SAndroid Build Coastguard Worker     // equality compares as integer?
4335*9880d681SAndroid Build Coastguard Worker   }
4336*9880d681SAndroid Build Coastguard Worker 
4337*9880d681SAndroid Build Coastguard Worker   // Check to see that the input is converted from an integer type that is small
4338*9880d681SAndroid Build Coastguard Worker   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4339*9880d681SAndroid Build Coastguard Worker   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4340*9880d681SAndroid Build Coastguard Worker   unsigned InputSize = IntTy->getScalarSizeInBits();
4341*9880d681SAndroid Build Coastguard Worker 
4342*9880d681SAndroid Build Coastguard Worker   // Following test does NOT adjust InputSize downwards for signed inputs,
4343*9880d681SAndroid Build Coastguard Worker   // because the most negative value still requires all the mantissa bits
4344*9880d681SAndroid Build Coastguard Worker   // to distinguish it from one less than that value.
4345*9880d681SAndroid Build Coastguard Worker   if ((int)InputSize > MantissaWidth) {
4346*9880d681SAndroid Build Coastguard Worker     // Conversion would lose accuracy. Check if loss can impact comparison.
4347*9880d681SAndroid Build Coastguard Worker     int Exp = ilogb(RHS);
4348*9880d681SAndroid Build Coastguard Worker     if (Exp == APFloat::IEK_Inf) {
4349*9880d681SAndroid Build Coastguard Worker       int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
4350*9880d681SAndroid Build Coastguard Worker       if (MaxExponent < (int)InputSize - !LHSUnsigned)
4351*9880d681SAndroid Build Coastguard Worker         // Conversion could create infinity.
4352*9880d681SAndroid Build Coastguard Worker         return nullptr;
4353*9880d681SAndroid Build Coastguard Worker     } else {
4354*9880d681SAndroid Build Coastguard Worker       // Note that if RHS is zero or NaN, then Exp is negative
4355*9880d681SAndroid Build Coastguard Worker       // and first condition is trivially false.
4356*9880d681SAndroid Build Coastguard Worker       if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
4357*9880d681SAndroid Build Coastguard Worker         // Conversion could affect comparison.
4358*9880d681SAndroid Build Coastguard Worker         return nullptr;
4359*9880d681SAndroid Build Coastguard Worker     }
4360*9880d681SAndroid Build Coastguard Worker   }
4361*9880d681SAndroid Build Coastguard Worker 
4362*9880d681SAndroid Build Coastguard Worker   // Otherwise, we can potentially simplify the comparison.  We know that it
4363*9880d681SAndroid Build Coastguard Worker   // will always come through as an integer value and we know the constant is
4364*9880d681SAndroid Build Coastguard Worker   // not a NAN (it would have been previously simplified).
4365*9880d681SAndroid Build Coastguard Worker   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4366*9880d681SAndroid Build Coastguard Worker 
4367*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate Pred;
4368*9880d681SAndroid Build Coastguard Worker   switch (I.getPredicate()) {
4369*9880d681SAndroid Build Coastguard Worker   default: llvm_unreachable("Unexpected predicate!");
4370*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UEQ:
4371*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OEQ:
4372*9880d681SAndroid Build Coastguard Worker     Pred = ICmpInst::ICMP_EQ;
4373*9880d681SAndroid Build Coastguard Worker     break;
4374*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UGT:
4375*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OGT:
4376*9880d681SAndroid Build Coastguard Worker     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4377*9880d681SAndroid Build Coastguard Worker     break;
4378*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UGE:
4379*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OGE:
4380*9880d681SAndroid Build Coastguard Worker     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4381*9880d681SAndroid Build Coastguard Worker     break;
4382*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ULT:
4383*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OLT:
4384*9880d681SAndroid Build Coastguard Worker     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4385*9880d681SAndroid Build Coastguard Worker     break;
4386*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ULE:
4387*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_OLE:
4388*9880d681SAndroid Build Coastguard Worker     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4389*9880d681SAndroid Build Coastguard Worker     break;
4390*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UNE:
4391*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ONE:
4392*9880d681SAndroid Build Coastguard Worker     Pred = ICmpInst::ICMP_NE;
4393*9880d681SAndroid Build Coastguard Worker     break;
4394*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_ORD:
4395*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(I, Builder->getTrue());
4396*9880d681SAndroid Build Coastguard Worker   case FCmpInst::FCMP_UNO:
4397*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(I, Builder->getFalse());
4398*9880d681SAndroid Build Coastguard Worker   }
4399*9880d681SAndroid Build Coastguard Worker 
4400*9880d681SAndroid Build Coastguard Worker   // Now we know that the APFloat is a normal number, zero or inf.
4401*9880d681SAndroid Build Coastguard Worker 
4402*9880d681SAndroid Build Coastguard Worker   // See if the FP constant is too large for the integer.  For example,
4403*9880d681SAndroid Build Coastguard Worker   // comparing an i8 to 300.0.
4404*9880d681SAndroid Build Coastguard Worker   unsigned IntWidth = IntTy->getScalarSizeInBits();
4405*9880d681SAndroid Build Coastguard Worker 
4406*9880d681SAndroid Build Coastguard Worker   if (!LHSUnsigned) {
4407*9880d681SAndroid Build Coastguard Worker     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4408*9880d681SAndroid Build Coastguard Worker     // and large values.
4409*9880d681SAndroid Build Coastguard Worker     APFloat SMax(RHS.getSemantics());
4410*9880d681SAndroid Build Coastguard Worker     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4411*9880d681SAndroid Build Coastguard Worker                           APFloat::rmNearestTiesToEven);
4412*9880d681SAndroid Build Coastguard Worker     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4413*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
4414*9880d681SAndroid Build Coastguard Worker           Pred == ICmpInst::ICMP_SLE)
4415*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getTrue());
4416*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(I, Builder->getFalse());
4417*9880d681SAndroid Build Coastguard Worker     }
4418*9880d681SAndroid Build Coastguard Worker   } else {
4419*9880d681SAndroid Build Coastguard Worker     // If the RHS value is > UnsignedMax, fold the comparison. This handles
4420*9880d681SAndroid Build Coastguard Worker     // +INF and large values.
4421*9880d681SAndroid Build Coastguard Worker     APFloat UMax(RHS.getSemantics());
4422*9880d681SAndroid Build Coastguard Worker     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4423*9880d681SAndroid Build Coastguard Worker                           APFloat::rmNearestTiesToEven);
4424*9880d681SAndroid Build Coastguard Worker     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
4425*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
4426*9880d681SAndroid Build Coastguard Worker           Pred == ICmpInst::ICMP_ULE)
4427*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getTrue());
4428*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(I, Builder->getFalse());
4429*9880d681SAndroid Build Coastguard Worker     }
4430*9880d681SAndroid Build Coastguard Worker   }
4431*9880d681SAndroid Build Coastguard Worker 
4432*9880d681SAndroid Build Coastguard Worker   if (!LHSUnsigned) {
4433*9880d681SAndroid Build Coastguard Worker     // See if the RHS value is < SignedMin.
4434*9880d681SAndroid Build Coastguard Worker     APFloat SMin(RHS.getSemantics());
4435*9880d681SAndroid Build Coastguard Worker     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4436*9880d681SAndroid Build Coastguard Worker                           APFloat::rmNearestTiesToEven);
4437*9880d681SAndroid Build Coastguard Worker     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4438*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4439*9880d681SAndroid Build Coastguard Worker           Pred == ICmpInst::ICMP_SGE)
4440*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getTrue());
4441*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(I, Builder->getFalse());
4442*9880d681SAndroid Build Coastguard Worker     }
4443*9880d681SAndroid Build Coastguard Worker   } else {
4444*9880d681SAndroid Build Coastguard Worker     // See if the RHS value is < UnsignedMin.
4445*9880d681SAndroid Build Coastguard Worker     APFloat SMin(RHS.getSemantics());
4446*9880d681SAndroid Build Coastguard Worker     SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4447*9880d681SAndroid Build Coastguard Worker                           APFloat::rmNearestTiesToEven);
4448*9880d681SAndroid Build Coastguard Worker     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4449*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4450*9880d681SAndroid Build Coastguard Worker           Pred == ICmpInst::ICMP_UGE)
4451*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getTrue());
4452*9880d681SAndroid Build Coastguard Worker       return replaceInstUsesWith(I, Builder->getFalse());
4453*9880d681SAndroid Build Coastguard Worker     }
4454*9880d681SAndroid Build Coastguard Worker   }
4455*9880d681SAndroid Build Coastguard Worker 
4456*9880d681SAndroid Build Coastguard Worker   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4457*9880d681SAndroid Build Coastguard Worker   // [0, UMAX], but it may still be fractional.  See if it is fractional by
4458*9880d681SAndroid Build Coastguard Worker   // casting the FP value to the integer value and back, checking for equality.
4459*9880d681SAndroid Build Coastguard Worker   // Don't do this for zero, because -0.0 is not fractional.
4460*9880d681SAndroid Build Coastguard Worker   Constant *RHSInt = LHSUnsigned
4461*9880d681SAndroid Build Coastguard Worker     ? ConstantExpr::getFPToUI(RHSC, IntTy)
4462*9880d681SAndroid Build Coastguard Worker     : ConstantExpr::getFPToSI(RHSC, IntTy);
4463*9880d681SAndroid Build Coastguard Worker   if (!RHS.isZero()) {
4464*9880d681SAndroid Build Coastguard Worker     bool Equal = LHSUnsigned
4465*9880d681SAndroid Build Coastguard Worker       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4466*9880d681SAndroid Build Coastguard Worker       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4467*9880d681SAndroid Build Coastguard Worker     if (!Equal) {
4468*9880d681SAndroid Build Coastguard Worker       // If we had a comparison against a fractional value, we have to adjust
4469*9880d681SAndroid Build Coastguard Worker       // the compare predicate and sometimes the value.  RHSC is rounded towards
4470*9880d681SAndroid Build Coastguard Worker       // zero at this point.
4471*9880d681SAndroid Build Coastguard Worker       switch (Pred) {
4472*9880d681SAndroid Build Coastguard Worker       default: llvm_unreachable("Unexpected integer comparison!");
4473*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
4474*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getTrue());
4475*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
4476*9880d681SAndroid Build Coastguard Worker         return replaceInstUsesWith(I, Builder->getFalse());
4477*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_ULE:
4478*9880d681SAndroid Build Coastguard Worker         // (float)int <= 4.4   --> int <= 4
4479*9880d681SAndroid Build Coastguard Worker         // (float)int <= -4.4  --> false
4480*9880d681SAndroid Build Coastguard Worker         if (RHS.isNegative())
4481*9880d681SAndroid Build Coastguard Worker           return replaceInstUsesWith(I, Builder->getFalse());
4482*9880d681SAndroid Build Coastguard Worker         break;
4483*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_SLE:
4484*9880d681SAndroid Build Coastguard Worker         // (float)int <= 4.4   --> int <= 4
4485*9880d681SAndroid Build Coastguard Worker         // (float)int <= -4.4  --> int < -4
4486*9880d681SAndroid Build Coastguard Worker         if (RHS.isNegative())
4487*9880d681SAndroid Build Coastguard Worker           Pred = ICmpInst::ICMP_SLT;
4488*9880d681SAndroid Build Coastguard Worker         break;
4489*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_ULT:
4490*9880d681SAndroid Build Coastguard Worker         // (float)int < -4.4   --> false
4491*9880d681SAndroid Build Coastguard Worker         // (float)int < 4.4    --> int <= 4
4492*9880d681SAndroid Build Coastguard Worker         if (RHS.isNegative())
4493*9880d681SAndroid Build Coastguard Worker           return replaceInstUsesWith(I, Builder->getFalse());
4494*9880d681SAndroid Build Coastguard Worker         Pred = ICmpInst::ICMP_ULE;
4495*9880d681SAndroid Build Coastguard Worker         break;
4496*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_SLT:
4497*9880d681SAndroid Build Coastguard Worker         // (float)int < -4.4   --> int < -4
4498*9880d681SAndroid Build Coastguard Worker         // (float)int < 4.4    --> int <= 4
4499*9880d681SAndroid Build Coastguard Worker         if (!RHS.isNegative())
4500*9880d681SAndroid Build Coastguard Worker           Pred = ICmpInst::ICMP_SLE;
4501*9880d681SAndroid Build Coastguard Worker         break;
4502*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_UGT:
4503*9880d681SAndroid Build Coastguard Worker         // (float)int > 4.4    --> int > 4
4504*9880d681SAndroid Build Coastguard Worker         // (float)int > -4.4   --> true
4505*9880d681SAndroid Build Coastguard Worker         if (RHS.isNegative())
4506*9880d681SAndroid Build Coastguard Worker           return replaceInstUsesWith(I, Builder->getTrue());
4507*9880d681SAndroid Build Coastguard Worker         break;
4508*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_SGT:
4509*9880d681SAndroid Build Coastguard Worker         // (float)int > 4.4    --> int > 4
4510*9880d681SAndroid Build Coastguard Worker         // (float)int > -4.4   --> int >= -4
4511*9880d681SAndroid Build Coastguard Worker         if (RHS.isNegative())
4512*9880d681SAndroid Build Coastguard Worker           Pred = ICmpInst::ICMP_SGE;
4513*9880d681SAndroid Build Coastguard Worker         break;
4514*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_UGE:
4515*9880d681SAndroid Build Coastguard Worker         // (float)int >= -4.4   --> true
4516*9880d681SAndroid Build Coastguard Worker         // (float)int >= 4.4    --> int > 4
4517*9880d681SAndroid Build Coastguard Worker         if (RHS.isNegative())
4518*9880d681SAndroid Build Coastguard Worker           return replaceInstUsesWith(I, Builder->getTrue());
4519*9880d681SAndroid Build Coastguard Worker         Pred = ICmpInst::ICMP_UGT;
4520*9880d681SAndroid Build Coastguard Worker         break;
4521*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_SGE:
4522*9880d681SAndroid Build Coastguard Worker         // (float)int >= -4.4   --> int >= -4
4523*9880d681SAndroid Build Coastguard Worker         // (float)int >= 4.4    --> int > 4
4524*9880d681SAndroid Build Coastguard Worker         if (!RHS.isNegative())
4525*9880d681SAndroid Build Coastguard Worker           Pred = ICmpInst::ICMP_SGT;
4526*9880d681SAndroid Build Coastguard Worker         break;
4527*9880d681SAndroid Build Coastguard Worker       }
4528*9880d681SAndroid Build Coastguard Worker     }
4529*9880d681SAndroid Build Coastguard Worker   }
4530*9880d681SAndroid Build Coastguard Worker 
4531*9880d681SAndroid Build Coastguard Worker   // Lower this FP comparison into an appropriate integer version of the
4532*9880d681SAndroid Build Coastguard Worker   // comparison.
4533*9880d681SAndroid Build Coastguard Worker   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4534*9880d681SAndroid Build Coastguard Worker }
4535*9880d681SAndroid Build Coastguard Worker 
visitFCmpInst(FCmpInst & I)4536*9880d681SAndroid Build Coastguard Worker Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4537*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
4538*9880d681SAndroid Build Coastguard Worker 
4539*9880d681SAndroid Build Coastguard Worker   /// Orders the operands of the compare so that they are listed from most
4540*9880d681SAndroid Build Coastguard Worker   /// complex to least complex.  This puts constants before unary operators,
4541*9880d681SAndroid Build Coastguard Worker   /// before binary operators.
4542*9880d681SAndroid Build Coastguard Worker   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4543*9880d681SAndroid Build Coastguard Worker     I.swapOperands();
4544*9880d681SAndroid Build Coastguard Worker     Changed = true;
4545*9880d681SAndroid Build Coastguard Worker   }
4546*9880d681SAndroid Build Coastguard Worker 
4547*9880d681SAndroid Build Coastguard Worker   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4548*9880d681SAndroid Build Coastguard Worker 
4549*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
4550*9880d681SAndroid Build Coastguard Worker                                   I.getFastMathFlags(), DL, TLI, DT, AC, &I))
4551*9880d681SAndroid Build Coastguard Worker     return replaceInstUsesWith(I, V);
4552*9880d681SAndroid Build Coastguard Worker 
4553*9880d681SAndroid Build Coastguard Worker   // Simplify 'fcmp pred X, X'
4554*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1) {
4555*9880d681SAndroid Build Coastguard Worker     switch (I.getPredicate()) {
4556*9880d681SAndroid Build Coastguard Worker     default: llvm_unreachable("Unknown predicate!");
4557*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4558*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4559*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4560*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4561*9880d681SAndroid Build Coastguard Worker       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4562*9880d681SAndroid Build Coastguard Worker       I.setPredicate(FCmpInst::FCMP_UNO);
4563*9880d681SAndroid Build Coastguard Worker       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4564*9880d681SAndroid Build Coastguard Worker       return &I;
4565*9880d681SAndroid Build Coastguard Worker 
4566*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4567*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4568*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4569*9880d681SAndroid Build Coastguard Worker     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4570*9880d681SAndroid Build Coastguard Worker       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4571*9880d681SAndroid Build Coastguard Worker       I.setPredicate(FCmpInst::FCMP_ORD);
4572*9880d681SAndroid Build Coastguard Worker       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4573*9880d681SAndroid Build Coastguard Worker       return &I;
4574*9880d681SAndroid Build Coastguard Worker     }
4575*9880d681SAndroid Build Coastguard Worker   }
4576*9880d681SAndroid Build Coastguard Worker 
4577*9880d681SAndroid Build Coastguard Worker   // Test if the FCmpInst instruction is used exclusively by a select as
4578*9880d681SAndroid Build Coastguard Worker   // part of a minimum or maximum operation. If so, refrain from doing
4579*9880d681SAndroid Build Coastguard Worker   // any other folding. This helps out other analyses which understand
4580*9880d681SAndroid Build Coastguard Worker   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4581*9880d681SAndroid Build Coastguard Worker   // and CodeGen. And in this case, at least one of the comparison
4582*9880d681SAndroid Build Coastguard Worker   // operands has at least one user besides the compare (the select),
4583*9880d681SAndroid Build Coastguard Worker   // which would often largely negate the benefit of folding anyway.
4584*9880d681SAndroid Build Coastguard Worker   if (I.hasOneUse())
4585*9880d681SAndroid Build Coastguard Worker     if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4586*9880d681SAndroid Build Coastguard Worker       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4587*9880d681SAndroid Build Coastguard Worker           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4588*9880d681SAndroid Build Coastguard Worker         return nullptr;
4589*9880d681SAndroid Build Coastguard Worker 
4590*9880d681SAndroid Build Coastguard Worker   // Handle fcmp with constant RHS
4591*9880d681SAndroid Build Coastguard Worker   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4592*9880d681SAndroid Build Coastguard Worker     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4593*9880d681SAndroid Build Coastguard Worker       switch (LHSI->getOpcode()) {
4594*9880d681SAndroid Build Coastguard Worker       case Instruction::FPExt: {
4595*9880d681SAndroid Build Coastguard Worker         // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4596*9880d681SAndroid Build Coastguard Worker         FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4597*9880d681SAndroid Build Coastguard Worker         ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4598*9880d681SAndroid Build Coastguard Worker         if (!RHSF)
4599*9880d681SAndroid Build Coastguard Worker           break;
4600*9880d681SAndroid Build Coastguard Worker 
4601*9880d681SAndroid Build Coastguard Worker         const fltSemantics *Sem;
4602*9880d681SAndroid Build Coastguard Worker         // FIXME: This shouldn't be here.
4603*9880d681SAndroid Build Coastguard Worker         if (LHSExt->getSrcTy()->isHalfTy())
4604*9880d681SAndroid Build Coastguard Worker           Sem = &APFloat::IEEEhalf;
4605*9880d681SAndroid Build Coastguard Worker         else if (LHSExt->getSrcTy()->isFloatTy())
4606*9880d681SAndroid Build Coastguard Worker           Sem = &APFloat::IEEEsingle;
4607*9880d681SAndroid Build Coastguard Worker         else if (LHSExt->getSrcTy()->isDoubleTy())
4608*9880d681SAndroid Build Coastguard Worker           Sem = &APFloat::IEEEdouble;
4609*9880d681SAndroid Build Coastguard Worker         else if (LHSExt->getSrcTy()->isFP128Ty())
4610*9880d681SAndroid Build Coastguard Worker           Sem = &APFloat::IEEEquad;
4611*9880d681SAndroid Build Coastguard Worker         else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4612*9880d681SAndroid Build Coastguard Worker           Sem = &APFloat::x87DoubleExtended;
4613*9880d681SAndroid Build Coastguard Worker         else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4614*9880d681SAndroid Build Coastguard Worker           Sem = &APFloat::PPCDoubleDouble;
4615*9880d681SAndroid Build Coastguard Worker         else
4616*9880d681SAndroid Build Coastguard Worker           break;
4617*9880d681SAndroid Build Coastguard Worker 
4618*9880d681SAndroid Build Coastguard Worker         bool Lossy;
4619*9880d681SAndroid Build Coastguard Worker         APFloat F = RHSF->getValueAPF();
4620*9880d681SAndroid Build Coastguard Worker         F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4621*9880d681SAndroid Build Coastguard Worker 
4622*9880d681SAndroid Build Coastguard Worker         // Avoid lossy conversions and denormals. Zero is a special case
4623*9880d681SAndroid Build Coastguard Worker         // that's OK to convert.
4624*9880d681SAndroid Build Coastguard Worker         APFloat Fabs = F;
4625*9880d681SAndroid Build Coastguard Worker         Fabs.clearSign();
4626*9880d681SAndroid Build Coastguard Worker         if (!Lossy &&
4627*9880d681SAndroid Build Coastguard Worker             ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4628*9880d681SAndroid Build Coastguard Worker                  APFloat::cmpLessThan) || Fabs.isZero()))
4629*9880d681SAndroid Build Coastguard Worker 
4630*9880d681SAndroid Build Coastguard Worker           return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4631*9880d681SAndroid Build Coastguard Worker                               ConstantFP::get(RHSC->getContext(), F));
4632*9880d681SAndroid Build Coastguard Worker         break;
4633*9880d681SAndroid Build Coastguard Worker       }
4634*9880d681SAndroid Build Coastguard Worker       case Instruction::PHI:
4635*9880d681SAndroid Build Coastguard Worker         // Only fold fcmp into the PHI if the phi and fcmp are in the same
4636*9880d681SAndroid Build Coastguard Worker         // block.  If in the same block, we're encouraging jump threading.  If
4637*9880d681SAndroid Build Coastguard Worker         // not, we are just pessimizing the code by making an i1 phi.
4638*9880d681SAndroid Build Coastguard Worker         if (LHSI->getParent() == I.getParent())
4639*9880d681SAndroid Build Coastguard Worker           if (Instruction *NV = FoldOpIntoPhi(I))
4640*9880d681SAndroid Build Coastguard Worker             return NV;
4641*9880d681SAndroid Build Coastguard Worker         break;
4642*9880d681SAndroid Build Coastguard Worker       case Instruction::SIToFP:
4643*9880d681SAndroid Build Coastguard Worker       case Instruction::UIToFP:
4644*9880d681SAndroid Build Coastguard Worker         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4645*9880d681SAndroid Build Coastguard Worker           return NV;
4646*9880d681SAndroid Build Coastguard Worker         break;
4647*9880d681SAndroid Build Coastguard Worker       case Instruction::FSub: {
4648*9880d681SAndroid Build Coastguard Worker         // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4649*9880d681SAndroid Build Coastguard Worker         Value *Op;
4650*9880d681SAndroid Build Coastguard Worker         if (match(LHSI, m_FNeg(m_Value(Op))))
4651*9880d681SAndroid Build Coastguard Worker           return new FCmpInst(I.getSwappedPredicate(), Op,
4652*9880d681SAndroid Build Coastguard Worker                               ConstantExpr::getFNeg(RHSC));
4653*9880d681SAndroid Build Coastguard Worker         break;
4654*9880d681SAndroid Build Coastguard Worker       }
4655*9880d681SAndroid Build Coastguard Worker       case Instruction::Load:
4656*9880d681SAndroid Build Coastguard Worker         if (GetElementPtrInst *GEP =
4657*9880d681SAndroid Build Coastguard Worker             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4658*9880d681SAndroid Build Coastguard Worker           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4659*9880d681SAndroid Build Coastguard Worker             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4660*9880d681SAndroid Build Coastguard Worker                 !cast<LoadInst>(LHSI)->isVolatile())
4661*9880d681SAndroid Build Coastguard Worker               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4662*9880d681SAndroid Build Coastguard Worker                 return Res;
4663*9880d681SAndroid Build Coastguard Worker         }
4664*9880d681SAndroid Build Coastguard Worker         break;
4665*9880d681SAndroid Build Coastguard Worker       case Instruction::Call: {
4666*9880d681SAndroid Build Coastguard Worker         if (!RHSC->isNullValue())
4667*9880d681SAndroid Build Coastguard Worker           break;
4668*9880d681SAndroid Build Coastguard Worker 
4669*9880d681SAndroid Build Coastguard Worker         CallInst *CI = cast<CallInst>(LHSI);
4670*9880d681SAndroid Build Coastguard Worker         Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
4671*9880d681SAndroid Build Coastguard Worker         if (IID != Intrinsic::fabs)
4672*9880d681SAndroid Build Coastguard Worker           break;
4673*9880d681SAndroid Build Coastguard Worker 
4674*9880d681SAndroid Build Coastguard Worker         // Various optimization for fabs compared with zero.
4675*9880d681SAndroid Build Coastguard Worker         switch (I.getPredicate()) {
4676*9880d681SAndroid Build Coastguard Worker         default:
4677*9880d681SAndroid Build Coastguard Worker           break;
4678*9880d681SAndroid Build Coastguard Worker         // fabs(x) < 0 --> false
4679*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_OLT:
4680*9880d681SAndroid Build Coastguard Worker           llvm_unreachable("handled by SimplifyFCmpInst");
4681*9880d681SAndroid Build Coastguard Worker         // fabs(x) > 0 --> x != 0
4682*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_OGT:
4683*9880d681SAndroid Build Coastguard Worker           return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4684*9880d681SAndroid Build Coastguard Worker         // fabs(x) <= 0 --> x == 0
4685*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_OLE:
4686*9880d681SAndroid Build Coastguard Worker           return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4687*9880d681SAndroid Build Coastguard Worker         // fabs(x) >= 0 --> !isnan(x)
4688*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_OGE:
4689*9880d681SAndroid Build Coastguard Worker           return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4690*9880d681SAndroid Build Coastguard Worker         // fabs(x) == 0 --> x == 0
4691*9880d681SAndroid Build Coastguard Worker         // fabs(x) != 0 --> x != 0
4692*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_OEQ:
4693*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_UEQ:
4694*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_ONE:
4695*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_UNE:
4696*9880d681SAndroid Build Coastguard Worker           return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
4697*9880d681SAndroid Build Coastguard Worker         }
4698*9880d681SAndroid Build Coastguard Worker       }
4699*9880d681SAndroid Build Coastguard Worker       }
4700*9880d681SAndroid Build Coastguard Worker   }
4701*9880d681SAndroid Build Coastguard Worker 
4702*9880d681SAndroid Build Coastguard Worker   // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
4703*9880d681SAndroid Build Coastguard Worker   Value *X, *Y;
4704*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
4705*9880d681SAndroid Build Coastguard Worker     return new FCmpInst(I.getSwappedPredicate(), X, Y);
4706*9880d681SAndroid Build Coastguard Worker 
4707*9880d681SAndroid Build Coastguard Worker   // fcmp (fpext x), (fpext y) -> fcmp x, y
4708*9880d681SAndroid Build Coastguard Worker   if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4709*9880d681SAndroid Build Coastguard Worker     if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4710*9880d681SAndroid Build Coastguard Worker       if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4711*9880d681SAndroid Build Coastguard Worker         return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4712*9880d681SAndroid Build Coastguard Worker                             RHSExt->getOperand(0));
4713*9880d681SAndroid Build Coastguard Worker 
4714*9880d681SAndroid Build Coastguard Worker   return Changed ? &I : nullptr;
4715*9880d681SAndroid Build Coastguard Worker }
4716