blob: b38ec7007de641629f7b9c7c798e06c2baec1c2e [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"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Chris Lattner0a8191e2010-01-05 07:50:36 +000026static inline Value *dyn_castNotVal(Value *V) {
27 // If this is not(not(x)) don't return that this is a not: we want the two
28 // not's to be folded first.
29 if (BinaryOperator::isNot(V)) {
30 Value *Operand = BinaryOperator::getNotArgument(V);
Sanjoy Das82ea3d42015-02-24 00:08:41 +000031 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
Chris Lattner0a8191e2010-01-05 07:50:36 +000032 return Operand;
33 }
Craig Topper9d4171a2012-12-20 07:09:41 +000034
Chris Lattner0a8191e2010-01-05 07:50:36 +000035 // Constants can be considered to be not'ed values...
36 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000038 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000039}
40
Sanjay Patel18549272015-09-08 18:24:36 +000041/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
42/// a three bit mask. It also returns whether it is an ordered predicate by
43/// reference.
Chris Lattner0a8191e2010-01-05 07:50:36 +000044static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
45 isOrdered = false;
46 switch (CC) {
47 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
48 case FCmpInst::FCMP_UNO: return 0; // 000
49 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
50 case FCmpInst::FCMP_UGT: return 1; // 001
51 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
52 case FCmpInst::FCMP_UEQ: return 2; // 010
53 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
54 case FCmpInst::FCMP_UGE: return 3; // 011
55 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
56 case FCmpInst::FCMP_ULT: return 4; // 100
57 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
58 case FCmpInst::FCMP_UNE: return 5; // 101
59 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
60 case FCmpInst::FCMP_ULE: return 6; // 110
61 // True -> 7
62 default:
63 // Not expecting FCMP_FALSE and FCMP_TRUE;
64 llvm_unreachable("Unexpected FCmp predicate!");
Chris Lattner0a8191e2010-01-05 07:50:36 +000065 }
66}
67
Sanjay Patel18549272015-09-08 18:24:36 +000068/// This is the complement of getICmpCode, which turns an opcode and two
69/// operands into either a constant true or false, or a brand new ICmp
70/// instruction. The sign is passed in to determine which kind of predicate to
71/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000072static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
73 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000074 ICmpInst::Predicate NewPred;
75 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
76 return NewConstant;
77 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000078}
79
Sanjay Patel18549272015-09-08 18:24:36 +000080/// This is the complement of getFCmpCode, which turns an opcode and two
81/// operands into either a FCmp instruction. isordered is passed in to determine
82/// which kind of predicate to use in the new fcmp instruction.
Chris Lattner0a8191e2010-01-05 07:50:36 +000083static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +000084 Value *LHS, Value *RHS,
85 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +000086 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +000087 switch (code) {
Craig Toppera2886c22012-02-07 05:05:23 +000088 default: llvm_unreachable("Illegal FCmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +000089 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
90 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
91 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
92 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
93 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
94 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
95 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
Craig Topper9d4171a2012-12-20 07:09:41 +000096 case 7:
Nick Lewycky8075fd22015-08-14 22:46:49 +000097 if (!isordered)
98 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Owen Andersona8342002011-01-21 19:39:42 +000099 Pred = FCmpInst::FCMP_ORD; break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000100 }
Chris Lattner067459c2010-03-05 08:46:26 +0000101 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000102}
103
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000104/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
105/// \param I Binary operator to transform.
106/// \return Pointer to node that must replace the original binary operator, or
107/// null pointer if no transformation was made.
108Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
109 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
110
111 // Can't do vectors.
112 if (I.getType()->isVectorTy()) return nullptr;
113
114 // Can only do bitwise ops.
115 unsigned Op = I.getOpcode();
116 if (Op != Instruction::And && Op != Instruction::Or &&
117 Op != Instruction::Xor)
118 return nullptr;
119
120 Value *OldLHS = I.getOperand(0);
121 Value *OldRHS = I.getOperand(1);
122 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
123 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
124 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
125 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
126 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
127 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
128
129 if (!IsBswapLHS && !IsBswapRHS)
130 return nullptr;
131
132 if (!IsBswapLHS && !ConstLHS)
133 return nullptr;
134
135 if (!IsBswapRHS && !ConstRHS)
136 return nullptr;
137
138 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
139 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
140 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
141 Builder->getInt(ConstLHS->getValue().byteSwap());
142
143 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
144 Builder->getInt(ConstRHS->getValue().byteSwap());
145
146 Value *BinOp = nullptr;
147 if (Op == Instruction::And)
148 BinOp = Builder->CreateAnd(NewLHS, NewRHS);
149 else if (Op == Instruction::Or)
150 BinOp = Builder->CreateOr(NewLHS, NewRHS);
151 else //if (Op == Instruction::Xor)
152 BinOp = Builder->CreateXor(NewLHS, NewRHS);
153
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000154 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000155 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.
Sanjay Patel4b198802016-02-01 22:23:39 +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.
Sanjay Patel4b198802016-02-01 22:23:39 +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
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000697 unsigned LeftType = getTypeOfMaskedICmp(A, B, C, LHSCC);
698 unsigned RightType = getTypeOfMaskedICmp(A, D, E, RHSCC);
699 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000700}
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();
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000708 unsigned Mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000709 LHSCC, RHSCC);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +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.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000726 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000727 if (!IsAnd) {
728 // Convert the masking analysis into its equivalent with negated
729 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000730 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000731 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000732
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000733 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)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000736 Value *NewOr = Builder->CreateOr(B, D);
737 Value *NewAnd = Builder->CreateAnd(A, NewOr);
738 // 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)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000740 // with B and D, having a single bit set.
741 Value *Zero = Constant::getNullValue(A->getType());
742 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000743 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +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))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000747 Value *NewOr = Builder->CreateOr(B, D);
748 Value *NewAnd = Builder->CreateAnd(A, NewOr);
749 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000750 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +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)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000754 Value *NewAnd1 = Builder->CreateAnd(B, D);
755 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
756 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000757 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000758
759 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000760 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000761 // 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
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000767 if (Mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000768 // (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 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000780 if (Mask & FoldMskICmp_AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000781 // (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 }
Sanjay Patel3b8dcc72016-01-18 18:28:09 +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.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +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)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +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;
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000807 if (LHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000808 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000809 if (RHSCC != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000810 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel3b8dcc72016-01-18 18:28:09 +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);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000816 Value *NewOr1 = Builder->CreateOr(B, D);
817 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
818 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
819 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000820 }
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)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000918 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000919 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000920 if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
921 (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000922 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000923 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000924 }
925 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000926
Benjamin Kramer101720f2011-04-28 20:09:57 +0000927 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000928 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000929 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000930 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000931 LHS->hasOneUse() && RHS->hasOneUse()) {
932 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000933 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000934
935 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000936 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000937 if (match(Val2, m_Trunc(m_Value(V))) &&
938 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
939 SmallCst = RHSCst;
940 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000941 } else if (match(Val, m_Trunc(m_Value(V))) &&
942 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000943 SmallCst = LHSCst;
944 BigCst = RHSCst;
945 }
946
947 if (SmallCst && BigCst) {
948 unsigned BigBitSize = BigCst->getType()->getBitWidth();
949 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
950
951 // Check that the low bits are zero.
952 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000953 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000954 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
955 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
956 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
957 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
958 }
959 }
960 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000961
Chris Lattner0a8191e2010-01-05 07:50:36 +0000962 // From here on, we only handle:
963 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000964 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000965
Chris Lattner0a8191e2010-01-05 07:50:36 +0000966 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
967 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
968 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
969 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
970 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000971 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000972
973 // Make a constant range that's the intersection of the two icmp ranges.
974 // If the intersection is empty, we know that the result is false.
Craig Topper9d4171a2012-12-20 07:09:41 +0000975 ConstantRange LHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000976 ConstantRange::makeAllowedICmpRegion(LHSCC, LHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000977 ConstantRange RHSRange =
Sanjoy Das7182d362015-03-18 00:41:24 +0000978 ConstantRange::makeAllowedICmpRegion(RHSCC, RHSCst->getValue());
Anders Carlssonda80afe2011-03-01 15:05:01 +0000979
980 if (LHSRange.intersectWith(RHSRange).isEmptySet())
981 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
982
Chris Lattner0a8191e2010-01-05 07:50:36 +0000983 // We can't fold (ugt x, C) & (sgt x, C2).
984 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000985 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000986
Chris Lattner0a8191e2010-01-05 07:50:36 +0000987 // Ensure that the larger constant is on the RHS.
988 bool ShouldSwap;
989 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000990 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000991 CmpInst::isSigned(RHSCC)))
992 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
993 else
994 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000995
Chris Lattner0a8191e2010-01-05 07:50:36 +0000996 if (ShouldSwap) {
997 std::swap(LHS, RHS);
998 std::swap(LHSCst, RHSCst);
999 std::swap(LHSCC, RHSCC);
1000 }
1001
Dan Gohman4a618822010-02-10 16:03:48 +00001002 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001003 // comparing a value against two constants and and'ing the result
1004 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +00001005 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1006 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +00001007 // are not equal and that the larger constant is on the RHS
1008 assert(LHSCst != RHSCst && "Compares not folded above?");
1009
1010 switch (LHSCC) {
1011 default: llvm_unreachable("Unknown integer condition code!");
1012 case ICmpInst::ICMP_EQ:
1013 switch (RHSCC) {
1014 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001015 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
1016 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
1017 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +00001018 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001019 }
1020 case ICmpInst::ICMP_NE:
1021 switch (RHSCC) {
1022 default: llvm_unreachable("Unknown integer condition code!");
1023 case ICmpInst::ICMP_ULT:
1024 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001025 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +00001026 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
1027 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001028 break; // (X != 13 & X u< 15) -> no change
1029 case ICmpInst::ICMP_SLT:
1030 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001031 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001032 break; // (X != 13 & X s< 15) -> no change
1033 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
1034 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
1035 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001036 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001037 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001038 // Special case to get the ordering right when the values wrap around
1039 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +00001040 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001041 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001042 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1043 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1044 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +00001045 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1046 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001047 }
1048 break; // (X != 13 & X != 15) -> no change
1049 }
1050 break;
1051 case ICmpInst::ICMP_ULT:
1052 switch (RHSCC) {
1053 default: llvm_unreachable("Unknown integer condition code!");
1054 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
1055 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +00001056 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001057 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
1058 break;
1059 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
1060 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +00001061 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001062 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
1063 break;
1064 }
1065 break;
1066 case ICmpInst::ICMP_SLT:
1067 switch (RHSCC) {
1068 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001069 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
1070 break;
1071 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
1072 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +00001073 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001074 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
1075 break;
1076 }
1077 break;
1078 case ICmpInst::ICMP_UGT:
1079 switch (RHSCC) {
1080 default: llvm_unreachable("Unknown integer condition code!");
1081 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
1082 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001083 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001084 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1085 break;
1086 case ICmpInst::ICMP_NE:
1087 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001088 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001089 break; // (X u> 13 & X != 15) -> no change
1090 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +00001091 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001092 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1093 break;
1094 }
1095 break;
1096 case ICmpInst::ICMP_SGT:
1097 switch (RHSCC) {
1098 default: llvm_unreachable("Unknown integer condition code!");
1099 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1100 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001101 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001102 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1103 break;
1104 case ICmpInst::ICMP_NE:
1105 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001106 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001107 break; // (X s> 13 & X != 15) -> no change
1108 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +00001109 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001110 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1111 break;
1112 }
1113 break;
1114 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001115
Craig Topperf40110f2014-04-25 05:29:35 +00001116 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001117}
1118
Sanjay Patel18549272015-09-08 18:24:36 +00001119/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1120/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001121Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001122 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1123 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001124 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001125 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001126
Chris Lattner0a8191e2010-01-05 07:50:36 +00001127 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1128 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1129 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1130 // If either of the constants are nans, then the whole thing returns
1131 // false.
1132 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001133 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001134 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001135 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001136
Chris Lattner0a8191e2010-01-05 07:50:36 +00001137 // Handle vector zeros. This occurs because the canonical form of
1138 // "fcmp ord x,x" is "fcmp ord x, 0".
1139 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1140 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001141 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001142 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001143 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001144
Chris Lattner0a8191e2010-01-05 07:50:36 +00001145 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1146 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1147 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001148
1149
Chris Lattner0a8191e2010-01-05 07:50:36 +00001150 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1151 // Swap RHS operands to match LHS.
1152 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1153 std::swap(Op1LHS, Op1RHS);
1154 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001155
Chris Lattner0a8191e2010-01-05 07:50:36 +00001156 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1157 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1158 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001159 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001160 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001161 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001162 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001163 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001164 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001165 return LHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001166
Chris Lattner0a8191e2010-01-05 07:50:36 +00001167 bool Op0Ordered;
1168 bool Op1Ordered;
1169 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1170 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
Chad Rosierfaa38942012-06-06 17:22:40 +00001171 // uno && ord -> false
1172 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1173 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001174 if (Op1Pred == 0) {
1175 std::swap(LHS, RHS);
1176 std::swap(Op0Pred, Op1Pred);
1177 std::swap(Op0Ordered, Op1Ordered);
1178 }
1179 if (Op0Pred == 0) {
Manman Renc2bc2d12012-06-14 05:57:42 +00001180 // uno && ueq -> uno && (uno || eq) -> uno
Chris Lattner0a8191e2010-01-05 07:50:36 +00001181 // ord && olt -> ord && (ord && lt) -> olt
Manman Renc2bc2d12012-06-14 05:57:42 +00001182 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1183 return LHS;
1184 if (Op0Ordered && (Op0Ordered == Op1Ordered))
Chris Lattner067459c2010-03-05 08:46:26 +00001185 return RHS;
Craig Topper9d4171a2012-12-20 07:09:41 +00001186
Chris Lattner0a8191e2010-01-05 07:50:36 +00001187 // uno && oeq -> uno && (ord && eq) -> false
Chris Lattner0a8191e2010-01-05 07:50:36 +00001188 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +00001189 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001190 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +00001191 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001192 }
1193 }
1194
Craig Topperf40110f2014-04-25 05:29:35 +00001195 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001196}
1197
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001198/// Match De Morgan's Laws:
1199/// (~A & ~B) == (~(A | B))
1200/// (~A | ~B) == (~(A & B))
1201static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1202 InstCombiner::BuilderTy *Builder) {
1203 auto Opcode = I.getOpcode();
1204 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1205 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001206 // Flip the logic operation.
1207 if (Opcode == Instruction::And)
1208 Opcode = Instruction::Or;
1209 else
1210 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001211
1212 Value *Op0 = I.getOperand(0);
1213 Value *Op1 = I.getOperand(1);
1214 // TODO: Use pattern matchers instead of dyn_cast.
1215 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1216 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1217 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001218 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1219 I.getName() + ".demorgan");
1220 return BinaryOperator::CreateNot(LogicOp);
1221 }
1222
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001223 // De Morgan's Law in disguise:
1224 // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
1225 // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
1226 Value *A = nullptr;
1227 Value *B = nullptr;
1228 ConstantInt *C1 = nullptr;
1229 if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
1230 match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
1231 // TODO: This check could be loosened to handle different type sizes.
1232 // Alternatively, we could fix the definition of m_Not to recognize a not
1233 // operation hidden by a zext?
1234 if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
1235 C1->isOne()) {
1236 Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
1237 I.getName() + ".demorgan");
1238 Value *Not = Builder->CreateNot(LogicOp);
1239 return CastInst::CreateZExtOrBitCast(Not, I.getType());
1240 }
1241 }
1242
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001243 return nullptr;
1244}
1245
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001246Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
1247 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001248 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1249 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1250 if (!Cast0 || !Cast1)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001251 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001252
Sanjay Patel713f25e2016-02-23 17:41:34 +00001253 // The casts must be of the same type, and this must be a cast from an integer
1254 // or integer vector source type.
1255 auto CastOpcode = Cast0->getOpcode();
1256 Type *SrcTy = Cast0->getSrcTy();
1257 if ((CastOpcode != Cast1->getOpcode()) || (SrcTy != Cast1->getSrcTy()) ||
1258 !SrcTy->isIntOrIntVectorTy())
1259 return nullptr;
1260
1261 Value *Cast0Src = Cast0->getOperand(0);
1262 Value *Cast1Src = Cast1->getOperand(0);
1263 Type *DestTy = I.getType();
1264
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001265 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001266
Sanjay Patel713f25e2016-02-23 17:41:34 +00001267 // Only do this if the casts both really cause code to be generated.
1268 if (ShouldOptimizeCast(CastOpcode, Cast0Src, DestTy) &&
1269 ShouldOptimizeCast(CastOpcode, Cast1Src, DestTy)) {
1270 Value *NewOp = Builder->CreateAnd(Cast0Src, Cast1Src, I.getName());
1271 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001272 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001273
1274 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1275 // cast is otherwise not optimizable. This happens for vector sexts.
1276 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Cast1Src))
1277 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Cast0Src))
1278 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1279 return CastInst::Create(CastOpcode, Res, DestTy);
1280
1281 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1282 // cast is otherwise not optimizable. This happens for vector sexts.
1283 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Cast1Src))
1284 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Cast0Src))
1285 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1286 return CastInst::Create(CastOpcode, Res, DestTy);
1287
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001288 return nullptr;
1289}
1290
Chris Lattner0a8191e2010-01-05 07:50:36 +00001291Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001292 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1294
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001295 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001296 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001297
Chandler Carruth66b31302015-01-04 12:03:27 +00001298 if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001299 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001300
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001301 // (A|B)&(A|C) -> A|(B&C) etc
1302 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001303 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001304
Craig Topper9d4171a2012-12-20 07:09:41 +00001305 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001306 // purpose is to compute bits we don't care about.
1307 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001308 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001309
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001310 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001311 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001312
Chris Lattner0a8191e2010-01-05 07:50:36 +00001313 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1314 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001315
1316 // Optimize a variety of ((val OP C1) & C2) combinations...
1317 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1318 Value *Op0LHS = Op0I->getOperand(0);
1319 Value *Op0RHS = Op0I->getOperand(1);
1320 switch (Op0I->getOpcode()) {
1321 default: break;
1322 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001323 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001324 // If the mask is only needed on one incoming arm, push it up.
1325 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001326
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001327 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001328 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001329 // Not masking anything out for the LHS, move to RHS.
1330 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1331 Op0RHS->getName()+".masked");
1332 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1333 }
1334 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001335 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001336 // Not masking anything out for the RHS, move to LHS.
1337 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1338 Op0LHS->getName()+".masked");
1339 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1340 }
1341
1342 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001343 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001344 case Instruction::Add:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001345 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1346 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1347 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001348 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1349 return BinaryOperator::CreateAnd(V, AndRHS);
1350 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1351 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1352 break;
1353
1354 case Instruction::Sub:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001355 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1356 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1357 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001358 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1359 return BinaryOperator::CreateAnd(V, AndRHS);
1360
Balaram Makamccf59732015-08-20 15:35:00 +00001361 // -x & 1 -> x & 1
1362 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1363 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1364
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001365 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
Chris Lattner0a8191e2010-01-05 07:50:36 +00001366 // has 1's for all bits that the subtraction with A might affect.
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001367 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001368 uint32_t BitWidth = AndRHSMask.getBitWidth();
1369 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1370 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1371
Hal Finkel60db0582014-09-07 18:57:58 +00001372 if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001373 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1374 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1375 }
1376 }
1377 break;
1378
1379 case Instruction::Shl:
1380 case Instruction::LShr:
1381 // (1 << x) & 1 --> zext(x == 0)
1382 // (1 >> x) & 1 --> zext(x == 0)
1383 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1384 Value *NewICmp =
1385 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1386 return new ZExtInst(NewICmp, I.getType());
1387 }
1388 break;
1389 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001390
Chris Lattner0a8191e2010-01-05 07:50:36 +00001391 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1392 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1393 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001394 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001395
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001396 // If this is an integer truncation, and if the source is an 'and' with
1397 // immediate, transform it. This frequently occurs for bitfield accesses.
1398 {
Craig Topperf40110f2014-04-25 05:29:35 +00001399 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001400 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1401 // Change: and (trunc (and X, YC) to T), C2
1402 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001403 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001404 // other simplifications.
1405 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1406 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1407 C3 = ConstantExpr::getAnd(C3, AndRHS);
1408 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001409 }
1410 }
1411
1412 // Try to fold constant and into select arguments.
1413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1414 if (Instruction *R = FoldOpIntoSelect(I, SI))
1415 return R;
1416 if (isa<PHINode>(Op0))
1417 if (Instruction *NV = FoldOpIntoPhi(I))
1418 return NV;
1419 }
1420
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001421 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1422 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001423
Chris Lattner0a8191e2010-01-05 07:50:36 +00001424 {
Craig Topperf40110f2014-04-25 05:29:35 +00001425 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001426 // (A|B) & ~(A&B) -> A^B
1427 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1428 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1429 ((A == C && B == D) || (A == D && B == C)))
1430 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001431
Chris Lattner0a8191e2010-01-05 07:50:36 +00001432 // ~(A&B) & (A|B) -> A^B
1433 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1434 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1435 ((A == C && B == D) || (A == D && B == C)))
1436 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001437
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001438 // A&(A^B) => A & ~B
1439 {
1440 Value *tmpOp0 = Op0;
1441 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001442 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001443 if (A == Op1 || B == Op1 ) {
1444 tmpOp1 = Op0;
1445 tmpOp0 = Op1;
1446 // Simplify below
1447 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001448 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001449
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001450 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001451 if (B == tmpOp0) {
1452 std::swap(A, B);
1453 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001454 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001455 // A is originally -1 (or a vector of -1 and undefs), then we enter
1456 // an endless loop. By checking that A is non-constant we ensure that
1457 // we will never get to the loop.
1458 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001459 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001460 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001461 }
1462
1463 // (A&((~A)|B)) -> A&B
1464 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1465 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1466 return BinaryOperator::CreateAnd(A, Op1);
1467 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1468 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1469 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001470
1471 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1472 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1473 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1474 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1475 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1476
1477 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1478 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1479 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1480 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1481 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001482
1483 // (A | B) & ((~A) ^ B) -> (A & B)
1484 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1485 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1486 return BinaryOperator::CreateAnd(A, B);
1487
1488 // ((~A) ^ B) & (A | B) -> (A & B)
1489 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1490 match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1491 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001492 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001493
David Majnemer5e96f1b2014-08-30 06:18:20 +00001494 {
1495 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1496 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1497 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001498 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001499 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001500
David Majnemer5e96f1b2014-08-30 06:18:20 +00001501 // TODO: Make this recursive; it's a little tricky because an arbitrary
1502 // number of 'and' instructions might have to be created.
1503 Value *X, *Y;
1504 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1505 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1506 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001507 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001508 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1509 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001510 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001511 }
1512 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1513 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1514 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001515 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001516 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1517 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001518 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001519 }
1520 }
1521
Chris Lattner4e8137d2010-02-11 06:26:33 +00001522 // If and'ing two fcmp, try combine them into one.
1523 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1524 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001525 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001526 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001527
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001528 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1529 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001530
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001531 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1532 Value *Op0COp = Op0C->getOperand(0);
1533 Type *SrcTy = Op0COp->getType();
Craig Topper9d4171a2012-12-20 07:09:41 +00001534
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001535 // If we are masking off the sign bit of a floating-point value, convert
1536 // this to the canonical fabs intrinsic call and cast back to integer.
1537 // The backend should know how to optimize fabs().
1538 // TODO: This transform should also apply to vectors.
1539 ConstantInt *CI;
1540 if (isa<BitCastInst>(Op0C) && SrcTy->isFloatingPointTy() &&
1541 match(Op1, m_ConstantInt(CI)) && CI->isMaxValue(true)) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001542 Module *M = I.getModule();
Sanjay Patelf61a08f2015-10-08 17:09:31 +00001543 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, SrcTy);
1544 Value *Call = Builder->CreateCall(Fabs, Op0COp, "fabs");
1545 return CastInst::CreateBitOrPointerCast(Call, I.getType());
1546 }
1547 }
1548
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001549 {
Craig Topperf40110f2014-04-25 05:29:35 +00001550 Value *X = nullptr;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001551 bool OpsSwapped = false;
1552 // Canonicalize SExt or Not to the LHS
1553 if (match(Op1, m_SExt(m_Value())) ||
1554 match(Op1, m_Not(m_Value()))) {
1555 std::swap(Op0, Op1);
1556 OpsSwapped = true;
1557 }
1558
1559 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1560 if (match(Op0, m_SExt(m_Value(X))) &&
1561 X->getType()->getScalarType()->isIntegerTy(1)) {
1562 Value *Zero = Constant::getNullValue(Op1->getType());
1563 return SelectInst::Create(X, Op1, Zero);
1564 }
1565
1566 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1567 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1568 X->getType()->getScalarType()->isIntegerTy(1)) {
1569 Value *Zero = Constant::getNullValue(Op0->getType());
1570 return SelectInst::Create(X, Zero, Op1);
1571 }
1572
1573 if (OpsSwapped)
1574 std::swap(Op0, Op1);
1575 }
1576
Craig Topperf40110f2014-04-25 05:29:35 +00001577 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001578}
1579
James Molloy37b82e72015-12-11 10:04:51 +00001580/// Given an OR instruction, check to see if this is a bswap or bitreverse
1581/// idiom. If so, insert the new intrinsic and return it.
1582Instruction *InstCombiner::MatchBSwapOrBitReverse(BinaryOperator &I) {
James Molloyf01488e2016-01-15 09:20:19 +00001583 SmallVector<Instruction*, 4> Insts;
1584 if (!recognizeBitReverseOrBSwapIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001585 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001586 Instruction *LastInst = Insts.pop_back_val();
1587 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001588
James Molloyf01488e2016-01-15 09:20:19 +00001589 for (auto *Inst : Insts)
1590 Worklist.Add(Inst);
1591 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001592}
1593
Sanjay Patel18549272015-09-08 18:24:36 +00001594/// We have an expression of the form (A&C)|(B&D). Check if A is (cond?-1:0)
1595/// and either B or D is ~(cond?-1,0) or (cond?0,-1), then we can simplify this
1596/// expression to "cond ? C : D or B".
Chris Lattner0a8191e2010-01-05 07:50:36 +00001597static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1598 Value *C, Value *D) {
1599 // If A is not a select of -1/0, this cannot match.
Craig Topperf40110f2014-04-25 05:29:35 +00001600 Value *Cond = nullptr;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001601 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001602 !Cond->getType()->isIntegerTy(1))
Craig Topperf40110f2014-04-25 05:29:35 +00001603 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001604
1605 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001606 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001607 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001608 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001609 return SelectInst::Create(Cond, C, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001610
Chris Lattner0a8191e2010-01-05 07:50:36 +00001611 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001612 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001613 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001614 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001615 return SelectInst::Create(Cond, C, D);
Craig Topperf40110f2014-04-25 05:29:35 +00001616 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001617}
1618
Sanjay Patel18549272015-09-08 18:24:36 +00001619/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001620Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1621 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001622 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1623
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001624 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1625 // if K1 and K2 are a one-bit mask.
1626 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1627 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1628
1629 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1630 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1631
1632 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1633 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1634 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1635 LAnd->getOpcode() == Instruction::And &&
1636 RAnd->getOpcode() == Instruction::And) {
1637
Craig Topperf40110f2014-04-25 05:29:35 +00001638 Value *Mask = nullptr;
1639 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001640 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001641 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1642 DT) &&
1643 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1644 DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001645 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1646 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1647 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001648 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1649 CxtI, DT) &&
1650 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1651 CxtI, DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001652 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1653 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1654 }
1655
1656 if (Masked)
1657 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1658 }
1659 }
1660
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001661 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1662 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1663 // The original condition actually refers to the following two ranges:
1664 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1665 // We can fold these two ranges if:
1666 // 1) C1 and C2 is unsigned greater than C3.
1667 // 2) The two ranges are separated.
1668 // 3) C1 ^ C2 is one-bit mask.
1669 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1670 // This implies all values in the two ranges differ by exactly one bit.
1671
1672 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1673 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1674 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1675 LHSCst->getValue() == (RHSCst->getValue())) {
1676
1677 Value *LAdd = LHS->getOperand(0);
1678 Value *RAdd = RHS->getOperand(0);
1679
1680 Value *LAddOpnd, *RAddOpnd;
1681 ConstantInt *LAddCst, *RAddCst;
1682 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1683 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1684 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1685 RAddCst->getValue().ugt(LHSCst->getValue())) {
1686
1687 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1688 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1689 ConstantInt *MaxAddCst = nullptr;
1690 if (LAddCst->getValue().ult(RAddCst->getValue()))
1691 MaxAddCst = RAddCst;
1692 else
1693 MaxAddCst = LAddCst;
1694
1695 APInt RRangeLow = -RAddCst->getValue();
1696 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1697 APInt LRangeLow = -LAddCst->getValue();
1698 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1699 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1700 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1701 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1702 : RRangeLow - LRangeLow;
1703
1704 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1705 RangeDiff.ugt(LHSCst->getValue())) {
1706 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1707
1708 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1709 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1710 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1711 }
1712 }
1713 }
1714 }
1715
Chris Lattner0a8191e2010-01-05 07:50:36 +00001716 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1717 if (PredicatesFoldable(LHSCC, RHSCC)) {
1718 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1719 LHS->getOperand(1) == RHS->getOperand(0))
1720 LHS->swapOperands();
1721 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1722 LHS->getOperand(1) == RHS->getOperand(1)) {
1723 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1724 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1725 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001726 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001727 }
1728 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001729
1730 // handle (roughly):
1731 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001732 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001733 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001734
Chris Lattner0a8191e2010-01-05 07:50:36 +00001735 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001736 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1737 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1738 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001739 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001740 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1741 B = Val;
1742 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1743 A = Val2;
1744 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1745 A = RHS->getOperand(1);
1746 }
1747 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1748 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1749 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1750 B = Val2;
1751 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1752 A = Val;
1753 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1754 A = LHS->getOperand(1);
1755 }
1756 if (A && B)
1757 return Builder->CreateICmp(
1758 ICmpInst::ICMP_UGE,
1759 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1760 }
1761
Erik Ecksteind1817522014-12-03 10:39:15 +00001762 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1763 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1764 return V;
1765
1766 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1767 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1768 return V;
1769
David Majnemerc2a990b2013-07-05 00:31:17 +00001770 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001771 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001772
Owen Anderson8f306a72010-08-02 09:32:13 +00001773 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1774 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1775 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1776 Value *NewOr = Builder->CreateOr(Val, Val2);
1777 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1778 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001779 }
1780
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001781 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001782 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001783 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001784 ConstantInt *AddCst;
1785 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1786 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001787 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001788 }
1789
Chris Lattner0a8191e2010-01-05 07:50:36 +00001790 // From here on, we only handle:
1791 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001792 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001793
Chris Lattner0a8191e2010-01-05 07:50:36 +00001794 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1795 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1796 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1797 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1798 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001799 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001800
Chris Lattner0a8191e2010-01-05 07:50:36 +00001801 // We can't fold (ugt x, C) | (sgt x, C2).
1802 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001803 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001804
Chris Lattner0a8191e2010-01-05 07:50:36 +00001805 // Ensure that the larger constant is on the RHS.
1806 bool ShouldSwap;
1807 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001808 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001809 CmpInst::isSigned(RHSCC)))
1810 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1811 else
1812 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001813
Chris Lattner0a8191e2010-01-05 07:50:36 +00001814 if (ShouldSwap) {
1815 std::swap(LHS, RHS);
1816 std::swap(LHSCst, RHSCst);
1817 std::swap(LHSCC, RHSCC);
1818 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001819
Dan Gohman4a618822010-02-10 16:03:48 +00001820 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 // comparing a value against two constants and or'ing the result
1822 // together. Because of the above check, we know that we only have
1823 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1824 // icmp folding check above), that the two constants are not
1825 // equal.
1826 assert(LHSCst != RHSCst && "Compares not folded above?");
1827
1828 switch (LHSCC) {
1829 default: llvm_unreachable("Unknown integer condition code!");
1830 case ICmpInst::ICMP_EQ:
1831 switch (RHSCC) {
1832 default: llvm_unreachable("Unknown integer condition code!");
1833 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001834 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001835 // if LHSCst and RHSCst differ only by one bit:
David Majnemer942003a2015-12-02 16:15:07 +00001836 // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001837 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1838
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001839 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1840 if (Xor.isPowerOf2()) {
David Majnemer942003a2015-12-02 16:15:07 +00001841 Value *Cst = Builder->getInt(Xor);
1842 Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
1843 return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001844 }
1845 }
1846
David Majnemer1fae1952013-04-14 21:15:43 +00001847 if (LHSCst == SubOne(RHSCst)) {
1848 // (X == 13 | X == 14) -> X-13 <u 2
1849 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1850 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1851 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1852 return Builder->CreateICmpULT(Add, AddCST);
1853 }
1854
Chris Lattner0a8191e2010-01-05 07:50:36 +00001855 break; // (X == 13 | X == 15) -> no change
1856 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1857 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1858 break;
1859 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1860 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1861 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001862 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001863 }
1864 break;
1865 case ICmpInst::ICMP_NE:
1866 switch (RHSCC) {
1867 default: llvm_unreachable("Unknown integer condition code!");
1868 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1869 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1870 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001871 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001872 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1873 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1874 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001875 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001876 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001877 case ICmpInst::ICMP_ULT:
1878 switch (RHSCC) {
1879 default: llvm_unreachable("Unknown integer condition code!");
1880 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1881 break;
1882 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1883 // If RHSCst is [us]MAXINT, it is always false. Not handling
1884 // this can cause overflow.
1885 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001886 return LHS;
1887 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001888 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1889 break;
1890 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1891 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001892 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001893 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1894 break;
1895 }
1896 break;
1897 case ICmpInst::ICMP_SLT:
1898 switch (RHSCC) {
1899 default: llvm_unreachable("Unknown integer condition code!");
1900 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1901 break;
1902 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1903 // If RHSCst is [us]MAXINT, it is always false. Not handling
1904 // this can cause overflow.
1905 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001906 return LHS;
1907 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001908 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1909 break;
1910 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1911 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001912 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001913 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1914 break;
1915 }
1916 break;
1917 case ICmpInst::ICMP_UGT:
1918 switch (RHSCC) {
1919 default: llvm_unreachable("Unknown integer condition code!");
1920 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1921 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001922 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001923 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1924 break;
1925 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1926 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001927 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001928 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1929 break;
1930 }
1931 break;
1932 case ICmpInst::ICMP_SGT:
1933 switch (RHSCC) {
1934 default: llvm_unreachable("Unknown integer condition code!");
1935 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1936 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001937 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001938 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1939 break;
1940 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1941 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001942 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001943 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1944 break;
1945 }
1946 break;
1947 }
Craig Topperf40110f2014-04-25 05:29:35 +00001948 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001949}
1950
Sanjay Patel18549272015-09-08 18:24:36 +00001951/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1952/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001953Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001954 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001955 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001956 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1957 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1958 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1959 // If either of the constants are nans, then the whole thing returns
1960 // true.
1961 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001962 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001963
Chris Lattner0a8191e2010-01-05 07:50:36 +00001964 // Otherwise, no need to compare the two constants, compare the
1965 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001966 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001967 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001968
Chris Lattner0a8191e2010-01-05 07:50:36 +00001969 // Handle vector zeros. This occurs because the canonical form of
1970 // "fcmp uno x,x" is "fcmp uno x, 0".
1971 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1972 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001973 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001974
Craig Topperf40110f2014-04-25 05:29:35 +00001975 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001976 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001977
Chris Lattner0a8191e2010-01-05 07:50:36 +00001978 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1979 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1980 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
Craig Topper9d4171a2012-12-20 07:09:41 +00001981
Chris Lattner0a8191e2010-01-05 07:50:36 +00001982 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1983 // Swap RHS operands to match LHS.
1984 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1985 std::swap(Op1LHS, Op1RHS);
1986 }
1987 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1988 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1989 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001990 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001991 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001992 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001993 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001994 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001995 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001996 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001997 bool Op0Ordered;
1998 bool Op1Ordered;
1999 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
2000 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
2001 if (Op0Ordered == Op1Ordered) {
2002 // If both are ordered or unordered, return a new fcmp with
2003 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00002004 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002005 }
2006 }
Craig Topperf40110f2014-04-25 05:29:35 +00002007 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002008}
2009
Sanjay Patel18549272015-09-08 18:24:36 +00002010/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00002011///
2012/// ((A | B) & C1) | (B & C2)
2013///
2014/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002015///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002016/// (A & C1) | B
2017///
2018/// when the XOR of the two constants is "all ones" (-1).
2019Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2020 Value *A, Value *B, Value *C) {
2021 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002022 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002023
Craig Topperf40110f2014-04-25 05:29:35 +00002024 Value *V1 = nullptr;
2025 ConstantInt *CI2 = nullptr;
2026 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002027
2028 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002029 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002030
2031 if (V1 == A || V1 == B) {
2032 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2033 return BinaryOperator::CreateOr(NewOp, V1);
2034 }
2035
Craig Topperf40110f2014-04-25 05:29:35 +00002036 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037}
2038
David Majnemer5d1aeba2014-08-21 05:14:48 +00002039/// \brief This helper function folds:
2040///
2041/// ((A | B) & C1) ^ (B & C2)
2042///
2043/// into:
2044///
2045/// (A & C1) ^ B
2046///
2047/// when the XOR of the two constants is "all ones" (-1).
2048Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2049 Value *A, Value *B, Value *C) {
2050 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2051 if (!CI1)
2052 return nullptr;
2053
2054 Value *V1 = nullptr;
2055 ConstantInt *CI2 = nullptr;
2056 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2057 return nullptr;
2058
2059 APInt Xor = CI1->getValue() ^ CI2->getValue();
2060 if (!Xor.isAllOnesValue())
2061 return nullptr;
2062
2063 if (V1 == A || V1 == B) {
2064 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2065 return BinaryOperator::CreateXor(NewOp, V1);
2066 }
2067
2068 return nullptr;
2069}
2070
Chris Lattner0a8191e2010-01-05 07:50:36 +00002071Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002072 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002073 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2074
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002075 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002076 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002077
Chandler Carruth66b31302015-01-04 12:03:27 +00002078 if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002079 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002080
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002081 // (A&B)|(A&C) -> A&(B|C) etc
2082 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002083 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002084
Craig Topper9d4171a2012-12-20 07:09:41 +00002085 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002086 // purpose is to compute bits we don't care about.
2087 if (SimplifyDemandedInstructionBits(I))
2088 return &I;
2089
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002090 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002091 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002092
Chris Lattner0a8191e2010-01-05 07:50:36 +00002093 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002094 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002095 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002096 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002097 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00002098 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002099 Op0->hasOneUse()) {
2100 Value *Or = Builder->CreateOr(X, RHS);
2101 Or->takeName(Op0);
Craig Topper9d4171a2012-12-20 07:09:41 +00002102 return BinaryOperator::CreateAnd(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002103 Builder->getInt(RHS->getValue() | C1->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002104 }
2105
2106 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2107 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2108 Op0->hasOneUse()) {
2109 Value *Or = Builder->CreateOr(X, RHS);
2110 Or->takeName(Op0);
2111 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002112 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002113 }
2114
2115 // Try to fold constant and into select arguments.
2116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2117 if (Instruction *R = FoldOpIntoSelect(I, SI))
2118 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002119
Chris Lattner0a8191e2010-01-05 07:50:36 +00002120 if (isa<PHINode>(Op0))
2121 if (Instruction *NV = FoldOpIntoPhi(I))
2122 return NV;
2123 }
2124
Craig Topperf40110f2014-04-25 05:29:35 +00002125 Value *A = nullptr, *B = nullptr;
2126 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002127
2128 // (A | B) | C and A | (B | C) -> bswap if possible.
Charlie Turner27205932015-09-24 10:24:58 +00002129 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
2130 match(Op1, m_Or(m_Value(), m_Value()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002131 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Charlie Turner27205932015-09-24 10:24:58 +00002132 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
2133 match(Op1, m_LogicalShift(m_Value(), m_Value()));
2134 // (A & B) | (C & D) -> bswap if possible.
2135 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
2136 match(Op1, m_And(m_Value(), m_Value()));
2137
2138 if (OrOfOrs || OrOfShifts || OrOfAnds)
James Molloy37b82e72015-12-11 10:04:51 +00002139 if (Instruction *BSwap = MatchBSwapOrBitReverse(I))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002140 return BSwap;
Craig Topper9d4171a2012-12-20 07:09:41 +00002141
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002142 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002143 if (Op0->hasOneUse() &&
2144 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002145 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002146 Value *NOr = Builder->CreateOr(A, Op1);
2147 NOr->takeName(Op0);
2148 return BinaryOperator::CreateXor(NOr, C1);
2149 }
2150
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002151 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002152 if (Op1->hasOneUse() &&
2153 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002154 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002155 Value *NOr = Builder->CreateOr(A, Op0);
2156 NOr->takeName(Op0);
2157 return BinaryOperator::CreateXor(NOr, C1);
2158 }
2159
Suyog Sardad64faf62014-07-22 18:09:41 +00002160 // ((~A & B) | A) -> (A | B)
2161 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2162 match(Op1, m_Specific(A)))
2163 return BinaryOperator::CreateOr(A, B);
2164
2165 // ((A & B) | ~A) -> (~A | B)
2166 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2167 match(Op1, m_Not(m_Specific(A))))
2168 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2169
Suyog Sarda52324c82014-08-01 04:50:31 +00002170 // (A & (~B)) | (A ^ B) -> (A ^ B)
2171 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2172 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2173 return BinaryOperator::CreateXor(A, B);
2174
2175 // (A ^ B) | ( A & (~B)) -> (A ^ B)
2176 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2177 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2178 return BinaryOperator::CreateXor(A, B);
2179
Chris Lattner0a8191e2010-01-05 07:50:36 +00002180 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002181 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002182 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2183 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002184 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002185 C1 = dyn_cast<ConstantInt>(C);
2186 C2 = dyn_cast<ConstantInt>(D);
2187 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002188 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002189 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002190 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002191 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002192 ((V1 == B &&
2193 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2194 (V2 == B &&
2195 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002196 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002197 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002198 // Or commutes, try both ways.
2199 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002200 ((V1 == A &&
2201 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2202 (V2 == A &&
2203 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002204 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002205 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002206
Chris Lattner95188692010-01-11 06:55:24 +00002207 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002208 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002209 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002210 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2211 (C3->getValue() & ~C1->getValue()) == 0 &&
2212 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2213 (C4->getValue() & ~C2->getValue()) == 0) {
2214 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2215 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002216 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002217 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002218 }
2219 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002220
Chris Lattner8e2c4712010-02-02 02:43:51 +00002221 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2222 // Don't do this for vector select idioms, the code generator doesn't handle
2223 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00002224 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00002225 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2226 return Match;
2227 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2228 return Match;
2229 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2230 return Match;
2231 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2232 return Match;
2233 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002234
2235 // ((A&~B)|(~A&B)) -> A^B
2236 if ((match(C, m_Not(m_Specific(D))) &&
2237 match(B, m_Not(m_Specific(A)))))
2238 return BinaryOperator::CreateXor(A, D);
2239 // ((~B&A)|(~A&B)) -> A^B
2240 if ((match(A, m_Not(m_Specific(D))) &&
2241 match(B, m_Not(m_Specific(C)))))
2242 return BinaryOperator::CreateXor(C, D);
2243 // ((A&~B)|(B&~A)) -> A^B
2244 if ((match(C, m_Not(m_Specific(B))) &&
2245 match(D, m_Not(m_Specific(A)))))
2246 return BinaryOperator::CreateXor(A, B);
2247 // ((~B&A)|(B&~A)) -> A^B
2248 if ((match(A, m_Not(m_Specific(B))) &&
2249 match(D, m_Not(m_Specific(C)))))
2250 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002251
2252 // ((A|B)&1)|(B&-2) -> (A&1) | B
2253 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2254 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2255 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2256 if (Ret) return Ret;
2257 }
2258 // (B&-2)|((A|B)&1) -> (A&1) | B
2259 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2260 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2261 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2262 if (Ret) return Ret;
2263 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002264 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2265 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2266 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2267 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2268 if (Ret) return Ret;
2269 }
2270 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2271 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2272 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2273 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2274 if (Ret) return Ret;
2275 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002276 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002277
David Majnemer42af3602014-07-30 21:26:37 +00002278 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2279 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2280 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2281 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2282 return BinaryOperator::CreateOr(Op0, C);
2283
2284 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2285 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2286 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2287 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2288 return BinaryOperator::CreateOr(Op1, C);
2289
David Majnemerf1eda232014-08-14 06:41:38 +00002290 // ((B | C) & A) | B -> B | (A & C)
2291 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2292 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2293
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002294 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2295 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002296
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002297 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002298 bool SwappedForXor = false;
2299 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002300 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002301 SwappedForXor = true;
2302 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002303
2304 // A | ( A ^ B) -> A | B
2305 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002306 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002307 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2308 if (Op0 == A || Op0 == B)
2309 return BinaryOperator::CreateOr(A, B);
2310
Chad Rosier7813dce2012-04-26 23:29:14 +00002311 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2312 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2313 return BinaryOperator::CreateOr(A, B);
2314
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002315 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2316 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2317 return BinaryOperator::CreateOr(Not, Op0);
2318 }
2319 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2320 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2321 return BinaryOperator::CreateOr(Not, Op0);
2322 }
2323 }
2324
2325 // A | ~(A | B) -> A | ~B
2326 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002327 if (match(Op1, m_Not(m_Value(A))))
2328 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002329 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2330 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2331 B->getOpcode() == Instruction::Xor)) {
2332 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2333 B->getOperand(0);
2334 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2335 return BinaryOperator::CreateOr(Not, Op0);
2336 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002337
Suyog Sarda16d64652014-08-01 04:41:43 +00002338 // (A & B) | ((~A) ^ B) -> (~A ^ B)
2339 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2340 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2341 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2342
2343 // ((~A) ^ B) | (A & B) -> (~A ^ B)
2344 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2345 match(Op1, m_And(m_Specific(A), m_Specific(B))))
2346 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2347
Eli Friedmane06535b2012-03-16 00:52:42 +00002348 if (SwappedForXor)
2349 std::swap(Op0, Op1);
2350
David Majnemer3d6f80b2014-11-28 19:58:29 +00002351 {
2352 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2353 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2354 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002355 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002356 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002357
David Majnemer3d6f80b2014-11-28 19:58:29 +00002358 // TODO: Make this recursive; it's a little tricky because an arbitrary
2359 // number of 'or' instructions might have to be created.
2360 Value *X, *Y;
2361 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2362 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2363 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002364 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002365 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2366 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002367 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002368 }
2369 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2370 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2371 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002372 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002373 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2374 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002375 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002376 }
2377 }
2378
Chris Lattner4e8137d2010-02-11 06:26:33 +00002379 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2380 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2381 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002382 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002383 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002384
Chris Lattner0a8191e2010-01-05 07:50:36 +00002385 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2386 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner311aa632011-01-15 05:40:29 +00002387 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2388 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner229907c2011-07-18 04:54:35 +00002389 Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner311aa632011-01-15 05:40:29 +00002390 if (SrcTy == Op1C->getOperand(0)->getType() &&
2391 SrcTy->isIntOrIntVectorTy()) {
2392 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
Chris Lattner4e8137d2010-02-11 06:26:33 +00002393
Chris Lattner311aa632011-01-15 05:40:29 +00002394 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2395 // Only do this if the casts both really cause code to be
2396 // generated.
2397 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2398 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2399 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2400 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002401 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002402
Chris Lattner311aa632011-01-15 05:40:29 +00002403 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2404 // cast is otherwise not optimizable. This happens for vector sexts.
2405 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2406 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Hal Finkel60db0582014-09-07 18:57:58 +00002407 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Chris Lattner311aa632011-01-15 05:40:29 +00002408 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Craig Topper9d4171a2012-12-20 07:09:41 +00002409
Chris Lattner311aa632011-01-15 05:40:29 +00002410 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2411 // cast is otherwise not optimizable. This happens for vector sexts.
2412 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2413 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2414 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2415 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002416 }
Chris Lattner311aa632011-01-15 05:40:29 +00002417 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002418 }
Eli Friedman23956262011-04-14 22:41:27 +00002419
2420 // or(sext(A), B) -> A ? -1 : B where A is an i1
2421 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2422 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2423 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2424 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2425 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2426
Owen Andersonc237a842010-09-13 17:59:27 +00002427 // Note: If we've gotten to the point of visiting the outer OR, then the
2428 // inner one couldn't be simplified. If it was a constant, then it won't
2429 // be simplified by a later pass either, so we try swapping the inner/outer
2430 // ORs in the hopes that we'll be able to simplify it this way.
2431 // (X|C) | V --> (X|V) | C
2432 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2433 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2434 Value *Inner = Builder->CreateOr(A, Op1);
2435 Inner->takeName(Op0);
2436 return BinaryOperator::CreateOr(Inner, C1);
2437 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002438
Bill Wendling23242092013-02-16 23:41:36 +00002439 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2440 // Since this OR statement hasn't been optimized further yet, we hope
2441 // that this transformation will allow the new ORs to be optimized.
2442 {
Craig Topperf40110f2014-04-25 05:29:35 +00002443 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002444 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2445 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2446 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2447 Value *orTrue = Builder->CreateOr(A, C);
2448 Value *orFalse = Builder->CreateOr(B, D);
2449 return SelectInst::Create(X, orTrue, orFalse);
2450 }
2451 }
2452
Craig Topperf40110f2014-04-25 05:29:35 +00002453 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002454}
2455
2456Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002457 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002458 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2459
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002460 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002461 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002462
Chandler Carruth66b31302015-01-04 12:03:27 +00002463 if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002464 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002465
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002466 // (A&B)^(A&C) -> A&(B^C) etc
2467 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002468 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002469
Craig Topper9d4171a2012-12-20 07:09:41 +00002470 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002471 // purpose is to compute bits we don't care about.
2472 if (SimplifyDemandedInstructionBits(I))
2473 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002474
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002475 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002476 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002477
Chris Lattner0a8191e2010-01-05 07:50:36 +00002478 // Is this a ~ operation?
2479 if (Value *NotOp = dyn_castNotVal(&I)) {
2480 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002481 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002482 Op0I->getOpcode() == Instruction::Or) {
2483 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2484 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2485 if (dyn_castNotVal(Op0I->getOperand(1)))
2486 Op0I->swapOperands();
2487 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2488 Value *NotY =
2489 Builder->CreateNot(Op0I->getOperand(1),
2490 Op0I->getOperand(1)->getName()+".not");
2491 if (Op0I->getOpcode() == Instruction::And)
2492 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2493 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2494 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002495
Chris Lattner0a8191e2010-01-05 07:50:36 +00002496 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2497 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002498 if (IsFreeToInvert(Op0I->getOperand(0),
2499 Op0I->getOperand(0)->hasOneUse()) &&
2500 IsFreeToInvert(Op0I->getOperand(1),
2501 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002502 Value *NotX =
2503 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2504 Value *NotY =
2505 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2506 if (Op0I->getOpcode() == Instruction::And)
2507 return BinaryOperator::CreateOr(NotX, NotY);
2508 return BinaryOperator::CreateAnd(NotX, NotY);
2509 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002510
2511 } else if (Op0I->getOpcode() == Instruction::AShr) {
2512 // ~(~X >>s Y) --> (X >>s Y)
2513 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2514 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002515 }
2516 }
2517 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002518
Benjamin Kramer443c7962015-02-12 20:26:46 +00002519 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2520 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002521 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002522 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2523 return CmpInst::Create(CI->getOpcode(),
2524 CI->getInversePredicate(),
2525 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002526 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002527
Benjamin Kramer443c7962015-02-12 20:26:46 +00002528 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002529 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2530 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2531 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2532 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2533 Instruction::CastOps Opcode = Op0C->getOpcode();
2534 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002535 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002536 Op0C->getDestTy()))) {
2537 CI->setPredicate(CI->getInversePredicate());
2538 return CastInst::Create(Opcode, CI, Op0C->getType());
2539 }
2540 }
2541 }
2542 }
2543
2544 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2545 // ~(c-X) == X-c-1 == X+(-c-1)
2546 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2547 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2548 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2549 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2550 ConstantInt::get(I.getType(), 1));
2551 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2552 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002553
Chris Lattner0a8191e2010-01-05 07:50:36 +00002554 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2555 if (Op0I->getOpcode() == Instruction::Add) {
2556 // ~(X-c) --> (-c-1)-X
2557 if (RHS->isAllOnesValue()) {
2558 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2559 return BinaryOperator::CreateSub(
2560 ConstantExpr::getSub(NegOp0CI,
2561 ConstantInt::get(I.getType(), 1)),
2562 Op0I->getOperand(0));
2563 } else if (RHS->getValue().isSignBit()) {
2564 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002565 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002566 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2567
2568 }
2569 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002570 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002571 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2572 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002573 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2574 // Anything in both C1 and C2 is known to be zero, remove it from
2575 // NewRHS.
2576 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002577 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002578 ConstantExpr::getNot(CommonBits));
2579 Worklist.Add(Op0I);
2580 I.setOperand(0, Op0I->getOperand(0));
2581 I.setOperand(1, NewRHS);
2582 return &I;
2583 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002584 } else if (Op0I->getOpcode() == Instruction::LShr) {
2585 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2586 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002587 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002588 ConstantInt *C1;
2589 if (Op0I->hasOneUse() &&
2590 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2591 E1->getOpcode() == Instruction::Xor &&
2592 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2593 // fold (C1 >> C2) ^ C3
2594 ConstantInt *C2 = Op0CI, *C3 = RHS;
2595 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2596 FoldConst ^= C3->getValue();
2597 // Prepare the two operands.
2598 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2599 Opnd0->takeName(Op0I);
2600 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2601 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2602
2603 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2604 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002605 }
2606 }
2607 }
2608
2609 // Try to fold constant and into select arguments.
2610 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2611 if (Instruction *R = FoldOpIntoSelect(I, SI))
2612 return R;
2613 if (isa<PHINode>(Op0))
2614 if (Instruction *NV = FoldOpIntoPhi(I))
2615 return NV;
2616 }
2617
Chris Lattner0a8191e2010-01-05 07:50:36 +00002618 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2619 if (Op1I) {
2620 Value *A, *B;
2621 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2622 if (A == Op0) { // B^(B|A) == (A|B)^B
2623 Op1I->swapOperands();
2624 I.swapOperands();
2625 std::swap(Op0, Op1);
2626 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2627 I.swapOperands(); // Simplified below.
2628 std::swap(Op0, Op1);
2629 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002630 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002631 Op1I->hasOneUse()){
2632 if (A == Op0) { // A^(A&B) -> A^(B&A)
2633 Op1I->swapOperands();
2634 std::swap(A, B);
2635 }
2636 if (B == Op0) { // A^(B&A) -> (B&A)^A
2637 I.swapOperands(); // Simplified below.
2638 std::swap(Op0, Op1);
2639 }
2640 }
2641 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002642
Chris Lattner0a8191e2010-01-05 07:50:36 +00002643 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2644 if (Op0I) {
2645 Value *A, *B;
2646 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2647 Op0I->hasOneUse()) {
2648 if (A == Op1) // (B|A)^B == (A|B)^B
2649 std::swap(A, B);
2650 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002651 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002652 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002653 Op0I->hasOneUse()){
2654 if (A == Op1) // (A&B)^A -> (B&A)^A
2655 std::swap(A, B);
2656 if (B == Op1 && // (B&A)^A == ~B & A
2657 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002658 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002659 }
2660 }
2661 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002662
Chris Lattner0a8191e2010-01-05 07:50:36 +00002663 if (Op0I && Op1I) {
2664 Value *A, *B, *C, *D;
2665 // (A & B)^(A | B) -> A ^ B
2666 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2667 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002668 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002669 return BinaryOperator::CreateXor(A, B);
2670 }
2671 // (A | B)^(A & B) -> A ^ B
2672 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2673 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002674 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002675 return BinaryOperator::CreateXor(A, B);
2676 }
David Majnemer698dca02014-08-14 06:46:25 +00002677 // (A | ~B) ^ (~A | B) -> A ^ B
2678 if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2679 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2680 return BinaryOperator::CreateXor(A, B);
2681 }
2682 // (~A | B) ^ (A | ~B) -> A ^ B
2683 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2684 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2685 return BinaryOperator::CreateXor(A, B);
2686 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002687 // (A & ~B) ^ (~A & B) -> A ^ B
2688 if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2689 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2690 return BinaryOperator::CreateXor(A, B);
2691 }
2692 // (~A & B) ^ (A & ~B) -> A ^ B
2693 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2694 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2695 return BinaryOperator::CreateXor(A, B);
2696 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002697 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2698 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2699 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2700 if (D == A)
2701 return BinaryOperator::CreateXor(
2702 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2703 if (D == B)
2704 return BinaryOperator::CreateXor(
2705 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002706 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002707 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002708 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002709 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2710 if (D == A)
2711 return BinaryOperator::CreateXor(
2712 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2713 if (D == B)
2714 return BinaryOperator::CreateXor(
2715 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002716 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002717 // (A & B) ^ (A ^ B) -> (A | B)
2718 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2719 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2720 return BinaryOperator::CreateOr(A, B);
2721 // (A ^ B) ^ (A & B) -> (A | B)
2722 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2723 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2724 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002725 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002726
Suyog Sarda521237c2014-07-22 15:37:39 +00002727 Value *A = nullptr, *B = nullptr;
Suyog Sarda56c9a872014-08-01 05:07:20 +00002728 // (A & ~B) ^ (~A) -> ~(A & B)
2729 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2730 match(Op1, m_Not(m_Specific(A))))
2731 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2732
Chris Lattner0a8191e2010-01-05 07:50:36 +00002733 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2734 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2735 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2736 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2737 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2738 LHS->getOperand(1) == RHS->getOperand(0))
2739 LHS->swapOperands();
2740 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2741 LHS->getOperand(1) == RHS->getOperand(1)) {
2742 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2743 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2744 bool isSigned = LHS->isSigned() || RHS->isSigned();
Sanjay Patel4b198802016-02-01 22:23:39 +00002745 return replaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002746 getNewICmpValue(isSigned, Code, Op0, Op1,
2747 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002748 }
2749 }
2750
2751 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2752 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2753 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2754 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
Chris Lattner229907c2011-07-18 04:54:35 +00002755 Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00002756 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002757 // Only do this if the casts both really cause code to be generated.
Craig Topper9d4171a2012-12-20 07:09:41 +00002758 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002759 I.getType()) &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002760 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner4e8137d2010-02-11 06:26:33 +00002761 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002762 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2763 Op1C->getOperand(0), I.getName());
2764 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2765 }
2766 }
2767 }
2768
Craig Topperf40110f2014-04-25 05:29:35 +00002769 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002770}