blob: 7f01d58c2ffcf2d75fdcdc27ecf5c7f349fa6ce7 [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Chris Lattner0a8191e2010-01-05 07:50:36 +000025static inline Value *dyn_castNotVal(Value *V) {
26 // If this is not(not(x)) don't return that this is a not: we want the two
27 // not's to be folded first.
28 if (BinaryOperator::isNot(V)) {
29 Value *Operand = BinaryOperator::getNotArgument(V);
Sanjoy Das82ea3d42015-02-24 00:08:41 +000030 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
Chris Lattner0a8191e2010-01-05 07:50:36 +000031 return Operand;
32 }
Craig Topper9d4171a2012-12-20 07:09:41 +000033
Chris Lattner0a8191e2010-01-05 07:50:36 +000034 // Constants can be considered to be not'ed values...
35 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
36 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000037 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000038}
39
Sanjay Patel18549272015-09-08 18:24:36 +000040/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
41/// a three bit mask. It also returns whether it is an ordered predicate by
42/// reference.
Chris Lattner0a8191e2010-01-05 07:50:36 +000043static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
44 isOrdered = false;
45 switch (CC) {
46 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
47 case FCmpInst::FCMP_UNO: return 0; // 000
48 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
49 case FCmpInst::FCMP_UGT: return 1; // 001
50 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
51 case FCmpInst::FCMP_UEQ: return 2; // 010
52 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
53 case FCmpInst::FCMP_UGE: return 3; // 011
54 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
55 case FCmpInst::FCMP_ULT: return 4; // 100
56 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
57 case FCmpInst::FCMP_UNE: return 5; // 101
58 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
59 case FCmpInst::FCMP_ULE: return 6; // 110
60 // True -> 7
61 default:
62 // Not expecting FCMP_FALSE and FCMP_TRUE;
63 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000064 }
65}
66
Sanjay Patel18549272015-09-08 18:24:36 +000067/// This is the complement of getICmpCode, which turns an opcode and two
68/// operands into either a constant true or false, or a brand new ICmp
69/// instruction. The sign is passed in to determine which kind of predicate to
70/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000071static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000073 ICmpInst::Predicate NewPred;
74 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
75 return NewConstant;
76 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000077}
78
Sanjay Patel18549272015-09-08 18:24:36 +000079/// This is the complement of getFCmpCode, which turns an opcode and two
80/// operands into either a FCmp instruction. isordered is passed in to determine
81/// which kind of predicate to use in the new fcmp instruction.
Chris Lattner0a8191e2010-01-05 07:50:36 +000082static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +000083 Value *LHS, Value *RHS,
84 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +000085 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +000086 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +000087 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +000088 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
89 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
90 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
91 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
92 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
93 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
94 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +000095 case 7:
Nick Lewycky8075fd22015-08-14 22:46:49 +000096 if (!isordered)
97 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Owen Andersona8342002011-01-21 19:39:42 +000098 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +000099 }
Chris Lattner067459c2010-03-05 08:46:26 +0000100 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000101}
102
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000103/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
104/// \param I Binary operator to transform.
105/// \return Pointer to node that must replace the original binary operator, or
106/// null pointer if no transformation was made.
107Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
108 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
109
110 // Can't do vectors.
111 if (I.getType()->isVectorTy()) return nullptr;
112
113 // Can only do bitwise ops.
114 unsigned Op = I.getOpcode();
115 if (Op != Instruction::And && Op != Instruction::Or &&
116 Op != Instruction::Xor)
117 return nullptr;
118
119 Value *OldLHS = I.getOperand(0);
120 Value *OldRHS = I.getOperand(1);
121 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
122 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
123 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
124 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
125 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
126 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
127
128 if (!IsBswapLHS && !IsBswapRHS)
129 return nullptr;
130
131 if (!IsBswapLHS && !ConstLHS)
132 return nullptr;
133
134 if (!IsBswapRHS && !ConstRHS)
135 return nullptr;
136
137 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
138 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
139 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
140 Builder->getInt(ConstLHS->getValue().byteSwap());
141
142 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
143 Builder->getInt(ConstRHS->getValue().byteSwap());
144
145 Value *BinOp = nullptr;
146 if (Op == Instruction::And)
147 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
148 else if (Op == Instruction::Or)
149 BinOp = Builder->CreateOr(NewLHS, NewRHS);
150 else //if (Op == Instruction::Xor)
151 BinOp = Builder->CreateXor(NewLHS, NewRHS);
152
153 Module *M = I.getParent()->getParent()->getParent();
154 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
155 return Builder->CreateCall(F, BinOp);
156}
157
Sanjay Patel18549272015-09-08 18:24:36 +0000158/// This handles expressions of the form ((val OP C1) & C2). Where
159/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
160/// guaranteed to be a binary operator.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000161Instruction *InstCombiner::OptAndOp(Instruction *Op,
162 ConstantInt *OpRHS,
163 ConstantInt *AndRHS,
164 BinaryOperator &TheAnd) {
165 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000166 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000167 if (!Op->isShift())
168 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
169
170 switch (Op->getOpcode()) {
171 case Instruction::Xor:
172 if (Op->hasOneUse()) {
173 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
174 Value *And = Builder->CreateAnd(X, AndRHS);
175 And->takeName(Op);
176 return BinaryOperator::CreateXor(And, Together);
177 }
178 break;
179 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000180 if (Op->hasOneUse()){
181 if (Together != OpRHS) {
182 // (X | C1) & C2 --> (X | (C1&C2)) & C2
183 Value *Or = Builder->CreateOr(X, Together);
184 Or->takeName(Op);
185 return BinaryOperator::CreateAnd(Or, AndRHS);
186 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000187
Owen Andersonc237a842010-09-13 17:59:27 +0000188 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
189 if (TogetherCI && !TogetherCI->isZero()){
190 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
191 // NOTE: This reduces the number of bits set in the & mask, which
192 // can expose opportunities for store narrowing.
193 Together = ConstantExpr::getXor(AndRHS, Together);
194 Value *And = Builder->CreateAnd(X, Together);
195 And->takeName(Op);
196 return BinaryOperator::CreateOr(And, OpRHS);
197 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000198 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000199
Chris Lattner0a8191e2010-01-05 07:50:36 +0000200 break;
201 case Instruction::Add:
202 if (Op->hasOneUse()) {
203 // Adding a one to a single bit bit-field should be turned into an XOR
204 // of the bit. First thing to check is to see if this AND is with a
205 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000206 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000207
208 // If there is only one bit set.
209 if (AndRHSV.isPowerOf2()) {
210 // Ok, at this point, we know that we are masking the result of the
211 // ADD down to exactly one bit. If the constant we are adding has
212 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000213 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000214
215 // Check to see if any bits below the one bit set in AndRHSV are set.
216 if ((AddRHS & (AndRHSV-1)) == 0) {
217 // If not, the only thing that can effect the output of the AND is
218 // the bit specified by AndRHSV. If that bit is set, the effect of
219 // the XOR is to toggle the bit. If it is clear, then the ADD has
220 // no effect.
221 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
222 TheAnd.setOperand(0, X);
223 return &TheAnd;
224 } else {
225 // Pull the XOR out of the AND.
226 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
227 NewAnd->takeName(Op);
228 return BinaryOperator::CreateXor(NewAnd, AndRHS);
229 }
230 }
231 }
232 }
233 break;
234
235 case Instruction::Shl: {
236 // We know that the AND will not produce any of the bits shifted in, so if
237 // the anded constant includes them, clear them now!
238 //
239 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
240 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
241 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000242 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000243
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000244 if (CI->getValue() == ShlMask)
245 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000246 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000247
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000248 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000249 TheAnd.setOperand(1, CI);
250 return &TheAnd;
251 }
252 break;
253 }
254 case Instruction::LShr: {
255 // We know that the AND will not produce any of the bits shifted in, so if
256 // the anded constant includes them, clear them now! This only applies to
257 // unsigned shifts, because a signed shr may bring in set bits!
258 //
259 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
260 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
261 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000262 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000263
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000264 if (CI->getValue() == ShrMask)
265 // Masking out bits that the shift already masks.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000266 return ReplaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000267
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000268 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000269 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
270 return &TheAnd;
271 }
272 break;
273 }
274 case Instruction::AShr:
275 // Signed shr.
276 // See if this is shifting in some sign extension, then masking it out
277 // with an and.
278 if (Op->hasOneUse()) {
279 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
280 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
281 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000282 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000283 if (C == AndRHS) { // Masking out bits shifted in.
284 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
285 // Make the argument unsigned.
286 Value *ShVal = Op->getOperand(0);
287 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
288 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
289 }
290 }
291 break;
292 }
Craig Topperf40110f2014-04-25 05:29:35 +0000293 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000294}
295
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000296/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
297/// (V < Lo || V >= Hi). In practice, we emit the more efficient
NAKAMURA Takumi00d2a102012-11-15 00:35:50 +0000298/// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
Chris Lattner0a8191e2010-01-05 07:50:36 +0000299/// whether to treat the V, Lo and HI as signed or not. IB is the location to
300/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000301Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
302 bool isSigned, bool Inside) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000303 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000304 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
305 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000306
Chris Lattner0a8191e2010-01-05 07:50:36 +0000307 if (Inside) {
308 if (Lo == Hi) // Trivially false.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000309 return Builder->getFalse();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000310
311 // V >= Min && V < Hi --> V < Hi
312 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000313 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000314 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000315 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000316 }
317
318 // Emit V-Lo <u Hi-Lo
319 Constant *NegLo = ConstantExpr::getNeg(Lo);
320 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
321 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000322 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000323 }
324
325 if (Lo == Hi) // Trivially true.
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000326 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000327
328 // V < Min || V >= Hi -> V > Hi-1
329 Hi = SubOne(cast<ConstantInt>(Hi));
330 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000331 ICmpInst::Predicate pred = (isSigned ?
Chris Lattner0a8191e2010-01-05 07:50:36 +0000332 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000333 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000334 }
335
336 // Emit V-Lo >u Hi-1-Lo
337 // Note that Hi has already had one subtracted from it, above.
338 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
339 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
340 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000341 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000342}
343
Sanjay Patel18549272015-09-08 18:24:36 +0000344/// Returns true iff Val consists of one contiguous run of 1s with any number
345/// of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
346/// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
347/// not, since all 1s are not contiguous.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000348static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
349 const APInt& V = Val->getValue();
350 uint32_t BitWidth = Val->getType()->getBitWidth();
351 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
352
353 // look for the first zero bit after the run of ones
354 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
355 // look for the first non-zero bit
Craig Topper9d4171a2012-12-20 07:09:41 +0000356 ME = V.getActiveBits();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000357 return true;
358}
359
Sanjay Patel18549272015-09-08 18:24:36 +0000360/// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
361/// whether the operator is a sub. If we can fold one of the following xforms:
Craig Topper9d4171a2012-12-20 07:09:41 +0000362///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000363/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
364/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
365/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +0000366///
367/// return (A +/- B).
368///
369Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
370 ConstantInt *Mask, bool isSub,
371 Instruction &I) {
372 Instruction *LHSI = dyn_cast<Instruction>(LHS);
373 if (!LHSI || LHSI->getNumOperands() != 2 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000374 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000375
376 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
377
378 switch (LHSI->getOpcode()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000379 default: return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000380 case Instruction::And:
381 if (ConstantExpr::getAnd(N, Mask) == Mask) {
382 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Craig Topper9d4171a2012-12-20 07:09:41 +0000383 if ((Mask->getValue().countLeadingZeros() +
384 Mask->getValue().countPopulation()) ==
Chris Lattner0a8191e2010-01-05 07:50:36 +0000385 Mask->getValue().getBitWidth())
386 break;
387
388 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
389 // part, we don't need any explicit masks to take them out of A. If that
390 // is all N is, ignore it.
391 uint32_t MB = 0, ME = 0;
392 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
393 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
394 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Hal Finkel60db0582014-09-07 18:57:58 +0000395 if (MaskedValueIsZero(RHS, Mask, 0, &I))
Chris Lattner0a8191e2010-01-05 07:50:36 +0000396 break;
397 }
398 }
Craig Topperf40110f2014-04-25 05:29:35 +0000399 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000400 case Instruction::Or:
401 case Instruction::Xor:
402 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Craig Topper9d4171a2012-12-20 07:09:41 +0000403 if ((Mask->getValue().countLeadingZeros() +
Chris Lattner0a8191e2010-01-05 07:50:36 +0000404 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
405 && ConstantExpr::getAnd(N, Mask)->isNullValue())
406 break;
Craig Topperf40110f2014-04-25 05:29:35 +0000407 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000408 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000409
Chris Lattner0a8191e2010-01-05 07:50:36 +0000410 if (isSub)
411 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
412 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
413}
414
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415/// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
Craig Topper9d4171a2012-12-20 07:09:41 +0000416/// One of A and B is considered the mask, the other the value. This is
417/// described as the "AMask" or "BMask" part of the enum. If the enum
Owen Anderson3fe002d2010-09-08 22:16:17 +0000418/// contains only "Mask", then both A and B can be considered masks.
419/// If A is the mask, then it was proven, that (A & C) == C. This
420/// is trivial if C == A, or C == 0. If both A and C are constants, this
421/// proof is also easy.
422/// For the following explanations we assume that A is the mask.
Craig Topper9d4171a2012-12-20 07:09:41 +0000423/// The part "AllOnes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424/// if (A & B) == A, or all bits of A are set in B.
425/// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
Craig Topper9d4171a2012-12-20 07:09:41 +0000426/// The part "AllZeroes" declares, that the comparison is true only
Owen Anderson3fe002d2010-09-08 22:16:17 +0000427/// if (A & B) == 0, or all bits of A are cleared in B.
428/// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
Craig Topper9d4171a2012-12-20 07:09:41 +0000429/// The part "Mixed" declares, that (A & B) == C and C might or might not
Owen Anderson3fe002d2010-09-08 22:16:17 +0000430/// contain any number of one bits and zero bits.
431/// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
432/// The Part "Not" means, that in above descriptions "==" should be replaced
433/// by "!=".
434/// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
435/// If the mask A contains a single bit, then the following is equivalent:
436/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
437/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
438enum MaskedICmpType {
439 FoldMskICmp_AMask_AllOnes = 1,
440 FoldMskICmp_AMask_NotAllOnes = 2,
441 FoldMskICmp_BMask_AllOnes = 4,
442 FoldMskICmp_BMask_NotAllOnes = 8,
443 FoldMskICmp_Mask_AllZeroes = 16,
444 FoldMskICmp_Mask_NotAllZeroes = 32,
445 FoldMskICmp_AMask_Mixed = 64,
446 FoldMskICmp_AMask_NotMixed = 128,
447 FoldMskICmp_BMask_Mixed = 256,
448 FoldMskICmp_BMask_NotMixed = 512
449};
450
Sanjay Patel18549272015-09-08 18:24:36 +0000451/// Return the set of pattern classes (from MaskedICmpType)
452/// that (icmp SCC (A & B), C) satisfies.
Craig Topper9d4171a2012-12-20 07:09:41 +0000453static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000454 ICmpInst::Predicate SCC)
455{
456 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
457 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
458 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
459 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
Craig Topperf40110f2014-04-25 05:29:35 +0000460 bool icmp_abit = (ACst && !ACst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000461 ACst->getValue().isPowerOf2());
Craig Topperf40110f2014-04-25 05:29:35 +0000462 bool icmp_bbit = (BCst && !BCst->isZero() &&
Owen Anderson3fe002d2010-09-08 22:16:17 +0000463 BCst->getValue().isPowerOf2());
464 unsigned result = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000465 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000466 // if C is zero, then both A and B qualify as mask
467 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
468 FoldMskICmp_Mask_AllZeroes |
469 FoldMskICmp_AMask_Mixed |
470 FoldMskICmp_BMask_Mixed)
471 : (FoldMskICmp_Mask_NotAllZeroes |
472 FoldMskICmp_Mask_NotAllZeroes |
473 FoldMskICmp_AMask_NotMixed |
474 FoldMskICmp_BMask_NotMixed));
475 if (icmp_abit)
476 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000477 FoldMskICmp_AMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000478 : (FoldMskICmp_AMask_AllOnes |
479 FoldMskICmp_AMask_Mixed));
480 if (icmp_bbit)
481 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000482 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000483 : (FoldMskICmp_BMask_AllOnes |
484 FoldMskICmp_BMask_Mixed));
485 return result;
486 }
487 if (A == C) {
488 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
489 FoldMskICmp_AMask_Mixed)
490 : (FoldMskICmp_AMask_NotAllOnes |
491 FoldMskICmp_AMask_NotMixed));
492 if (icmp_abit)
493 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
494 FoldMskICmp_AMask_NotMixed)
495 : (FoldMskICmp_Mask_AllZeroes |
496 FoldMskICmp_AMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000497 } else if (ACst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000498 ConstantExpr::getAnd(ACst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000499 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
500 : FoldMskICmp_AMask_NotMixed);
501 }
Craig Topperae48cb22012-12-20 07:15:54 +0000502 if (B == C) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000503 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
504 FoldMskICmp_BMask_Mixed)
505 : (FoldMskICmp_BMask_NotAllOnes |
506 FoldMskICmp_BMask_NotMixed));
507 if (icmp_bbit)
508 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
Craig Topper9d4171a2012-12-20 07:09:41 +0000509 FoldMskICmp_BMask_NotMixed)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000510 : (FoldMskICmp_Mask_AllZeroes |
511 FoldMskICmp_BMask_Mixed));
Craig Topperf40110f2014-04-25 05:29:35 +0000512 } else if (BCst && CCst &&
Craig Topperae48cb22012-12-20 07:15:54 +0000513 ConstantExpr::getAnd(BCst, CCst) == CCst) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000514 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
515 : FoldMskICmp_BMask_NotMixed);
516 }
517 return result;
518}
519
Tim Northoverc0756c42013-09-04 11:57:13 +0000520/// Convert an analysis of a masked ICmp into its equivalent if all boolean
521/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
522/// is adjacent to the corresponding normal flag (recording ==), this just
523/// involves swapping those bits over.
524static unsigned conjugateICmpMask(unsigned Mask) {
525 unsigned NewMask;
526 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
527 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
528 FoldMskICmp_BMask_Mixed))
529 << 1;
530
531 NewMask |=
532 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
533 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
534 FoldMskICmp_BMask_NotMixed))
535 >> 1;
536
537 return NewMask;
538}
539
Sanjay Patel18549272015-09-08 18:24:36 +0000540/// Decompose an icmp into the form ((X & Y) pred Z) if possible.
541/// The returned predicate is either == or !=. Returns false if
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000542/// decomposition fails.
543static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
544 Value *&X, Value *&Y, Value *&Z) {
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000545 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
546 if (!C)
547 return false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000548
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000549 switch (I->getPredicate()) {
550 default:
551 return false;
552 case ICmpInst::ICMP_SLT:
553 // X < 0 is equivalent to (X & SignBit) != 0.
554 if (!C->isZero())
555 return false;
556 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
557 Pred = ICmpInst::ICMP_NE;
558 break;
559 case ICmpInst::ICMP_SGT:
560 // X > -1 is equivalent to (X & SignBit) == 0.
561 if (!C->isAllOnesValue())
562 return false;
563 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
564 Pred = ICmpInst::ICMP_EQ;
565 break;
566 case ICmpInst::ICMP_ULT:
567 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
568 if (!C->getValue().isPowerOf2())
569 return false;
570 Y = ConstantInt::get(I->getContext(), -C->getValue());
571 Pred = ICmpInst::ICMP_EQ;
572 break;
573 case ICmpInst::ICMP_UGT:
574 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
575 if (!(C->getValue() + 1).isPowerOf2())
576 return false;
577 Y = ConstantInt::get(I->getContext(), ~C->getValue());
578 Pred = ICmpInst::ICMP_NE;
579 break;
580 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000581
Benjamin Kramer94fc18d2014-02-11 21:09:03 +0000582 X = I->getOperand(0);
583 Z = ConstantInt::getNullValue(C->getType());
584 return true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000585}
586
Sanjay Patel18549272015-09-08 18:24:36 +0000587/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
588/// Return the set of pattern classes (from MaskedICmpType)
589/// that both LHS and RHS satisfy.
Craig Topper9d4171a2012-12-20 07:09:41 +0000590static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000591 Value*& B, Value*& C,
592 Value*& D, Value*& E,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000593 ICmpInst *LHS, ICmpInst *RHS,
594 ICmpInst::Predicate &LHSCC,
595 ICmpInst::Predicate &RHSCC) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000596 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
597 // vectors are not (yet?) supported
598 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
599
600 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000601 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000602 // and L11 & L12 == L21 & L22. The same goes for RHS.
603 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000604 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000605 // above.
606 Value *L1 = LHS->getOperand(0);
607 Value *L2 = LHS->getOperand(1);
608 Value *L11,*L12,*L21,*L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000609 // Check whether the icmp can be decomposed into a bit test.
610 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000611 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000612 } else {
613 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000614 if (!L1->getType()->isIntegerTy()) {
615 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000616 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000617 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
618 // Any icmp can be viewed as being trivially masked; if it allows us to
619 // remove one, it's worth it.
620 L11 = L1;
621 L12 = Constant::getAllOnesValue(L1->getType());
622 }
623
624 if (!L2->getType()->isIntegerTy()) {
625 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000626 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000627 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
628 L21 = L2;
629 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000630 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000631 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000632
633 // Bail if LHS was a icmp that can't be decomposed into an equality.
634 if (!ICmpInst::isEquality(LHSCC))
635 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000636
637 Value *R1 = RHS->getOperand(0);
638 Value *R2 = RHS->getOperand(1);
639 Value *R11,*R12;
640 bool ok = false;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000641 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
642 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
643 A = R11; D = R12;
644 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
645 A = R12; D = R11;
646 } else {
647 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000648 }
Craig Topperf40110f2014-04-25 05:29:35 +0000649 E = R2; R1 = nullptr; ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000650 } else if (R1->getType()->isIntegerTy()) {
651 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
652 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000653 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000654 R11 = R1;
655 R12 = Constant::getAllOnesValue(R1->getType());
656 }
657
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000658 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
659 A = R11; D = R12; E = R2; ok = true;
660 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000661 A = R12; D = R11; E = R2; ok = true;
662 }
663 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000664
665 // Bail if RHS was a icmp that can't be decomposed into an equality.
666 if (!ICmpInst::isEquality(RHSCC))
667 return 0;
668
669 // Look for ANDs in on the right side of the RHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000670 if (!ok && R2->getType()->isIntegerTy()) {
671 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
672 R11 = R2;
673 R12 = Constant::getAllOnesValue(R2->getType());
674 }
675
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000676 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
677 A = R11; D = R12; E = R1; ok = true;
678 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000679 A = R12; D = R11; E = R1; ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000680 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000681 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000682 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000683 }
684 if (!ok)
685 return 0;
686
687 if (L11 == A) {
688 B = L12; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000689 } else if (L12 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000690 B = L11; C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000691 } else if (L21 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000692 B = L22; C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000693 } else if (L22 == A) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000694 B = L21; C = L1;
695 }
696
697 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
698 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
699 return left_type & right_type;
700}
Sanjay Patel18549272015-09-08 18:24:36 +0000701
702/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
703/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000704static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
705 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000706 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000707 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
708 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
709 LHSCC, RHSCC);
Craig Topperf40110f2014-04-25 05:29:35 +0000710 if (mask == 0) return nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000711 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
712 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000713
Tim Northoverc0756c42013-09-04 11:57:13 +0000714 // In full generality:
715 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
716 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
717 //
718 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
719 // equivalent to (icmp (A & X) !Op Y).
720 //
721 // Therefore, we can pretend for the rest of this function that we're dealing
722 // with the conjunction, provided we flip the sense of any comparisons (both
723 // input and output).
724
725 // In most cases we're going to produce an EQ for the "&&" case.
726 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
727 if (!IsAnd) {
728 // Convert the masking analysis into its equivalent with negated
729 // comparisons.
730 mask = conjugateICmpMask(mask);
731 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000732
733 if (mask & FoldMskICmp_Mask_AllZeroes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000734 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000735 // -> (icmp eq (A & (B|D)), 0)
David Majnemer1a3327b2014-11-18 09:31:36 +0000736 Value *newOr = Builder->CreateOr(B, D);
737 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000738 // we can't use C as zero, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000739 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000740 // with B and D, having a single bit set
David Majnemer1a3327b2014-11-18 09:31:36 +0000741 Value *zero = Constant::getNullValue(A->getType());
Owen Anderson3fe002d2010-09-08 22:16:17 +0000742 return Builder->CreateICmp(NEWCC, newAnd, zero);
743 }
Craig Topperae48cb22012-12-20 07:15:54 +0000744 if (mask & FoldMskICmp_BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000745 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000746 // -> (icmp eq (A & (B|D)), (B|D))
David Majnemer1a3327b2014-11-18 09:31:36 +0000747 Value *newOr = Builder->CreateOr(B, D);
748 Value *newAnd = Builder->CreateAnd(A, newOr);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000749 return Builder->CreateICmp(NEWCC, newAnd, newOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000750 }
Craig Topperae48cb22012-12-20 07:15:54 +0000751 if (mask & FoldMskICmp_AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000752 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000753 // -> (icmp eq (A & (B&D)), A)
David Majnemer1a3327b2014-11-18 09:31:36 +0000754 Value *newAnd1 = Builder->CreateAnd(B, D);
755 Value *newAnd = Builder->CreateAnd(A, newAnd1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000756 return Builder->CreateICmp(NEWCC, newAnd, A);
757 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000758
759 // Remaining cases assume at least that B and D are constant, and depend on
760 // their actual values. This isn't strictly, necessary, just a "handle the
761 // easy cases for now" decision.
762 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Craig Topperf40110f2014-04-25 05:29:35 +0000763 if (!BCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000764 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Craig Topperf40110f2014-04-25 05:29:35 +0000765 if (!DCst) return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000766
767 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
768 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
769 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
770 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
771 // Only valid if one of the masks is a superset of the other (check "B&D" is
772 // the same as either B or D).
773 APInt NewMask = BCst->getValue() & DCst->getValue();
774
775 if (NewMask == BCst->getValue())
776 return LHS;
777 else if (NewMask == DCst->getValue())
778 return RHS;
779 }
780 if (mask & FoldMskICmp_AMask_NotAllOnes) {
781 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
782 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
783 // Only valid if one of the masks is a superset of the other (check "B|D" is
784 // the same as either B or D).
785 APInt NewMask = BCst->getValue() | DCst->getValue();
786
787 if (NewMask == BCst->getValue())
788 return LHS;
789 else if (NewMask == DCst->getValue())
790 return RHS;
791 }
Craig Topperae48cb22012-12-20 07:15:54 +0000792 if (mask & FoldMskICmp_BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000793 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000794 // We already know that B & C == C && D & E == E.
795 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
796 // C and E, which are shared by both the mask B and the mask D, don't
797 // contradict, then we can transform to
798 // -> (icmp eq (A & (B|D)), (C|E))
799 // Currently, we only handle the case of B, C, D, and E being constant.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000800 // we can't simply use C and E, because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000801 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000802 // with B and D, having a single bit set
Owen Anderson3fe002d2010-09-08 22:16:17 +0000803 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +0000804 if (!CCst) return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000805 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Craig Topperf40110f2014-04-25 05:29:35 +0000806 if (!ECst) return nullptr;
David Majnemer1a3327b2014-11-18 09:31:36 +0000807 if (LHSCC != NEWCC)
808 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000809 if (RHSCC != NEWCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000810 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Owen Anderson3fe002d2010-09-08 22:16:17 +0000811 // if there is a conflict we should actually return a false for the
812 // whole construct
David Majnemer1a3327b2014-11-18 09:31:36 +0000813 if (((BCst->getValue() & DCst->getValue()) &
814 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000815 return ConstantInt::get(LHS->getType(), !IsAnd);
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000816 Value *newOr1 = Builder->CreateOr(B, D);
817 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
818 Value *newAnd = Builder->CreateAnd(A, newOr1);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000819 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
820 }
Craig Topperf40110f2014-04-25 05:29:35 +0000821 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000822}
823
Erik Ecksteind1817522014-12-03 10:39:15 +0000824/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
825/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
826/// If \p Inverted is true then the check is for the inverted range, e.g.
827/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
828Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
829 bool Inverted) {
830 // Check the lower range comparison, e.g. x >= 0
831 // InstCombine already ensured that if there is a constant it's on the RHS.
832 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
833 if (!RangeStart)
834 return nullptr;
835
836 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
837 Cmp0->getPredicate());
838
839 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
840 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
841 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
842 return nullptr;
843
844 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
845 Cmp1->getPredicate());
846
847 Value *Input = Cmp0->getOperand(0);
848 Value *RangeEnd;
849 if (Cmp1->getOperand(0) == Input) {
850 // For the upper range compare we have: icmp x, n
851 RangeEnd = Cmp1->getOperand(1);
852 } else if (Cmp1->getOperand(1) == Input) {
853 // For the upper range compare we have: icmp n, x
854 RangeEnd = Cmp1->getOperand(0);
855 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
856 } else {
857 return nullptr;
858 }
859
860 // Check the upper range comparison, e.g. x < n
861 ICmpInst::Predicate NewPred;
862 switch (Pred1) {
863 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
864 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
865 default: return nullptr;
866 }
867
868 // This simplification is only valid if the upper range is not negative.
869 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000870 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000871 if (!IsNotNegative)
872 return nullptr;
873
874 if (Inverted)
875 NewPred = ICmpInst::getInversePredicate(NewPred);
876
877 return Builder->CreateICmp(NewPred, Input, RangeEnd);
878}
879
Sanjay Patel18549272015-09-08 18:24:36 +0000880/// Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000881Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000882 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
883
884 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
885 if (PredicatesFoldable(LHSCC, RHSCC)) {
886 if (LHS->getOperand(0) == RHS->getOperand(1) &&
887 LHS->getOperand(1) == RHS->getOperand(0))
888 LHS->swapOperands();
889 if (LHS->getOperand(0) == RHS->getOperand(0) &&
890 LHS->getOperand(1) == RHS->getOperand(1)) {
891 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
892 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
893 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000894 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000895 }
896 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000897
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000898 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000899 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000900 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000901
Erik Ecksteind1817522014-12-03 10:39:15 +0000902 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
903 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
904 return V;
905
906 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
907 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
908 return V;
909
Chris Lattner0a8191e2010-01-05 07:50:36 +0000910 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
911 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
912 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
913 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000914 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000915
Chris Lattner0a8191e2010-01-05 07:50:36 +0000916 if (LHSCst == RHSCst && LHSCC == RHSCC) {
917 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
918 // where C is a power of 2
919 if (LHSCC == ICmpInst::ICMP_ULT &&
920 LHSCst->getValue().isPowerOf2()) {
921 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000922 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000923 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000924
Chris Lattner0a8191e2010-01-05 07:50:36 +0000925 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
926 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
927 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000928 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000929 }
930 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000931
Benjamin Kramer101720f2011-04-28 20:09:57 +0000932 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000933 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000934 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000935 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000936 LHS->hasOneUse() && RHS->hasOneUse()) {
937 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000938 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000939
940 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000941 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000942 if (match(Val2, m_Trunc(m_Value(V))) &&
943 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
944 SmallCst = RHSCst;
945 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000946 } else if (match(Val, m_Trunc(m_Value(V))) &&
947 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000948 SmallCst = LHSCst;
949 BigCst = RHSCst;
950 }
951
952 if (SmallCst && BigCst) {
953 unsigned BigBitSize = BigCst->getType()->getBitWidth();
954 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
955
956 // Check that the low bits are zero.
957 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000958 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000959 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
960 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
961 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
962 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
963 }
964 }
965 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000966
Chris Lattner0a8191e2010-01-05 07:50:36 +0000967 // From here on, we only handle:
968 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000969 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000970
Chris Lattner0a8191e2010-01-05 07:50:36 +0000971 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
972 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
973 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
974 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
975 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000976 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000977
978 // Make a constant range that's the intersection of the two icmp ranges.
979 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000980 ConstantRange LHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000981 ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000982 ConstantRange RHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000983 ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
Anders Carlssonda80afe2011-03-01 15:05:01 +0000984
985 if (LHSRange.intersectWith(RHSRange).isEmptySet())
986 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
987
Chris Lattner0a8191e2010-01-05 07:50:36 +0000988 // We can't fold (ugt x, C) & (sgt x, C2).
989 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000990 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000991
Chris Lattner0a8191e2010-01-05 07:50:36 +0000992 // Ensure that the larger constant is on the RHS.
993 bool ShouldSwap;
994 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000995 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000996 CmpInst::isSigned(RHSCC)))
997 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
998 else
999 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001000
Chris Lattner0a8191e2010-01-05 07:50:36 +00001001 if (ShouldSwap) {
1002 std::swap(LHS, RHS);
1003 std::swap(LHSCst, RHSCst);
1004 std::swap(LHSCC, RHSCC);
1005 }
1006
Dan Gohman4a618822010-02-10 16:03:48 +00001007 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001008 // comparing a value against two constants and and'ing the result
1009 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +00001010 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1011 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +00001012 // are not equal and that the larger constant is on the RHS
1013 assert(LHSCst != RHSCst && "Compares not folded above?");
1014
1015 switch (LHSCC) {
1016 default: llvm_unreachable("Unknown integer condition code!");
1017 case ICmpInst::ICMP_EQ:
1018 switch (RHSCC) {
1019 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001020 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1021 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1022 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +00001023 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001024 }
1025 case ICmpInst::ICMP_NE:
1026 switch (RHSCC) {
1027 default: llvm_unreachable("Unknown integer condition code!");
1028 case ICmpInst::ICMP_ULT:
1029 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001030 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +00001031 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1032 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001033 break; // (X != 13 & X u< 15) -> no change
1034 case ICmpInst::ICMP_SLT:
1035 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001036 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001037 break; // (X != 13 & X s< 15) -> no change
1038 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1039 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1040 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001041 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001042 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001043 // Special case to get the ordering right when the values wrap around
1044 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +00001045 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001046 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001047 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1048 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1049 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001050 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1051 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001052 }
1053 break; // (X != 13 & X != 15) -> no change
1054 }
1055 break;
1056 case ICmpInst::ICMP_ULT:
1057 switch (RHSCC) {
1058 default: llvm_unreachable("Unknown integer condition code!");
1059 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1060 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +00001061 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001062 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1063 break;
1064 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1065 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +00001066 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001067 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1068 break;
1069 }
1070 break;
1071 case ICmpInst::ICMP_SLT:
1072 switch (RHSCC) {
1073 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001074 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1075 break;
1076 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1077 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001078 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001079 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1080 break;
1081 }
1082 break;
1083 case ICmpInst::ICMP_UGT:
1084 switch (RHSCC) {
1085 default: llvm_unreachable("Unknown integer condition code!");
1086 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1087 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001088 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001089 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1090 break;
1091 case ICmpInst::ICMP_NE:
1092 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001093 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001094 break; // (X u> 13 & X != 15) -> no change
1095 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +00001096 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001097 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1098 break;
1099 }
1100 break;
1101 case ICmpInst::ICMP_SGT:
1102 switch (RHSCC) {
1103 default: llvm_unreachable("Unknown integer condition code!");
1104 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1105 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001106 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001107 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1108 break;
1109 case ICmpInst::ICMP_NE:
1110 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001111 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001112 break; // (X s> 13 & X != 15) -> no change
1113 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001114 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001115 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1116 break;
1117 }
1118 break;
1119 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001120
Craig Topperf40110f2014-04-25 05:29:35 +00001121 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001122}
1123
Sanjay Patel18549272015-09-08 18:24:36 +00001124/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1125/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001126Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001127 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1128 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001129 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001130 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001131
Chris Lattner0a8191e2010-01-05 07:50:36 +00001132 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1133 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1134 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1135 // If either of the constants are nans, then the whole thing returns
1136 // false.
1137 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001138 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001139 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001140 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001141
Chris Lattner0a8191e2010-01-05 07:50:36 +00001142 // Handle vector zeros. This occurs because the canonical form of
1143 // "fcmp ord x,x" is "fcmp ord x, 0".
1144 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1145 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001146 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001147 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001148 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001149
Chris Lattner0a8191e2010-01-05 07:50:36 +00001150 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1151 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1152 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001153
1154
Chris Lattner0a8191e2010-01-05 07:50:36 +00001155 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1156 // Swap RHS operands to match LHS.
1157 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1158 std::swap(Op1LHS, Op1RHS);
1159 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001160
Chris Lattner0a8191e2010-01-05 07:50:36 +00001161 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1162 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1163 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001164 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001165 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001166 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001167 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001168 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001169 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001170 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001171
Chris Lattner0a8191e2010-01-05 07:50:36 +00001172 bool Op0Ordered;
1173 bool Op1Ordered;
1174 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1175 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001176 // uno && ord -> false
1177 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1178 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001179 if (Op1Pred == 0) {
1180 std::swap(LHS, RHS);
1181 std::swap(Op0Pred, Op1Pred);
1182 std::swap(Op0Ordered, Op1Ordered);
1183 }
1184 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001185 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001186 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001187 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1188 return LHS;
1189 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001190 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001191
Chris Lattner0a8191e2010-01-05 07:50:36 +00001192 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001193 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001194 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001195 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001196 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001197 }
1198 }
1199
Craig Topperf40110f2014-04-25 05:29:35 +00001200 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001201}
1202
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001203/// Match De Morgan's Laws:
1204/// (~A & ~B) == (~(A | B))
1205/// (~A | ~B) == (~(A & B))
1206static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1207 InstCombiner::BuilderTy *Builder) {
1208 auto Opcode = I.getOpcode();
1209 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1210 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001211 // Flip the logic operation.
1212 if (Opcode == Instruction::And)
1213 Opcode = Instruction::Or;
1214 else
1215 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001216
1217 Value *Op0 = I.getOperand(0);
1218 Value *Op1 = I.getOperand(1);
1219 // TODO: Use pattern matchers instead of dyn_cast.
1220 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1221 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1222 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001223 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1224 I.getName() + ".demorgan");
1225 return BinaryOperator::CreateNot(LogicOp);
1226 }
1227
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001228 // De Morgan's Law in disguise:
1229 // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
1230 // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
1231 Value *A = nullptr;
1232 Value *B = nullptr;
1233 ConstantInt *C1 = nullptr;
1234 if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
1235 match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
1236 // TODO: This check could be loosened to handle different type sizes.
1237 // Alternatively, we could fix the definition of m_Not to recognize a not
1238 // operation hidden by a zext?
1239 if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
1240 C1->isOne()) {
1241 Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
1242 I.getName() + ".demorgan");
1243 Value *Not = Builder->CreateNot(LogicOp);
1244 return CastInst::CreateZExtOrBitCast(Not, I.getType());
1245 }
1246 }
1247
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001248 return nullptr;
1249}
1250
Chris Lattner0a8191e2010-01-05 07:50:36 +00001251Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001252 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1254
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001255 if (Value *V = SimplifyVectorOp(I))
1256 return ReplaceInstUsesWith(I, V);
1257
Chandler Carruth66b31302015-01-04 12:03:27 +00001258 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001259 return ReplaceInstUsesWith(I, V);
1260
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001261 // (A|B)&(A|C) -> A|(B&C) etc
1262 if (Value *V = SimplifyUsingDistributiveLaws(I))
1263 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001264
Craig Topper9d4171a2012-12-20 07:09:41 +00001265 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001266 // purpose is to compute bits we don't care about.
1267 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001268 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001269
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001270 if (Value *V = SimplifyBSwap(I))
1271 return ReplaceInstUsesWith(I, V);
1272
Chris Lattner0a8191e2010-01-05 07:50:36 +00001273 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1274 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001275
1276 // Optimize a variety of ((val OP C1) & C2) combinations...
1277 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1278 Value *Op0LHS = Op0I->getOperand(0);
1279 Value *Op0RHS = Op0I->getOperand(1);
1280 switch (Op0I->getOpcode()) {
1281 default: break;
1282 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001283 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001284 // If the mask is only needed on one incoming arm, push it up.
1285 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001286
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001287 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001288 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001289 // Not masking anything out for the LHS, move to RHS.
1290 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1291 Op0RHS->getName()+".masked");
1292 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1293 }
1294 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001295 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001296 // Not masking anything out for the RHS, move to LHS.
1297 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1298 Op0LHS->getName()+".masked");
1299 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1300 }
1301
1302 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001303 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001304 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001305 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1306 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1307 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001308 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1309 return BinaryOperator::CreateAnd(V, AndRHS);
1310 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1311 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1312 break;
1313
1314 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001315 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1316 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1317 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001318 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1319 return BinaryOperator::CreateAnd(V, AndRHS);
1320
Balaram Makamccf59732015-08-20 15:35:00 +00001321 // -x & 1 -> x & 1
1322 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1323 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1324
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001325 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001326 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001327 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001328 uint32_t BitWidth = AndRHSMask.getBitWidth();
1329 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1330 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1331
Hal Finkel60db0582014-09-07 18:57:58 +00001332 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001333 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1334 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1335 }
1336 }
1337 break;
1338
1339 case Instruction::Shl:
1340 case Instruction::LShr:
1341 // (1 << x) & 1 --> zext(x == 0)
1342 // (1 >> x) & 1 --> zext(x == 0)
1343 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1344 Value *NewICmp =
1345 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1346 return new ZExtInst(NewICmp, I.getType());
1347 }
1348 break;
1349 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001350
Chris Lattner0a8191e2010-01-05 07:50:36 +00001351 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1352 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1353 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001354 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001355
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001356 // If this is an integer truncation, and if the source is an 'and' with
1357 // immediate, transform it. This frequently occurs for bitfield accesses.
1358 {
Craig Topperf40110f2014-04-25 05:29:35 +00001359 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001360 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1361 // Change: and (trunc (and X, YC) to T), C2
1362 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001363 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001364 // other simplifications.
1365 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1366 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1367 C3 = ConstantExpr::getAnd(C3, AndRHS);
1368 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001369 }
1370 }
1371
1372 // Try to fold constant and into select arguments.
1373 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1374 if (Instruction *R = FoldOpIntoSelect(I, SI))
1375 return R;
1376 if (isa<PHINode>(Op0))
1377 if (Instruction *NV = FoldOpIntoPhi(I))
1378 return NV;
1379 }
1380
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001381 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1382 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001383
Chris Lattner0a8191e2010-01-05 07:50:36 +00001384 {
Craig Topperf40110f2014-04-25 05:29:35 +00001385 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001386 // (A|B) & ~(A&B) -> A^B
1387 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1388 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1389 ((A == C && B == D) || (A == D && B == C)))
1390 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001391
Chris Lattner0a8191e2010-01-05 07:50:36 +00001392 // ~(A&B) & (A|B) -> A^B
1393 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1394 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1395 ((A == C && B == D) || (A == D && B == C)))
1396 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001397
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001398 // A&(A^B) => A & ~B
1399 {
1400 Value *tmpOp0 = Op0;
1401 Value *tmpOp1 = Op1;
1402 if (Op0->hasOneUse() &&
1403 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1404 if (A == Op1 || B == Op1 ) {
1405 tmpOp1 = Op0;
1406 tmpOp0 = Op1;
1407 // Simplify below
1408 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001409 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001410
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001411 if (tmpOp1->hasOneUse() &&
1412 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1413 if (B == tmpOp0) {
1414 std::swap(A, B);
1415 }
1416 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1417 // A is originally -1 (or a vector of -1 and undefs), then we enter
1418 // an endless loop. By checking that A is non-constant we ensure that
1419 // we will never get to the loop.
1420 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001421 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001422 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001423 }
1424
1425 // (A&((~A)|B)) -> A&B
1426 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1427 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1428 return BinaryOperator::CreateAnd(A, Op1);
1429 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1430 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1431 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001432
1433 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1434 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1435 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1436 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1437 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1438
1439 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1440 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1441 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1442 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1443 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001444
1445 // (A | B) & ((~A) ^ B) -> (A & B)
1446 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1447 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1448 return BinaryOperator::CreateAnd(A, B);
1449
1450 // ((~A) ^ B) & (A | B) -> (A & B)
1451 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1452 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1453 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001454 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001455
David Majnemer5e96f1b2014-08-30 06:18:20 +00001456 {
1457 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1458 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1459 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001460 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1461 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001462
David Majnemer5e96f1b2014-08-30 06:18:20 +00001463 // TODO: Make this recursive; it's a little tricky because an arbitrary
1464 // number of 'and' instructions might have to be created.
1465 Value *X, *Y;
1466 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1467 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1468 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1469 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1470 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1471 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1472 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1473 }
1474 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1475 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1476 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1477 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1478 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1479 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1480 return ReplaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1481 }
1482 }
1483
Chris Lattner4e8137d2010-02-11 06:26:33 +00001484 // If and'ing two fcmp, try combine them into one.
1485 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1486 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001487 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1488 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001489
1490
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001491 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1492 Value *Op0COp = Op0C->getOperand(0);
1493 Type *SrcTy = Op0COp->getType();
1494 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001495 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001496 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1497 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001498 SrcTy->isIntOrIntVectorTy()) {
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001499 Value *Op1COp = Op1C->getOperand(0);
Craig Topper9d4171a2012-12-20 07:09:41 +00001500
Chris Lattner4e8137d2010-02-11 06:26:33 +00001501 // Only do this if the casts both really cause code to be generated.
1502 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1503 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1504 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001505 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1506 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001507
Chris Lattner4e8137d2010-02-11 06:26:33 +00001508 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1509 // cast is otherwise not optimizable. This happens for vector sexts.
1510 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1511 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001512 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001513 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00001514
Chris Lattner4e8137d2010-02-11 06:26:33 +00001515 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1516 // cast is otherwise not optimizable. This happens for vector sexts.
1517 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1518 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001519 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001520 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001521 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001522 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001523
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001524 // If we are masking off the sign bit of a floating-point value, convert
1525 // this to the canonical fabs intrinsic call and cast back to integer.
1526 // The backend should know how to optimize fabs().
1527 // TODO: This transform should also apply to vectors.
1528 ConstantInt *CI;
1529 if (isa<BitCastInst>(Op0C) && SrcTy->isFloatingPointTy() &&
1530 match(Op1, m_ConstantInt(CI)) && CI->isMaxValue(true)) {
1531 Module *M = I.getParent()->getParent()->getParent();
1532 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, SrcTy);
1533 Value *Call = Builder->CreateCall(Fabs, Op0COp, "fabs");
1534 return CastInst::CreateBitOrPointerCast(Call, I.getType());
1535 }
1536 }
1537
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001538 {
Craig Topperf40110f2014-04-25 05:29:35 +00001539 Value *X = nullptr;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001540 bool OpsSwapped = false;
1541 // Canonicalize SExt or Not to the LHS
1542 if (match(Op1, m_SExt(m_Value())) ||
1543 match(Op1, m_Not(m_Value()))) {
1544 std::swap(Op0, Op1);
1545 OpsSwapped = true;
1546 }
1547
1548 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1549 if (match(Op0, m_SExt(m_Value(X))) &&
1550 X->getType()->getScalarType()->isIntegerTy(1)) {
1551 Value *Zero = Constant::getNullValue(Op1->getType());
1552 return SelectInst::Create(X, Op1, Zero);
1553 }
1554
1555 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1556 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1557 X->getType()->getScalarType()->isIntegerTy(1)) {
1558 Value *Zero = Constant::getNullValue(Op0->getType());
1559 return SelectInst::Create(X, Zero, Op1);
1560 }
1561
1562 if (OpsSwapped)
1563 std::swap(Op0, Op1);
1564 }
1565
Craig Topperf40110f2014-04-25 05:29:35 +00001566 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001567}
1568
James Molloy37b82e72015-12-11 10:04:51 +00001569
Sanjay Patel18549272015-09-08 18:24:36 +00001570/// Analyze the specified subexpression and see if it is capable of providing
James Molloy37b82e72015-12-11 10:04:51 +00001571/// pieces of a bswap or bitreverse. The subexpression provides a potential
1572/// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
1573/// the output of the expression came from a corresponding bit in some other
1574/// value. This function is recursive, and the end result is a mapping of
1575/// (value, bitnumber) to bitnumber. It is the caller's responsibility to
1576/// validate that all `value`s are identical and that the bitnumber to bitnumber
1577/// mapping is correct for a bswap or bitreverse.
1578///
1579/// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
1580/// that the expression deposits the low byte of %X into the high byte of the
1581/// result and that all other bits are zero. This expression is accepted,
1582/// BitValues[24-31] are set to %X and BitProvenance[24-31] are set to [0-7].
Chris Lattner0a8191e2010-01-05 07:50:36 +00001583///
1584/// This function returns true if the match was unsuccessful and false if so.
1585/// On entry to the function the "OverallLeftShift" is a signed integer value
James Molloy37b82e72015-12-11 10:04:51 +00001586/// indicating the number of bits that the subexpression is later shifted. For
Chris Lattner0a8191e2010-01-05 07:50:36 +00001587/// example, if the expression is later right shifted by 16 bits, the
James Molloy37b82e72015-12-11 10:04:51 +00001588/// OverallLeftShift value would be -16 on entry. This is used to specify which
1589/// bits of BitValues are actually being set.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001590///
James Molloy37b82e72015-12-11 10:04:51 +00001591/// Similarly, BitMask is a bitmask where a bit is clear if its corresponding
1592/// bit is masked to zero by a user. For example, in (X & 255), X will be
1593/// processed with a bytemask of 255. BitMask is always in the local
1594/// (OverallLeftShift) coordinate space.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001595///
James Molloy37b82e72015-12-11 10:04:51 +00001596static bool CollectBitParts(Value *V, int OverallLeftShift, APInt BitMask,
1597 SmallVectorImpl<Value *> &BitValues,
1598 SmallVectorImpl<int> &BitProvenance) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001599 if (Instruction *I = dyn_cast<Instruction>(V)) {
1600 // If this is an or instruction, it may be an inner node of the bswap.
James Molloy37b82e72015-12-11 10:04:51 +00001601 if (I->getOpcode() == Instruction::Or)
1602 return CollectBitParts(I->getOperand(0), OverallLeftShift, BitMask,
1603 BitValues, BitProvenance) ||
1604 CollectBitParts(I->getOperand(1), OverallLeftShift, BitMask,
1605 BitValues, BitProvenance);
Craig Topper9d4171a2012-12-20 07:09:41 +00001606
James Molloy37b82e72015-12-11 10:04:51 +00001607 // If this is a logical shift by a constant, recurse with OverallLeftShift
1608 // and BitMask adjusted.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001609 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00001610 unsigned ShAmt =
James Molloy37b82e72015-12-11 10:04:51 +00001611 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1612 // Ensure the shift amount is defined.
1613 if (ShAmt > BitValues.size())
Chris Lattner0a8191e2010-01-05 07:50:36 +00001614 return true;
1615
James Molloy37b82e72015-12-11 10:04:51 +00001616 unsigned BitShift = ShAmt;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001617 if (I->getOpcode() == Instruction::Shl) {
James Molloy37b82e72015-12-11 10:04:51 +00001618 // X << C -> collect(X, +C)
1619 OverallLeftShift += BitShift;
1620 BitMask = BitMask.lshr(BitShift);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001621 } else {
James Molloy37b82e72015-12-11 10:04:51 +00001622 // X >>u C -> collect(X, -C)
1623 OverallLeftShift -= BitShift;
1624 BitMask = BitMask.shl(BitShift);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001625 }
1626
James Molloy37b82e72015-12-11 10:04:51 +00001627 if (OverallLeftShift >= (int)BitValues.size())
1628 return true;
1629 if (OverallLeftShift <= -(int)BitValues.size())
1630 return true;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001631
James Molloy37b82e72015-12-11 10:04:51 +00001632 return CollectBitParts(I->getOperand(0), OverallLeftShift, BitMask,
1633 BitValues, BitProvenance);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001634 }
1635
James Molloy37b82e72015-12-11 10:04:51 +00001636 // If this is a logical 'and' with a mask that clears bits, clear the
1637 // corresponding bits in BitMask.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001638 if (I->getOpcode() == Instruction::And &&
1639 isa<ConstantInt>(I->getOperand(1))) {
James Molloy37b82e72015-12-11 10:04:51 +00001640 unsigned NumBits = BitValues.size();
1641 APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001642 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001643
James Molloy37b82e72015-12-11 10:04:51 +00001644 for (unsigned i = 0; i != NumBits; ++i, Bit <<= 1) {
1645 // If this bit is masked out by a later operation, we don't care what
Chris Lattner0a8191e2010-01-05 07:50:36 +00001646 // the and mask is.
James Molloy37b82e72015-12-11 10:04:51 +00001647 if (BitMask[i] == 0)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001648 continue;
Craig Topper9d4171a2012-12-20 07:09:41 +00001649
James Molloy37b82e72015-12-11 10:04:51 +00001650 // If the AndMask is zero for this bit, clear the bit.
1651 APInt MaskB = AndMask & Bit;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001652 if (MaskB == 0) {
James Molloy37b82e72015-12-11 10:04:51 +00001653 BitMask.clearBit(i);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001654 continue;
1655 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001656
James Molloy37b82e72015-12-11 10:04:51 +00001657 // Otherwise, this bit is kept.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001658 }
1659
James Molloy37b82e72015-12-11 10:04:51 +00001660 return CollectBitParts(I->getOperand(0), OverallLeftShift, BitMask,
1661 BitValues, BitProvenance);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001662 }
1663 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001664
Chris Lattner0a8191e2010-01-05 07:50:36 +00001665 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
James Molloy37b82e72015-12-11 10:04:51 +00001666 // the input value to the bswap/bitreverse. To be part of a bswap or
1667 // bitreverse we must be demanding a contiguous range of bits from it.
1668 unsigned InputBitLen = BitMask.countPopulation();
1669 unsigned InputBitNo = BitMask.countTrailingZeros();
1670 if (BitMask.getBitWidth() - BitMask.countLeadingZeros() - InputBitNo !=
1671 InputBitLen)
1672 // Not a contiguous set range of bits!
Chris Lattnerb1e2e1e2012-03-26 19:13:57 +00001673 return true;
Craig Topper9d4171a2012-12-20 07:09:41 +00001674
James Molloy37b82e72015-12-11 10:04:51 +00001675 // We know we're moving a contiguous range of bits from the input to the
1676 // output. Record which bits in the output came from which bits in the input.
1677 unsigned DestBitNo = InputBitNo + OverallLeftShift;
1678 for (unsigned I = 0; I < InputBitLen; ++I)
1679 BitProvenance[DestBitNo + I] = InputBitNo + I;
1680
1681 // If the destination bit value is already defined, the values are or'd
1682 // together, which isn't a bswap/bitreverse (unless it's an or of the same
1683 // bits).
1684 if (BitValues[DestBitNo] && BitValues[DestBitNo] != V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001685 return true;
James Molloy37b82e72015-12-11 10:04:51 +00001686 for (unsigned I = 0; I < InputBitLen; ++I)
1687 BitValues[DestBitNo + I] = V;
1688
Chris Lattner0a8191e2010-01-05 07:50:36 +00001689 return false;
1690}
1691
James Molloy37b82e72015-12-11 10:04:51 +00001692static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
1693 unsigned BitWidth) {
1694 if (From % 8 != To % 8)
1695 return false;
1696 // Convert from bit indices to byte indices and check for a byte reversal.
1697 From >>= 3;
1698 To >>= 3;
1699 BitWidth >>= 3;
1700 return From == BitWidth - To - 1;
1701}
1702
1703static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
1704 unsigned BitWidth) {
1705 return From == BitWidth - To - 1;
1706}
1707
1708/// Given an OR instruction, check to see if this is a bswap or bitreverse
1709/// idiom. If so, insert the new intrinsic and return it.
1710Instruction *InstCombiner::MatchBSwapOrBitReverse(BinaryOperator &I) {
Jay Foadb804a2b2011-07-12 14:06:48 +00001711 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
James Molloy37b82e72015-12-11 10:04:51 +00001712 if (!ITy)
1713 return nullptr; // Can't do vectors.
1714 unsigned BW = ITy->getBitWidth();
1715
1716 /// We keep track of which bit (BitProvenance) inside which value (BitValues)
1717 /// defines each bit in the result.
1718 SmallVector<Value *, 8> BitValues(BW, nullptr);
1719 SmallVector<int, 8> BitProvenance(BW, -1);
1720
Chris Lattner0a8191e2010-01-05 07:50:36 +00001721 // Try to find all the pieces corresponding to the bswap.
James Molloy37b82e72015-12-11 10:04:51 +00001722 APInt BitMask = APInt::getAllOnesValue(BitValues.size());
1723 if (CollectBitParts(&I, 0, BitMask, BitValues, BitProvenance))
Craig Topperf40110f2014-04-25 05:29:35 +00001724 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001725
James Molloy37b82e72015-12-11 10:04:51 +00001726 // Check to see if all of the bits come from the same value.
1727 Value *V = BitValues[0];
1728 if (!V) return nullptr; // Didn't find a bit? Must be zero.
Craig Topper9d4171a2012-12-20 07:09:41 +00001729
James Molloy37b82e72015-12-11 10:04:51 +00001730 if (!std::all_of(BitValues.begin(), BitValues.end(),
1731 [&](const Value *X) { return X == V; }))
1732 return nullptr;
1733
1734 // Now, is the bit permutation correct for a bswap or a bitreverse? We can
1735 // only byteswap values with an even number of bytes.
1736 bool OKForBSwap = BW % 16 == 0, OKForBitReverse = true;;
1737 for (unsigned i = 0, e = BitValues.size(); i != e; ++i) {
1738 OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[i], i, BW);
1739 OKForBitReverse &=
1740 bitTransformIsCorrectForBitReverse(BitProvenance[i], i, BW);
1741 }
1742
1743 Intrinsic::ID Intrin;
1744 if (OKForBSwap)
1745 Intrin = Intrinsic::bswap;
1746 else if (OKForBitReverse)
1747 Intrin = Intrinsic::bitreverse;
1748 else
1749 return nullptr;
1750
Chris Lattner0a8191e2010-01-05 07:50:36 +00001751 Module *M = I.getParent()->getParent()->getParent();
James Molloy37b82e72015-12-11 10:04:51 +00001752 Function *F = Intrinsic::getDeclaration(M, Intrin, ITy);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001753 return CallInst::Create(F, V);
1754}
1755
Sanjay Patel18549272015-09-08 18:24:36 +00001756/// We have an expression of the form (A&C)|(B&D). Check if A is (cond?-1:0)
1757/// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
1758/// expression to "cond ? C : D or B".
Chris Lattner0a8191e2010-01-05 07:50:36 +00001759static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1760 Value *C, Value *D) {
1761 // If A is not a select of -1/0, this cannot match.
Craig Topperf40110f2014-04-25 05:29:35 +00001762 Value *Cond = nullptr;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001763 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001764 !Cond->getType()->isIntegerTy(1))
Craig Topperf40110f2014-04-25 05:29:35 +00001765 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001766
1767 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001768 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001769 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001770 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001771 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001772
Chris Lattner0a8191e2010-01-05 07:50:36 +00001773 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001774 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001775 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001776 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001777 return SelectInst::Create(Cond, C, D);
Craig Topperf40110f2014-04-25 05:29:35 +00001778 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001779}
1780
Sanjay Patel18549272015-09-08 18:24:36 +00001781/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001782Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1783 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001784 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1785
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001786 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1787 // if K1 and K2 are a one-bit mask.
1788 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1789 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1790
1791 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1792 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1793
1794 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1795 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1796 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1797 LAnd->getOpcode() == Instruction::And &&
1798 RAnd->getOpcode() == Instruction::And) {
1799
Craig Topperf40110f2014-04-25 05:29:35 +00001800 Value *Mask = nullptr;
1801 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001802 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001803 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1804 DT) &&
1805 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1806 DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001807 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1808 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1809 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001810 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1811 CxtI, DT) &&
1812 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1813 CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001814 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1815 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1816 }
1817
1818 if (Masked)
1819 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1820 }
1821 }
1822
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001823 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1824 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1825 // The original condition actually refers to the following two ranges:
1826 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1827 // We can fold these two ranges if:
1828 // 1) C1 and C2 is unsigned greater than C3.
1829 // 2) The two ranges are separated.
1830 // 3) C1 ^ C2 is one-bit mask.
1831 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1832 // This implies all values in the two ranges differ by exactly one bit.
1833
1834 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1835 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1836 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1837 LHSCst->getValue() == (RHSCst->getValue())) {
1838
1839 Value *LAdd = LHS->getOperand(0);
1840 Value *RAdd = RHS->getOperand(0);
1841
1842 Value *LAddOpnd, *RAddOpnd;
1843 ConstantInt *LAddCst, *RAddCst;
1844 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1845 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1846 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1847 RAddCst->getValue().ugt(LHSCst->getValue())) {
1848
1849 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1850 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1851 ConstantInt *MaxAddCst = nullptr;
1852 if (LAddCst->getValue().ult(RAddCst->getValue()))
1853 MaxAddCst = RAddCst;
1854 else
1855 MaxAddCst = LAddCst;
1856
1857 APInt RRangeLow = -RAddCst->getValue();
1858 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1859 APInt LRangeLow = -LAddCst->getValue();
1860 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1861 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1862 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1863 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1864 : RRangeLow - LRangeLow;
1865
1866 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1867 RangeDiff.ugt(LHSCst->getValue())) {
1868 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1869
1870 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1871 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1872 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1873 }
1874 }
1875 }
1876 }
1877
Chris Lattner0a8191e2010-01-05 07:50:36 +00001878 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1879 if (PredicatesFoldable(LHSCC, RHSCC)) {
1880 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1881 LHS->getOperand(1) == RHS->getOperand(0))
1882 LHS->swapOperands();
1883 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1884 LHS->getOperand(1) == RHS->getOperand(1)) {
1885 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1886 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1887 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001888 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001889 }
1890 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001891
1892 // handle (roughly):
1893 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001894 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001895 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001896
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001898 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1899 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1900 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001901 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001902 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1903 B = Val;
1904 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1905 A = Val2;
1906 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1907 A = RHS->getOperand(1);
1908 }
1909 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1910 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1911 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1912 B = Val2;
1913 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1914 A = Val;
1915 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1916 A = LHS->getOperand(1);
1917 }
1918 if (A && B)
1919 return Builder->CreateICmp(
1920 ICmpInst::ICMP_UGE,
1921 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1922 }
1923
Erik Ecksteind1817522014-12-03 10:39:15 +00001924 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1925 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1926 return V;
1927
1928 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1929 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1930 return V;
1931
David Majnemerc2a990b2013-07-05 00:31:17 +00001932 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001933 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001934
Owen Anderson8f306a72010-08-02 09:32:13 +00001935 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1936 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1937 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1938 Value *NewOr = Builder->CreateOr(Val, Val2);
1939 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1940 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001941 }
1942
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001943 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001944 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001945 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001946 ConstantInt *AddCst;
1947 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1948 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001949 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001950 }
1951
Chris Lattner0a8191e2010-01-05 07:50:36 +00001952 // From here on, we only handle:
1953 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001954 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001955
Chris Lattner0a8191e2010-01-05 07:50:36 +00001956 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1957 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1958 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1959 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1960 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001961 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001962
Chris Lattner0a8191e2010-01-05 07:50:36 +00001963 // We can't fold (ugt x, C) | (sgt x, C2).
1964 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001965 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001966
Chris Lattner0a8191e2010-01-05 07:50:36 +00001967 // Ensure that the larger constant is on the RHS.
1968 bool ShouldSwap;
1969 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001970 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001971 CmpInst::isSigned(RHSCC)))
1972 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1973 else
1974 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001975
Chris Lattner0a8191e2010-01-05 07:50:36 +00001976 if (ShouldSwap) {
1977 std::swap(LHS, RHS);
1978 std::swap(LHSCst, RHSCst);
1979 std::swap(LHSCC, RHSCC);
1980 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001981
Dan Gohman4a618822010-02-10 16:03:48 +00001982 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001983 // comparing a value against two constants and or'ing the result
1984 // together. Because of the above check, we know that we only have
1985 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1986 // icmp folding check above), that the two constants are not
1987 // equal.
1988 assert(LHSCst != RHSCst && "Compares not folded above?");
1989
1990 switch (LHSCC) {
1991 default: llvm_unreachable("Unknown integer condition code!");
1992 case ICmpInst::ICMP_EQ:
1993 switch (RHSCC) {
1994 default: llvm_unreachable("Unknown integer condition code!");
1995 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001996 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001997 // if LHSCst and RHSCst differ only by one bit:
David Majnemer942003a2015-12-02 16:15:07 +00001998 // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001999 assert(LHSCst->getValue().ule(LHSCst->getValue()));
2000
Jakub Staszakea2b9b92012-12-31 00:34:55 +00002001 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
2002 if (Xor.isPowerOf2()) {
David Majnemer942003a2015-12-02 16:15:07 +00002003 Value *Cst = Builder->getInt(Xor);
2004 Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
2005 return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
Jakub Staszakea2b9b92012-12-31 00:34:55 +00002006 }
2007 }
2008
David Majnemer1fae1952013-04-14 21:15:43 +00002009 if (LHSCst == SubOne(RHSCst)) {
2010 // (X == 13 | X == 14) -> X-13 <u 2
2011 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2012 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
2013 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2014 return Builder->CreateICmpULT(Add, AddCST);
2015 }
2016
Chris Lattner0a8191e2010-01-05 07:50:36 +00002017 break; // (X == 13 | X == 15) -> no change
2018 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
2019 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
2020 break;
2021 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
2022 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
2023 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00002024 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002025 }
2026 break;
2027 case ICmpInst::ICMP_NE:
2028 switch (RHSCC) {
2029 default: llvm_unreachable("Unknown integer condition code!");
2030 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
2031 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
2032 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00002033 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002034 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
2035 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
2036 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002037 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002038 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002039 case ICmpInst::ICMP_ULT:
2040 switch (RHSCC) {
2041 default: llvm_unreachable("Unknown integer condition code!");
2042 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2043 break;
2044 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2045 // If RHSCst is [us]MAXINT, it is always false. Not handling
2046 // this can cause overflow.
2047 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00002048 return LHS;
2049 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002050 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
2051 break;
2052 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
2053 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00002054 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002055 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
2056 break;
2057 }
2058 break;
2059 case ICmpInst::ICMP_SLT:
2060 switch (RHSCC) {
2061 default: llvm_unreachable("Unknown integer condition code!");
2062 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
2063 break;
2064 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
2065 // If RHSCst is [us]MAXINT, it is always false. Not handling
2066 // this can cause overflow.
2067 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00002068 return LHS;
2069 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002070 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
2071 break;
2072 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
2073 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00002074 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002075 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
2076 break;
2077 }
2078 break;
2079 case ICmpInst::ICMP_UGT:
2080 switch (RHSCC) {
2081 default: llvm_unreachable("Unknown integer condition code!");
2082 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
2083 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00002084 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002085 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
2086 break;
2087 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
2088 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002089 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002090 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
2091 break;
2092 }
2093 break;
2094 case ICmpInst::ICMP_SGT:
2095 switch (RHSCC) {
2096 default: llvm_unreachable("Unknown integer condition code!");
2097 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
2098 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00002099 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002100 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
2101 break;
2102 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
2103 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002104 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002105 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
2106 break;
2107 }
2108 break;
2109 }
Craig Topperf40110f2014-04-25 05:29:35 +00002110 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002111}
2112
Sanjay Patel18549272015-09-08 18:24:36 +00002113/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
2114/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00002115Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002116 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002117 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002118 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2119 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2120 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2121 // If either of the constants are nans, then the whole thing returns
2122 // true.
2123 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002124 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002125
Chris Lattner0a8191e2010-01-05 07:50:36 +00002126 // Otherwise, no need to compare the two constants, compare the
2127 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002128 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002129 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002130
Chris Lattner0a8191e2010-01-05 07:50:36 +00002131 // Handle vector zeros. This occurs because the canonical form of
2132 // "fcmp uno x,x" is "fcmp uno x, 0".
2133 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2134 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002135 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002136
Craig Topperf40110f2014-04-25 05:29:35 +00002137 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002138 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002139
Chris Lattner0a8191e2010-01-05 07:50:36 +00002140 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2141 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2142 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00002143
Chris Lattner0a8191e2010-01-05 07:50:36 +00002144 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2145 // Swap RHS operands to match LHS.
2146 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2147 std::swap(Op1LHS, Op1RHS);
2148 }
2149 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
2150 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2151 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00002152 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002153 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00002154 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002155 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002156 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002157 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00002158 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002159 bool Op0Ordered;
2160 bool Op1Ordered;
2161 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2162 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2163 if (Op0Ordered == Op1Ordered) {
2164 // If both are ordered or unordered, return a new fcmp with
2165 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00002166 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002167 }
2168 }
Craig Topperf40110f2014-04-25 05:29:35 +00002169 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002170}
2171
Sanjay Patel18549272015-09-08 18:24:36 +00002172/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00002173///
2174/// ((A | B) & C1) | (B & C2)
2175///
2176/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002177///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002178/// (A & C1) | B
2179///
2180/// when the XOR of the two constants is "all ones" (-1).
2181Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2182 Value *A, Value *B, Value *C) {
2183 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002184 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002185
Craig Topperf40110f2014-04-25 05:29:35 +00002186 Value *V1 = nullptr;
2187 ConstantInt *CI2 = nullptr;
2188 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002189
2190 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002191 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002192
2193 if (V1 == A || V1 == B) {
2194 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2195 return BinaryOperator::CreateOr(NewOp, V1);
2196 }
2197
Craig Topperf40110f2014-04-25 05:29:35 +00002198 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002199}
2200
David Majnemer5d1aeba2014-08-21 05:14:48 +00002201/// \brief This helper function folds:
2202///
2203/// ((A | B) & C1) ^ (B & C2)
2204///
2205/// into:
2206///
2207/// (A & C1) ^ B
2208///
2209/// when the XOR of the two constants is "all ones" (-1).
2210Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2211 Value *A, Value *B, Value *C) {
2212 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2213 if (!CI1)
2214 return nullptr;
2215
2216 Value *V1 = nullptr;
2217 ConstantInt *CI2 = nullptr;
2218 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2219 return nullptr;
2220
2221 APInt Xor = CI1->getValue() ^ CI2->getValue();
2222 if (!Xor.isAllOnesValue())
2223 return nullptr;
2224
2225 if (V1 == A || V1 == B) {
2226 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2227 return BinaryOperator::CreateXor(NewOp, V1);
2228 }
2229
2230 return nullptr;
2231}
2232
Chris Lattner0a8191e2010-01-05 07:50:36 +00002233Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002234 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2236
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002237 if (Value *V = SimplifyVectorOp(I))
2238 return ReplaceInstUsesWith(I, V);
2239
Chandler Carruth66b31302015-01-04 12:03:27 +00002240 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002241 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002242
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002243 // (A&B)|(A&C) -> A&(B|C) etc
2244 if (Value *V = SimplifyUsingDistributiveLaws(I))
2245 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002246
Craig Topper9d4171a2012-12-20 07:09:41 +00002247 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002248 // purpose is to compute bits we don't care about.
2249 if (SimplifyDemandedInstructionBits(I))
2250 return &I;
2251
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002252 if (Value *V = SimplifyBSwap(I))
2253 return ReplaceInstUsesWith(I, V);
2254
Chris Lattner0a8191e2010-01-05 07:50:36 +00002255 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002256 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002257 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002258 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002259 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002260 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002261 Op0->hasOneUse()) {
2262 Value *Or = Builder->CreateOr(X, RHS);
2263 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002264 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002265 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002266 }
2267
2268 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2269 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2270 Op0->hasOneUse()) {
2271 Value *Or = Builder->CreateOr(X, RHS);
2272 Or->takeName(Op0);
2273 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002274 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002275 }
2276
2277 // Try to fold constant and into select arguments.
2278 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2279 if (Instruction *R = FoldOpIntoSelect(I, SI))
2280 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002281
Chris Lattner0a8191e2010-01-05 07:50:36 +00002282 if (isa<PHINode>(Op0))
2283 if (Instruction *NV = FoldOpIntoPhi(I))
2284 return NV;
2285 }
2286
Craig Topperf40110f2014-04-25 05:29:35 +00002287 Value *A = nullptr, *B = nullptr;
2288 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002289
2290 // (A | B) | C and A | (B | C) -> bswap if possible.
Charlie Turner27205932015-09-24 10:24:58 +00002291 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
2292 match(Op1, m_Or(m_Value(), m_Value()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002293 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Charlie Turner27205932015-09-24 10:24:58 +00002294 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2295 match(Op1, m_LogicalShift(m_Value(), m_Value()));
2296 // (A & B) | (C & D) -> bswap if possible.
2297 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
2298 match(Op1, m_And(m_Value(), m_Value()));
2299
2300 if (OrOfOrs || OrOfShifts || OrOfAnds)
James Molloy37b82e72015-12-11 10:04:51 +00002301 if (Instruction *BSwap = MatchBSwapOrBitReverse(I))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002302 return BSwap;
Craig Topper9d4171a2012-12-20 07:09:41 +00002303
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002304 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002305 if (Op0->hasOneUse() &&
2306 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002307 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002308 Value *NOr = Builder->CreateOr(A, Op1);
2309 NOr->takeName(Op0);
2310 return BinaryOperator::CreateXor(NOr, C1);
2311 }
2312
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002313 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002314 if (Op1->hasOneUse() &&
2315 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002316 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002317 Value *NOr = Builder->CreateOr(A, Op0);
2318 NOr->takeName(Op0);
2319 return BinaryOperator::CreateXor(NOr, C1);
2320 }
2321
Suyog Sardad64faf62014-07-22 18:09:41 +00002322 // ((~A & B) | A) -> (A | B)
2323 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2324 match(Op1, m_Specific(A)))
2325 return BinaryOperator::CreateOr(A, B);
2326
2327 // ((A & B) | ~A) -> (~A | B)
2328 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2329 match(Op1, m_Not(m_Specific(A))))
2330 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2331
Suyog Sarda52324c82014-08-01 04:50:31 +00002332 // (A & (~B)) | (A ^ B) -> (A ^ B)
2333 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2334 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2335 return BinaryOperator::CreateXor(A, B);
2336
2337 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2338 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2339 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2340 return BinaryOperator::CreateXor(A, B);
2341
Chris Lattner0a8191e2010-01-05 07:50:36 +00002342 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002343 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002344 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2345 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002346 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002347 C1 = dyn_cast<ConstantInt>(C);
2348 C2 = dyn_cast<ConstantInt>(D);
2349 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002350 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002351 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002352 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002353 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002354 ((V1 == B &&
2355 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2356 (V2 == B &&
2357 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002358 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002359 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002360 // Or commutes, try both ways.
2361 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002362 ((V1 == A &&
2363 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2364 (V2 == A &&
2365 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002366 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002367 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002368
Chris Lattner95188692010-01-11 06:55:24 +00002369 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002370 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002371 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002372 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2373 (C3->getValue() & ~C1->getValue()) == 0 &&
2374 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2375 (C4->getValue() & ~C2->getValue()) == 0) {
2376 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2377 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002378 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002379 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002380 }
2381 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002382
Chris Lattner8e2c4712010-02-02 02:43:51 +00002383 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2384 // Don't do this for vector select idioms, the code generator doesn't handle
2385 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002386 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002387 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2388 return Match;
2389 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2390 return Match;
2391 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2392 return Match;
2393 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2394 return Match;
2395 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002396
2397 // ((A&~B)|(~A&B)) -> A^B
2398 if ((match(C, m_Not(m_Specific(D))) &&
2399 match(B, m_Not(m_Specific(A)))))
2400 return BinaryOperator::CreateXor(A, D);
2401 // ((~B&A)|(~A&B)) -> A^B
2402 if ((match(A, m_Not(m_Specific(D))) &&
2403 match(B, m_Not(m_Specific(C)))))
2404 return BinaryOperator::CreateXor(C, D);
2405 // ((A&~B)|(B&~A)) -> A^B
2406 if ((match(C, m_Not(m_Specific(B))) &&
2407 match(D, m_Not(m_Specific(A)))))
2408 return BinaryOperator::CreateXor(A, B);
2409 // ((~B&A)|(B&~A)) -> A^B
2410 if ((match(A, m_Not(m_Specific(B))) &&
2411 match(D, m_Not(m_Specific(C)))))
2412 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002413
2414 // ((A|B)&1)|(B&-2) -> (A&1) | B
2415 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2416 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2417 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2418 if (Ret) return Ret;
2419 }
2420 // (B&-2)|((A|B)&1) -> (A&1) | B
2421 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2422 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2423 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2424 if (Ret) return Ret;
2425 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002426 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2427 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2428 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2429 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2430 if (Ret) return Ret;
2431 }
2432 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2433 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2434 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2435 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2436 if (Ret) return Ret;
2437 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002438 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002439
David Majnemer42af3602014-07-30 21:26:37 +00002440 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2441 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2442 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2443 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2444 return BinaryOperator::CreateOr(Op0, C);
2445
2446 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2447 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2448 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2449 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2450 return BinaryOperator::CreateOr(Op1, C);
2451
David Majnemerf1eda232014-08-14 06:41:38 +00002452 // ((B | C) & A) | B -> B | (A & C)
2453 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2454 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2455
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002456 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2457 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002458
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002459 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002460 bool SwappedForXor = false;
2461 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002462 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002463 SwappedForXor = true;
2464 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002465
2466 // A | ( A ^ B) -> A | B
2467 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002468 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002469 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2470 if (Op0 == A || Op0 == B)
2471 return BinaryOperator::CreateOr(A, B);
2472
Chad Rosier7813dce2012-04-26 23:29:14 +00002473 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2474 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2475 return BinaryOperator::CreateOr(A, B);
2476
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002477 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2478 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2479 return BinaryOperator::CreateOr(Not, Op0);
2480 }
2481 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2482 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2483 return BinaryOperator::CreateOr(Not, Op0);
2484 }
2485 }
2486
2487 // A | ~(A | B) -> A | ~B
2488 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002489 if (match(Op1, m_Not(m_Value(A))))
2490 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002491 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2492 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2493 B->getOpcode() == Instruction::Xor)) {
2494 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2495 B->getOperand(0);
2496 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2497 return BinaryOperator::CreateOr(Not, Op0);
2498 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002499
Suyog Sarda16d64652014-08-01 04:41:43 +00002500 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2501 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2502 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2503 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2504
2505 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2506 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2507 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2508 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2509
Eli Friedmane06535b2012-03-16 00:52:42 +00002510 if (SwappedForXor)
2511 std::swap(Op0, Op1);
2512
David Majnemer3d6f80b2014-11-28 19:58:29 +00002513 {
2514 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2515 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2516 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002517 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner067459c2010-03-05 08:46:26 +00002518 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002519
David Majnemer3d6f80b2014-11-28 19:58:29 +00002520 // TODO: Make this recursive; it's a little tricky because an arbitrary
2521 // number of 'or' instructions might have to be created.
2522 Value *X, *Y;
2523 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2524 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2525 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2526 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2527 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2528 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2529 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2530 }
2531 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2532 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2533 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2534 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2535 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2536 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2537 return ReplaceInstUsesWith(I, Builder->CreateOr(Res, X));
2538 }
2539 }
2540
Chris Lattner4e8137d2010-02-11 06:26:33 +00002541 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2542 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2543 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002544 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2545 return ReplaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002546
Chris Lattner0a8191e2010-01-05 07:50:36 +00002547 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2548 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002549 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2550 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002551 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002552 if (SrcTy == Op1C->getOperand(0)->getType() &&
2553 SrcTy->isIntOrIntVectorTy()) {
2554 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002555
Chris Lattner311aa632011-01-15 05:40:29 +00002556 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2557 // Only do this if the casts both really cause code to be
2558 // generated.
2559 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2560 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2561 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2562 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002563 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002564
Chris Lattner311aa632011-01-15 05:40:29 +00002565 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2566 // cast is otherwise not optimizable. This happens for vector sexts.
2567 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2568 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Hal Finkel60db0582014-09-07 18:57:58 +00002569 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner311aa632011-01-15 05:40:29 +00002570 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002571
Chris Lattner311aa632011-01-15 05:40:29 +00002572 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2573 // cast is otherwise not optimizable. This happens for vector sexts.
2574 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2575 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2576 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2577 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002578 }
Chris Lattner311aa632011-01-15 05:40:29 +00002579 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002580 }
Eli Friedman23956262011-04-14 22:41:27 +00002581
2582 // or(sext(A), B) -> A ? -1 : B where A is an i1
2583 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2584 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2585 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2586 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2587 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2588
Owen Andersonc237a842010-09-13 17:59:27 +00002589 // Note: If we've gotten to the point of visiting the outer OR, then the
2590 // inner one couldn't be simplified. If it was a constant, then it won't
2591 // be simplified by a later pass either, so we try swapping the inner/outer
2592 // ORs in the hopes that we'll be able to simplify it this way.
2593 // (X|C) | V --> (X|V) | C
2594 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2595 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2596 Value *Inner = Builder->CreateOr(A, Op1);
2597 Inner->takeName(Op0);
2598 return BinaryOperator::CreateOr(Inner, C1);
2599 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002600
Bill Wendling23242092013-02-16 23:41:36 +00002601 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2602 // Since this OR statement hasn't been optimized further yet, we hope
2603 // that this transformation will allow the new ORs to be optimized.
2604 {
Craig Topperf40110f2014-04-25 05:29:35 +00002605 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002606 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2607 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2608 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2609 Value *orTrue = Builder->CreateOr(A, C);
2610 Value *orFalse = Builder->CreateOr(B, D);
2611 return SelectInst::Create(X, orTrue, orFalse);
2612 }
2613 }
2614
Craig Topperf40110f2014-04-25 05:29:35 +00002615 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002616}
2617
2618Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002619 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002622 if (Value *V = SimplifyVectorOp(I))
2623 return ReplaceInstUsesWith(I, V);
2624
Chandler Carruth66b31302015-01-04 12:03:27 +00002625 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002626 return ReplaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002627
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002628 // (A&B)^(A&C) -> A&(B^C) etc
2629 if (Value *V = SimplifyUsingDistributiveLaws(I))
2630 return ReplaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002631
Craig Topper9d4171a2012-12-20 07:09:41 +00002632 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002633 // purpose is to compute bits we don't care about.
2634 if (SimplifyDemandedInstructionBits(I))
2635 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002636
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002637 if (Value *V = SimplifyBSwap(I))
2638 return ReplaceInstUsesWith(I, V);
2639
Chris Lattner0a8191e2010-01-05 07:50:36 +00002640 // Is this a ~ operation?
2641 if (Value *NotOp = dyn_castNotVal(&I)) {
2642 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002643 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002644 Op0I->getOpcode() == Instruction::Or) {
2645 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2646 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2647 if (dyn_castNotVal(Op0I->getOperand(1)))
2648 Op0I->swapOperands();
2649 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2650 Value *NotY =
2651 Builder->CreateNot(Op0I->getOperand(1),
2652 Op0I->getOperand(1)->getName()+".not");
2653 if (Op0I->getOpcode() == Instruction::And)
2654 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2655 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2656 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002657
Chris Lattner0a8191e2010-01-05 07:50:36 +00002658 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2659 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002660 if (IsFreeToInvert(Op0I->getOperand(0),
2661 Op0I->getOperand(0)->hasOneUse()) &&
2662 IsFreeToInvert(Op0I->getOperand(1),
2663 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002664 Value *NotX =
2665 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2666 Value *NotY =
2667 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2668 if (Op0I->getOpcode() == Instruction::And)
2669 return BinaryOperator::CreateOr(NotX, NotY);
2670 return BinaryOperator::CreateAnd(NotX, NotY);
2671 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002672
2673 } else if (Op0I->getOpcode() == Instruction::AShr) {
2674 // ~(~X >>s Y) --> (X >>s Y)
2675 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2676 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002677 }
2678 }
2679 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002680
Benjamin Kramer443c7962015-02-12 20:26:46 +00002681 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2682 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002683 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002684 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2685 return CmpInst::Create(CI->getOpcode(),
2686 CI->getInversePredicate(),
2687 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002688 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002689
Benjamin Kramer443c7962015-02-12 20:26:46 +00002690 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002691 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2692 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2693 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2694 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2695 Instruction::CastOps Opcode = Op0C->getOpcode();
2696 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002697 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002698 Op0C->getDestTy()))) {
2699 CI->setPredicate(CI->getInversePredicate());
2700 return CastInst::Create(Opcode, CI, Op0C->getType());
2701 }
2702 }
2703 }
2704 }
2705
2706 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2707 // ~(c-X) == X-c-1 == X+(-c-1)
2708 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2709 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2710 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2711 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2712 ConstantInt::get(I.getType(), 1));
2713 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2714 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002715
Chris Lattner0a8191e2010-01-05 07:50:36 +00002716 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2717 if (Op0I->getOpcode() == Instruction::Add) {
2718 // ~(X-c) --> (-c-1)-X
2719 if (RHS->isAllOnesValue()) {
2720 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2721 return BinaryOperator::CreateSub(
2722 ConstantExpr::getSub(NegOp0CI,
2723 ConstantInt::get(I.getType(), 1)),
2724 Op0I->getOperand(0));
2725 } else if (RHS->getValue().isSignBit()) {
2726 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002727 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002728 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2729
2730 }
2731 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002732 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002733 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2734 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002735 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2736 // Anything in both C1 and C2 is known to be zero, remove it from
2737 // NewRHS.
2738 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002739 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002740 ConstantExpr::getNot(CommonBits));
2741 Worklist.Add(Op0I);
2742 I.setOperand(0, Op0I->getOperand(0));
2743 I.setOperand(1, NewRHS);
2744 return &I;
2745 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002746 } else if (Op0I->getOpcode() == Instruction::LShr) {
2747 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2748 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002749 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002750 ConstantInt *C1;
2751 if (Op0I->hasOneUse() &&
2752 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2753 E1->getOpcode() == Instruction::Xor &&
2754 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2755 // fold (C1 >> C2) ^ C3
2756 ConstantInt *C2 = Op0CI, *C3 = RHS;
2757 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2758 FoldConst ^= C3->getValue();
2759 // Prepare the two operands.
2760 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2761 Opnd0->takeName(Op0I);
2762 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2763 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2764
2765 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2766 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002767 }
2768 }
2769 }
2770
2771 // Try to fold constant and into select arguments.
2772 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2773 if (Instruction *R = FoldOpIntoSelect(I, SI))
2774 return R;
2775 if (isa<PHINode>(Op0))
2776 if (Instruction *NV = FoldOpIntoPhi(I))
2777 return NV;
2778 }
2779
Chris Lattner0a8191e2010-01-05 07:50:36 +00002780 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2781 if (Op1I) {
2782 Value *A, *B;
2783 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2784 if (A == Op0) { // B^(B|A) == (A|B)^B
2785 Op1I->swapOperands();
2786 I.swapOperands();
2787 std::swap(Op0, Op1);
2788 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2789 I.swapOperands(); // Simplified below.
2790 std::swap(Op0, Op1);
2791 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002792 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002793 Op1I->hasOneUse()){
2794 if (A == Op0) { // A^(A&B) -> A^(B&A)
2795 Op1I->swapOperands();
2796 std::swap(A, B);
2797 }
2798 if (B == Op0) { // A^(B&A) -> (B&A)^A
2799 I.swapOperands(); // Simplified below.
2800 std::swap(Op0, Op1);
2801 }
2802 }
2803 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002804
Chris Lattner0a8191e2010-01-05 07:50:36 +00002805 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2806 if (Op0I) {
2807 Value *A, *B;
2808 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2809 Op0I->hasOneUse()) {
2810 if (A == Op1) // (B|A)^B == (A|B)^B
2811 std::swap(A, B);
2812 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002813 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002814 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002815 Op0I->hasOneUse()){
2816 if (A == Op1) // (A&B)^A -> (B&A)^A
2817 std::swap(A, B);
2818 if (B == Op1 && // (B&A)^A == ~B & A
2819 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002820 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002821 }
2822 }
2823 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002824
Chris Lattner0a8191e2010-01-05 07:50:36 +00002825 if (Op0I && Op1I) {
2826 Value *A, *B, *C, *D;
2827 // (A & B)^(A | B) -> A ^ B
2828 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2829 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002830 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002831 return BinaryOperator::CreateXor(A, B);
2832 }
2833 // (A | B)^(A & B) -> A ^ B
2834 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2835 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002836 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002837 return BinaryOperator::CreateXor(A, B);
2838 }
David Majnemer698dca02014-08-14 06:46:25 +00002839 // (A | ~B) ^ (~A | B) -> A ^ B
2840 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2841 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2842 return BinaryOperator::CreateXor(A, B);
2843 }
2844 // (~A | B) ^ (A | ~B) -> A ^ B
2845 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2846 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2847 return BinaryOperator::CreateXor(A, B);
2848 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002849 // (A & ~B) ^ (~A & B) -> A ^ B
2850 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2851 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2852 return BinaryOperator::CreateXor(A, B);
2853 }
2854 // (~A & B) ^ (A & ~B) -> A ^ B
2855 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2856 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2857 return BinaryOperator::CreateXor(A, B);
2858 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002859 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2860 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2861 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2862 if (D == A)
2863 return BinaryOperator::CreateXor(
2864 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2865 if (D == B)
2866 return BinaryOperator::CreateXor(
2867 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002868 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002869 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002870 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002871 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2872 if (D == A)
2873 return BinaryOperator::CreateXor(
2874 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2875 if (D == B)
2876 return BinaryOperator::CreateXor(
2877 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002878 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002879 // (A & B) ^ (A ^ B) -> (A | B)
2880 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2881 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2882 return BinaryOperator::CreateOr(A, B);
2883 // (A ^ B) ^ (A & B) -> (A | B)
2884 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2885 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2886 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002887 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002888
Suyog Sarda521237c2014-07-22 15:37:39 +00002889 Value *A = nullptr, *B = nullptr;
Suyog Sarda56c9a872014-08-01 05:07:20 +00002890 // (A & ~B) ^ (~A) -> ~(A & B)
2891 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2892 match(Op1, m_Not(m_Specific(A))))
2893 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2894
Chris Lattner0a8191e2010-01-05 07:50:36 +00002895 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2896 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2897 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2898 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2899 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2900 LHS->getOperand(1) == RHS->getOperand(0))
2901 LHS->swapOperands();
2902 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2903 LHS->getOperand(1) == RHS->getOperand(1)) {
2904 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2905 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2906 bool isSigned = LHS->isSigned() || RHS->isSigned();
Craig Topper9d4171a2012-12-20 07:09:41 +00002907 return ReplaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002908 getNewICmpValue(isSigned, Code, Op0, Op1,
2909 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002910 }
2911 }
2912
2913 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2914 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2915 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2916 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002917 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002918 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002919 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002920 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002921 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002922 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002923 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002924 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2925 Op1C->getOperand(0), I.getName());
2926 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2927 }
2928 }
2929 }
2930
Craig Topperf40110f2014-04-25 05:29:35 +00002931 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002932}