blob: 19a05bfe9bba3d7b7ef3c20ab1405144f1a80549 [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
14#include "InstCombine.h"
15#include "llvm/Intrinsics.h"
16#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Support/PatternMatch.h"
18using namespace llvm;
19using namespace PatternMatch;
20
21
22/// AddOne - Add one to a ConstantInt.
23static Constant *AddOne(Constant *C) {
24 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
25}
26/// SubOne - Subtract one from a ConstantInt.
27static Constant *SubOne(ConstantInt *C) {
28 return ConstantInt::get(C->getContext(), C->getValue()-1);
29}
30
31/// isFreeToInvert - Return true if the specified value is free to invert (apply
32/// ~ to). This happens in cases where the ~ can be eliminated.
33static inline bool isFreeToInvert(Value *V) {
34 // ~(~(X)) -> X.
35 if (BinaryOperator::isNot(V))
36 return true;
37
38 // Constants can be considered to be not'ed values.
39 if (isa<ConstantInt>(V))
40 return true;
41
42 // Compares can be inverted if they have a single use.
43 if (CmpInst *CI = dyn_cast<CmpInst>(V))
44 return CI->hasOneUse();
45
46 return false;
47}
48
49static inline Value *dyn_castNotVal(Value *V) {
50 // If this is not(not(x)) don't return that this is a not: we want the two
51 // not's to be folded first.
52 if (BinaryOperator::isNot(V)) {
53 Value *Operand = BinaryOperator::getNotArgument(V);
54 if (!isFreeToInvert(Operand))
55 return Operand;
56 }
57
58 // Constants can be considered to be not'ed values...
59 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
60 return ConstantInt::get(C->getType(), ~C->getValue());
61 return 0;
62}
63
64
65/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
66/// are carefully arranged to allow folding of expressions such as:
67///
68/// (A < B) | (A > B) --> (A != B)
69///
70/// Note that this is only valid if the first and second predicates have the
71/// same sign. Is illegal to do: (A u< B) | (A s> B)
72///
73/// Three bits are used to represent the condition, as follows:
74/// 0 A > B
75/// 1 A == B
76/// 2 A < B
77///
78/// <=> Value Definition
79/// 000 0 Always false
80/// 001 1 A > B
81/// 010 2 A == B
82/// 011 3 A >= B
83/// 100 4 A < B
84/// 101 5 A != B
85/// 110 6 A <= B
86/// 111 7 Always true
87///
88static unsigned getICmpCode(const ICmpInst *ICI) {
89 switch (ICI->getPredicate()) {
90 // False -> 0
91 case ICmpInst::ICMP_UGT: return 1; // 001
92 case ICmpInst::ICMP_SGT: return 1; // 001
93 case ICmpInst::ICMP_EQ: return 2; // 010
94 case ICmpInst::ICMP_UGE: return 3; // 011
95 case ICmpInst::ICMP_SGE: return 3; // 011
96 case ICmpInst::ICMP_ULT: return 4; // 100
97 case ICmpInst::ICMP_SLT: return 4; // 100
98 case ICmpInst::ICMP_NE: return 5; // 101
99 case ICmpInst::ICMP_ULE: return 6; // 110
100 case ICmpInst::ICMP_SLE: return 6; // 110
101 // True -> 7
102 default:
103 llvm_unreachable("Invalid ICmp predicate!");
104 return 0;
105 }
106}
107
108/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
109/// predicate into a three bit mask. It also returns whether it is an ordered
110/// predicate by reference.
111static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
112 isOrdered = false;
113 switch (CC) {
114 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
115 case FCmpInst::FCMP_UNO: return 0; // 000
116 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
117 case FCmpInst::FCMP_UGT: return 1; // 001
118 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
119 case FCmpInst::FCMP_UEQ: return 2; // 010
120 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
121 case FCmpInst::FCMP_UGE: return 3; // 011
122 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
123 case FCmpInst::FCMP_ULT: return 4; // 100
124 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
125 case FCmpInst::FCMP_UNE: return 5; // 101
126 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
127 case FCmpInst::FCMP_ULE: return 6; // 110
128 // True -> 7
129 default:
130 // Not expecting FCMP_FALSE and FCMP_TRUE;
131 llvm_unreachable("Unexpected FCmp predicate!");
132 return 0;
133 }
134}
135
136/// getICmpValue - This is the complement of getICmpCode, which turns an
137/// opcode and two operands into either a constant true or false, or a brand
138/// new ICmp instruction. The sign is passed in to determine which kind
139/// of predicate to use in the new icmp instruction.
Chris Lattner067459c2010-03-05 08:46:26 +0000140static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
141 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000142 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000143 switch (Code) {
144 default: assert(0 && "Illegal ICmp code!");
Chris Lattner343d2e42010-03-05 07:47:57 +0000145 case 0: // False.
146 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
147 case 1: Pred = Sign ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
148 case 2: Pred = ICmpInst::ICMP_EQ; break;
149 case 3: Pred = Sign ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
150 case 4: Pred = Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
151 case 5: Pred = ICmpInst::ICMP_NE; break;
152 case 6: Pred = Sign ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
153 case 7: // True.
154 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000155 }
Chris Lattner067459c2010-03-05 08:46:26 +0000156 return Builder->CreateICmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000157}
158
159/// getFCmpValue - This is the complement of getFCmpCode, which turns an
160/// opcode and two operands into either a FCmp instruction. isordered is passed
161/// in to determine which kind of predicate to use in the new fcmp instruction.
162static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner067459c2010-03-05 08:46:26 +0000163 Value *LHS, Value *RHS,
164 InstCombiner::BuilderTy *Builder) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000165 CmpInst::Predicate Pred;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000166 switch (code) {
Chris Lattner343d2e42010-03-05 07:47:57 +0000167 default: assert(0 && "Illegal FCmp code!");
168 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
169 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
170 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
171 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
172 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
173 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
174 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
175 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000176 }
Chris Lattner067459c2010-03-05 08:46:26 +0000177 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000178}
179
180/// PredicatesFoldable - Return true if both predicates match sign or if at
181/// least one of them is an equality comparison (which is signless).
182static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
183 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
184 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
185 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
186}
187
188// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
189// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
190// guaranteed to be a binary operator.
191Instruction *InstCombiner::OptAndOp(Instruction *Op,
192 ConstantInt *OpRHS,
193 ConstantInt *AndRHS,
194 BinaryOperator &TheAnd) {
195 Value *X = Op->getOperand(0);
196 Constant *Together = 0;
197 if (!Op->isShift())
198 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
199
200 switch (Op->getOpcode()) {
201 case Instruction::Xor:
202 if (Op->hasOneUse()) {
203 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
204 Value *And = Builder->CreateAnd(X, AndRHS);
205 And->takeName(Op);
206 return BinaryOperator::CreateXor(And, Together);
207 }
208 break;
209 case Instruction::Or:
210 if (Together == AndRHS) // (X | C) & C --> C
211 return ReplaceInstUsesWith(TheAnd, AndRHS);
212
213 if (Op->hasOneUse() && Together != OpRHS) {
214 // (X | C1) & C2 --> (X | (C1&C2)) & C2
215 Value *Or = Builder->CreateOr(X, Together);
216 Or->takeName(Op);
217 return BinaryOperator::CreateAnd(Or, AndRHS);
218 }
219 break;
220 case Instruction::Add:
221 if (Op->hasOneUse()) {
222 // Adding a one to a single bit bit-field should be turned into an XOR
223 // of the bit. First thing to check is to see if this AND is with a
224 // single bit constant.
225 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
226
227 // If there is only one bit set.
228 if (AndRHSV.isPowerOf2()) {
229 // Ok, at this point, we know that we are masking the result of the
230 // ADD down to exactly one bit. If the constant we are adding has
231 // no bits set below this bit, then we can eliminate the ADD.
232 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
233
234 // Check to see if any bits below the one bit set in AndRHSV are set.
235 if ((AddRHS & (AndRHSV-1)) == 0) {
236 // If not, the only thing that can effect the output of the AND is
237 // the bit specified by AndRHSV. If that bit is set, the effect of
238 // the XOR is to toggle the bit. If it is clear, then the ADD has
239 // no effect.
240 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
241 TheAnd.setOperand(0, X);
242 return &TheAnd;
243 } else {
244 // Pull the XOR out of the AND.
245 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
246 NewAnd->takeName(Op);
247 return BinaryOperator::CreateXor(NewAnd, AndRHS);
248 }
249 }
250 }
251 }
252 break;
253
254 case Instruction::Shl: {
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!
257 //
258 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
259 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
260 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
261 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
262 AndRHS->getValue() & ShlMask);
263
264 if (CI->getValue() == ShlMask) {
265 // Masking out bits that the shift already masks
266 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
267 } else if (CI != AndRHS) { // Reducing bits set in and.
268 TheAnd.setOperand(1, CI);
269 return &TheAnd;
270 }
271 break;
272 }
273 case Instruction::LShr: {
274 // We know that the AND will not produce any of the bits shifted in, so if
275 // the anded constant includes them, clear them now! This only applies to
276 // unsigned shifts, because a signed shr may bring in set bits!
277 //
278 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
279 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
280 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
281 ConstantInt *CI = ConstantInt::get(Op->getContext(),
282 AndRHS->getValue() & ShrMask);
283
284 if (CI->getValue() == ShrMask) {
285 // Masking out bits that the shift already masks.
286 return ReplaceInstUsesWith(TheAnd, Op);
287 } else if (CI != AndRHS) {
288 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
289 return &TheAnd;
290 }
291 break;
292 }
293 case Instruction::AShr:
294 // Signed shr.
295 // See if this is shifting in some sign extension, then masking it out
296 // with an and.
297 if (Op->hasOneUse()) {
298 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
299 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
300 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
301 Constant *C = ConstantInt::get(Op->getContext(),
302 AndRHS->getValue() & ShrMask);
303 if (C == AndRHS) { // Masking out bits shifted in.
304 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
305 // Make the argument unsigned.
306 Value *ShVal = Op->getOperand(0);
307 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
308 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
309 }
310 }
311 break;
312 }
313 return 0;
314}
315
316
317/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
318/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
319/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
320/// whether to treat the V, Lo and HI as signed or not. IB is the location to
321/// insert new instructions.
Chris Lattner067459c2010-03-05 08:46:26 +0000322Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
323 bool isSigned, bool Inside) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000324 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
325 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
326 "Lo is not <= Hi in range emission code!");
327
328 if (Inside) {
329 if (Lo == Hi) // Trivially false.
Chris Lattner067459c2010-03-05 08:46:26 +0000330 return ConstantInt::getFalse(V->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000331
332 // V >= Min && V < Hi --> V < Hi
333 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
334 ICmpInst::Predicate pred = (isSigned ?
335 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Chris Lattner067459c2010-03-05 08:46:26 +0000336 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000337 }
338
339 // Emit V-Lo <u Hi-Lo
340 Constant *NegLo = ConstantExpr::getNeg(Lo);
341 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
342 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000343 return Builder->CreateICmpULT(Add, UpperBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000344 }
345
346 if (Lo == Hi) // Trivially true.
Chris Lattner067459c2010-03-05 08:46:26 +0000347 return ConstantInt::getTrue(V->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000348
349 // V < Min || V >= Hi -> V > Hi-1
350 Hi = SubOne(cast<ConstantInt>(Hi));
351 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
352 ICmpInst::Predicate pred = (isSigned ?
353 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Chris Lattner067459c2010-03-05 08:46:26 +0000354 return Builder->CreateICmp(pred, V, Hi);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000355 }
356
357 // Emit V-Lo >u Hi-1-Lo
358 // Note that Hi has already had one subtracted from it, above.
359 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
360 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
361 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Chris Lattner067459c2010-03-05 08:46:26 +0000362 return Builder->CreateICmpUGT(Add, LowerBound);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000363}
364
365// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
366// any number of 0s on either side. The 1s are allowed to wrap from LSB to
367// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
368// not, since all 1s are not contiguous.
369static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
370 const APInt& V = Val->getValue();
371 uint32_t BitWidth = Val->getType()->getBitWidth();
372 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
373
374 // look for the first zero bit after the run of ones
375 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
376 // look for the first non-zero bit
377 ME = V.getActiveBits();
378 return true;
379}
380
381/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
382/// where isSub determines whether the operator is a sub. If we can fold one of
383/// the following xforms:
384///
385/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
386/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
387/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
388///
389/// return (A +/- B).
390///
391Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
392 ConstantInt *Mask, bool isSub,
393 Instruction &I) {
394 Instruction *LHSI = dyn_cast<Instruction>(LHS);
395 if (!LHSI || LHSI->getNumOperands() != 2 ||
396 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
397
398 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
399
400 switch (LHSI->getOpcode()) {
401 default: return 0;
402 case Instruction::And:
403 if (ConstantExpr::getAnd(N, Mask) == Mask) {
404 // If the AndRHS is a power of two minus one (0+1+), this is simple.
405 if ((Mask->getValue().countLeadingZeros() +
406 Mask->getValue().countPopulation()) ==
407 Mask->getValue().getBitWidth())
408 break;
409
410 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
411 // part, we don't need any explicit masks to take them out of A. If that
412 // is all N is, ignore it.
413 uint32_t MB = 0, ME = 0;
414 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
415 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
416 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
417 if (MaskedValueIsZero(RHS, Mask))
418 break;
419 }
420 }
421 return 0;
422 case Instruction::Or:
423 case Instruction::Xor:
424 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
425 if ((Mask->getValue().countLeadingZeros() +
426 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
427 && ConstantExpr::getAnd(N, Mask)->isNullValue())
428 break;
429 return 0;
430 }
431
432 if (isSub)
433 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
434 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
435}
436
437/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000438Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000439 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
440
441 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
442 if (PredicatesFoldable(LHSCC, RHSCC)) {
443 if (LHS->getOperand(0) == RHS->getOperand(1) &&
444 LHS->getOperand(1) == RHS->getOperand(0))
445 LHS->swapOperands();
446 if (LHS->getOperand(0) == RHS->getOperand(0) &&
447 LHS->getOperand(1) == RHS->getOperand(1)) {
448 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
449 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
450 bool isSigned = LHS->isSigned() || RHS->isSigned();
Chris Lattner067459c2010-03-05 08:46:26 +0000451 return getICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000452 }
453 }
454
455 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
456 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
457 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
458 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
459 if (LHSCst == 0 || RHSCst == 0) return 0;
460
461 if (LHSCst == RHSCst && LHSCC == RHSCC) {
462 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
463 // where C is a power of 2
464 if (LHSCC == ICmpInst::ICMP_ULT &&
465 LHSCst->getValue().isPowerOf2()) {
466 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000467 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000468 }
469
470 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
471 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
472 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000473 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000474 }
Owen Anderson8f306a72010-08-02 09:32:13 +0000475
476 // (icmp ne (A & C1), 0) & (icmp ne (A & C2), 0) -->
477 // (icmp eq (A & (C1|C2)), (C1|C2)) where C1 and C2 are non-zero POT
478 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
479 Value *Op1 = 0, *Op2 = 0;
480 ConstantInt *CI1 = 0, *CI2 = 0;
481 if (match(LHS->getOperand(0), m_And(m_Value(Op1), m_ConstantInt(CI1))) &&
482 match(RHS->getOperand(0), m_And(m_Value(Op2), m_ConstantInt(CI2)))) {
483 if (Op1 == Op2 && !CI1->isZero() && !CI2->isZero() &&
484 CI1->getValue().isPowerOf2() && CI2->getValue().isPowerOf2()) {
485 Constant *ConstOr = ConstantExpr::getOr(CI1, CI2);
486 Value *NewAnd = Builder->CreateAnd(Op1, ConstOr);
487 return Builder->CreateICmp(ICmpInst::ICMP_EQ, NewAnd, ConstOr);
488 }
489 }
490 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000491 }
492
493 // From here on, we only handle:
494 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
495 if (Val != Val2) return 0;
496
497 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
498 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
499 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
500 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
501 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
502 return 0;
503
504 // We can't fold (ugt x, C) & (sgt x, C2).
505 if (!PredicatesFoldable(LHSCC, RHSCC))
506 return 0;
507
508 // Ensure that the larger constant is on the RHS.
509 bool ShouldSwap;
510 if (CmpInst::isSigned(LHSCC) ||
511 (ICmpInst::isEquality(LHSCC) &&
512 CmpInst::isSigned(RHSCC)))
513 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
514 else
515 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
516
517 if (ShouldSwap) {
518 std::swap(LHS, RHS);
519 std::swap(LHSCst, RHSCst);
520 std::swap(LHSCC, RHSCC);
521 }
522
Dan Gohman4a618822010-02-10 16:03:48 +0000523 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000524 // comparing a value against two constants and and'ing the result
525 // together. Because of the above check, we know that we only have
526 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
527 // (from the icmp folding check above), that the two constants
528 // are not equal and that the larger constant is on the RHS
529 assert(LHSCst != RHSCst && "Compares not folded above?");
530
531 switch (LHSCC) {
532 default: llvm_unreachable("Unknown integer condition code!");
533 case ICmpInst::ICMP_EQ:
534 switch (RHSCC) {
535 default: llvm_unreachable("Unknown integer condition code!");
536 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
537 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
538 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000539 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000540 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
541 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
542 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000543 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000544 }
545 case ICmpInst::ICMP_NE:
546 switch (RHSCC) {
547 default: llvm_unreachable("Unknown integer condition code!");
548 case ICmpInst::ICMP_ULT:
549 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000550 return Builder->CreateICmpULT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000551 break; // (X != 13 & X u< 15) -> no change
552 case ICmpInst::ICMP_SLT:
553 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000554 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000555 break; // (X != 13 & X s< 15) -> no change
556 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
557 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
558 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000559 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000560 case ICmpInst::ICMP_NE:
561 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
562 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
563 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Chris Lattner067459c2010-03-05 08:46:26 +0000564 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000565 }
566 break; // (X != 13 & X != 15) -> no change
567 }
568 break;
569 case ICmpInst::ICMP_ULT:
570 switch (RHSCC) {
571 default: llvm_unreachable("Unknown integer condition code!");
572 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
573 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000574 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000575 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
576 break;
577 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
578 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000579 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000580 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
581 break;
582 }
583 break;
584 case ICmpInst::ICMP_SLT:
585 switch (RHSCC) {
586 default: llvm_unreachable("Unknown integer condition code!");
587 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
588 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000589 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000590 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
591 break;
592 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
593 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000594 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000595 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
596 break;
597 }
598 break;
599 case ICmpInst::ICMP_UGT:
600 switch (RHSCC) {
601 default: llvm_unreachable("Unknown integer condition code!");
602 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
603 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000604 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000605 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
606 break;
607 case ICmpInst::ICMP_NE:
608 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000609 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000610 break; // (X u> 13 & X != 15) -> no change
611 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner067459c2010-03-05 08:46:26 +0000612 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000613 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
614 break;
615 }
616 break;
617 case ICmpInst::ICMP_SGT:
618 switch (RHSCC) {
619 default: llvm_unreachable("Unknown integer condition code!");
620 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
621 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000622 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000623 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
624 break;
625 case ICmpInst::ICMP_NE:
626 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000627 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000628 break; // (X s> 13 & X != 15) -> no change
629 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner067459c2010-03-05 08:46:26 +0000630 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000631 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
632 break;
633 }
634 break;
635 }
636
637 return 0;
638}
639
Chris Lattner067459c2010-03-05 08:46:26 +0000640/// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
641/// instcombine, this returns a Value which should already be inserted into the
642/// function.
643Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000644 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
645 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
646 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
647 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
648 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
649 // If either of the constants are nans, then the whole thing returns
650 // false.
651 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner067459c2010-03-05 08:46:26 +0000652 return ConstantInt::getFalse(LHS->getContext());
653 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000654 }
655
656 // Handle vector zeros. This occurs because the canonical form of
657 // "fcmp ord x,x" is "fcmp ord x, 0".
658 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
659 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +0000660 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000661 return 0;
662 }
663
664 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
665 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
666 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
667
668
669 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
670 // Swap RHS operands to match LHS.
671 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
672 std::swap(Op1LHS, Op1RHS);
673 }
674
675 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
676 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
677 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +0000678 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000679 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +0000680 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000681 if (Op0CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000682 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000683 if (Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +0000684 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000685
686 bool Op0Ordered;
687 bool Op1Ordered;
688 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
689 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
690 if (Op1Pred == 0) {
691 std::swap(LHS, RHS);
692 std::swap(Op0Pred, Op1Pred);
693 std::swap(Op0Ordered, Op1Ordered);
694 }
695 if (Op0Pred == 0) {
696 // uno && ueq -> uno && (uno || eq) -> ueq
697 // ord && olt -> ord && (ord && lt) -> olt
698 if (Op0Ordered == Op1Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +0000699 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000700
701 // uno && oeq -> uno && (ord && eq) -> false
702 // uno && ord -> false
703 if (!Op0Ordered)
Chris Lattner067459c2010-03-05 08:46:26 +0000704 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000705 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner067459c2010-03-05 08:46:26 +0000706 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000707 }
708 }
709
710 return 0;
711}
712
713
714Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
715 bool Changed = SimplifyCommutative(I);
716 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
717
718 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
719 return ReplaceInstUsesWith(I, V);
720
721 // See if we can simplify any instructions used by the instruction whose sole
722 // purpose is to compute bits we don't care about.
723 if (SimplifyDemandedInstructionBits(I))
724 return &I;
725
726 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
727 const APInt &AndRHSMask = AndRHS->getValue();
728 APInt NotAndRHS(~AndRHSMask);
729
730 // Optimize a variety of ((val OP C1) & C2) combinations...
731 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
732 Value *Op0LHS = Op0I->getOperand(0);
733 Value *Op0RHS = Op0I->getOperand(1);
734 switch (Op0I->getOpcode()) {
735 default: break;
736 case Instruction::Xor:
737 case Instruction::Or:
738 // If the mask is only needed on one incoming arm, push it up.
739 if (!Op0I->hasOneUse()) break;
740
741 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
742 // Not masking anything out for the LHS, move to RHS.
743 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
744 Op0RHS->getName()+".masked");
745 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
746 }
747 if (!isa<Constant>(Op0RHS) &&
748 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
749 // Not masking anything out for the RHS, move to LHS.
750 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
751 Op0LHS->getName()+".masked");
752 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
753 }
754
755 break;
756 case Instruction::Add:
757 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
758 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
759 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
760 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
761 return BinaryOperator::CreateAnd(V, AndRHS);
762 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
763 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
764 break;
765
766 case Instruction::Sub:
767 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
768 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
769 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
770 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
771 return BinaryOperator::CreateAnd(V, AndRHS);
772
773 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
774 // has 1's for all bits that the subtraction with A might affect.
775 if (Op0I->hasOneUse()) {
776 uint32_t BitWidth = AndRHSMask.getBitWidth();
777 uint32_t Zeros = AndRHSMask.countLeadingZeros();
778 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
779
780 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
781 if (!(A && A->isZero()) && // avoid infinite recursion.
782 MaskedValueIsZero(Op0LHS, Mask)) {
783 Value *NewNeg = Builder->CreateNeg(Op0RHS);
784 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
785 }
786 }
787 break;
788
789 case Instruction::Shl:
790 case Instruction::LShr:
791 // (1 << x) & 1 --> zext(x == 0)
792 // (1 >> x) & 1 --> zext(x == 0)
793 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
794 Value *NewICmp =
795 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
796 return new ZExtInst(NewICmp, I.getType());
797 }
798 break;
799 }
800
801 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
802 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
803 return Res;
804 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
805 // If this is an integer truncation or change from signed-to-unsigned, and
806 // if the source is an and/or with immediate, transform it. This
807 // frequently occurs for bitfield accesses.
808 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
809 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
810 CastOp->getNumOperands() == 2)
811 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
812 if (CastOp->getOpcode() == Instruction::And) {
813 // Change: and (cast (and X, C1) to T), C2
814 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
815 // This will fold the two constants together, which may allow
816 // other simplifications.
817 Value *NewCast = Builder->CreateTruncOrBitCast(
818 CastOp->getOperand(0), I.getType(),
819 CastOp->getName()+".shrunk");
820 // trunc_or_bitcast(C1)&C2
821 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
822 C3 = ConstantExpr::getAnd(C3, AndRHS);
823 return BinaryOperator::CreateAnd(NewCast, C3);
824 } else if (CastOp->getOpcode() == Instruction::Or) {
825 // Change: and (cast (or X, C1) to T), C2
826 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
827 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
828 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
829 // trunc(C1)&C2
830 return ReplaceInstUsesWith(I, AndRHS);
831 }
832 }
833 }
834 }
835
836 // Try to fold constant and into select arguments.
837 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
838 if (Instruction *R = FoldOpIntoSelect(I, SI))
839 return R;
840 if (isa<PHINode>(Op0))
841 if (Instruction *NV = FoldOpIntoPhi(I))
842 return NV;
843 }
844
845
846 // (~A & ~B) == (~(A | B)) - De Morgan's Law
847 if (Value *Op0NotVal = dyn_castNotVal(Op0))
848 if (Value *Op1NotVal = dyn_castNotVal(Op1))
849 if (Op0->hasOneUse() && Op1->hasOneUse()) {
850 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
851 I.getName()+".demorgan");
852 return BinaryOperator::CreateNot(Or);
853 }
854
855 {
856 Value *A = 0, *B = 0, *C = 0, *D = 0;
857 // (A|B) & ~(A&B) -> A^B
858 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
859 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
860 ((A == C && B == D) || (A == D && B == C)))
861 return BinaryOperator::CreateXor(A, B);
862
863 // ~(A&B) & (A|B) -> A^B
864 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
865 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
866 ((A == C && B == D) || (A == D && B == C)))
867 return BinaryOperator::CreateXor(A, B);
868
869 if (Op0->hasOneUse() &&
870 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
871 if (A == Op1) { // (A^B)&A -> A&(A^B)
872 I.swapOperands(); // Simplify below
873 std::swap(Op0, Op1);
874 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
875 cast<BinaryOperator>(Op0)->swapOperands();
876 I.swapOperands(); // Simplify below
877 std::swap(Op0, Op1);
878 }
879 }
880
881 if (Op1->hasOneUse() &&
882 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
883 if (B == Op0) { // B&(A^B) -> B&(B^A)
884 cast<BinaryOperator>(Op1)->swapOperands();
885 std::swap(A, B);
886 }
887 if (A == Op0) // A&(A^B) -> A & ~B
888 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
889 }
890
891 // (A&((~A)|B)) -> A&B
892 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
893 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
894 return BinaryOperator::CreateAnd(A, Op1);
895 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
896 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
897 return BinaryOperator::CreateAnd(A, Op0);
898 }
899
900 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
901 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
Chris Lattner067459c2010-03-05 08:46:26 +0000902 if (Value *Res = FoldAndOfICmps(LHS, RHS))
903 return ReplaceInstUsesWith(I, Res);
Chris Lattner4e8137d2010-02-11 06:26:33 +0000904
905 // If and'ing two fcmp, try combine them into one.
906 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
907 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +0000908 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
909 return ReplaceInstUsesWith(I, Res);
Chris Lattner4e8137d2010-02-11 06:26:33 +0000910
911
Chris Lattner0a8191e2010-01-05 07:50:36 +0000912 // fold (and (cast A), (cast B)) -> (cast (and A, B))
913 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner4e8137d2010-02-11 06:26:33 +0000914 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
915 const Type *SrcTy = Op0C->getOperand(0)->getType();
916 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
917 SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000918 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +0000919 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
920
921 // Only do this if the casts both really cause code to be generated.
922 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
923 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
924 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000925 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
926 }
Chris Lattner4e8137d2010-02-11 06:26:33 +0000927
928 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
929 // cast is otherwise not optimizable. This happens for vector sexts.
930 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
931 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +0000932 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +0000933 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner4e8137d2010-02-11 06:26:33 +0000934
935 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
936 // cast is otherwise not optimizable. This happens for vector sexts.
937 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
938 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +0000939 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +0000940 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +0000941 }
Chris Lattner4e8137d2010-02-11 06:26:33 +0000942 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000943
944 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
945 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
946 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
947 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
948 SI0->getOperand(1) == SI1->getOperand(1) &&
949 (SI0->hasOneUse() || SI1->hasOneUse())) {
950 Value *NewOp =
951 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
952 SI0->getName());
953 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
954 SI1->getOperand(1));
955 }
956 }
957
Chris Lattner0a8191e2010-01-05 07:50:36 +0000958 return Changed ? &I : 0;
959}
960
961/// CollectBSwapParts - Analyze the specified subexpression and see if it is
962/// capable of providing pieces of a bswap. The subexpression provides pieces
963/// of a bswap if it is proven that each of the non-zero bytes in the output of
964/// the expression came from the corresponding "byte swapped" byte in some other
965/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
966/// we know that the expression deposits the low byte of %X into the high byte
967/// of the bswap result and that all other bytes are zero. This expression is
968/// accepted, the high byte of ByteValues is set to X to indicate a correct
969/// match.
970///
971/// This function returns true if the match was unsuccessful and false if so.
972/// On entry to the function the "OverallLeftShift" is a signed integer value
973/// indicating the number of bytes that the subexpression is later shifted. For
974/// example, if the expression is later right shifted by 16 bits, the
975/// OverallLeftShift value would be -2 on entry. This is used to specify which
976/// byte of ByteValues is actually being set.
977///
978/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
979/// byte is masked to zero by a user. For example, in (X & 255), X will be
980/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
981/// this function to working on up to 32-byte (256 bit) values. ByteMask is
982/// always in the local (OverallLeftShift) coordinate space.
983///
984static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
985 SmallVector<Value*, 8> &ByteValues) {
986 if (Instruction *I = dyn_cast<Instruction>(V)) {
987 // If this is an or instruction, it may be an inner node of the bswap.
988 if (I->getOpcode() == Instruction::Or) {
989 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
990 ByteValues) ||
991 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
992 ByteValues);
993 }
994
995 // If this is a logical shift by a constant multiple of 8, recurse with
996 // OverallLeftShift and ByteMask adjusted.
997 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
998 unsigned ShAmt =
999 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1000 // Ensure the shift amount is defined and of a byte value.
1001 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1002 return true;
1003
1004 unsigned ByteShift = ShAmt >> 3;
1005 if (I->getOpcode() == Instruction::Shl) {
1006 // X << 2 -> collect(X, +2)
1007 OverallLeftShift += ByteShift;
1008 ByteMask >>= ByteShift;
1009 } else {
1010 // X >>u 2 -> collect(X, -2)
1011 OverallLeftShift -= ByteShift;
1012 ByteMask <<= ByteShift;
1013 ByteMask &= (~0U >> (32-ByteValues.size()));
1014 }
1015
1016 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1017 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1018
1019 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1020 ByteValues);
1021 }
1022
1023 // If this is a logical 'and' with a mask that clears bytes, clear the
1024 // corresponding bytes in ByteMask.
1025 if (I->getOpcode() == Instruction::And &&
1026 isa<ConstantInt>(I->getOperand(1))) {
1027 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1028 unsigned NumBytes = ByteValues.size();
1029 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1030 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1031
1032 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1033 // If this byte is masked out by a later operation, we don't care what
1034 // the and mask is.
1035 if ((ByteMask & (1 << i)) == 0)
1036 continue;
1037
1038 // If the AndMask is all zeros for this byte, clear the bit.
1039 APInt MaskB = AndMask & Byte;
1040 if (MaskB == 0) {
1041 ByteMask &= ~(1U << i);
1042 continue;
1043 }
1044
1045 // If the AndMask is not all ones for this byte, it's not a bytezap.
1046 if (MaskB != Byte)
1047 return true;
1048
1049 // Otherwise, this byte is kept.
1050 }
1051
1052 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1053 ByteValues);
1054 }
1055 }
1056
1057 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1058 // the input value to the bswap. Some observations: 1) if more than one byte
1059 // is demanded from this input, then it could not be successfully assembled
1060 // into a byteswap. At least one of the two bytes would not be aligned with
1061 // their ultimate destination.
1062 if (!isPowerOf2_32(ByteMask)) return true;
1063 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1064
1065 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1066 // is demanded, it needs to go into byte 0 of the result. This means that the
1067 // byte needs to be shifted until it lands in the right byte bucket. The
1068 // shift amount depends on the position: if the byte is coming from the high
1069 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1070 // low part, it must be shifted left.
1071 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1072 if (InputByteNo < ByteValues.size()/2) {
1073 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1074 return true;
1075 } else {
1076 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1077 return true;
1078 }
1079
1080 // If the destination byte value is already defined, the values are or'd
1081 // together, which isn't a bswap (unless it's an or of the same bits).
1082 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1083 return true;
1084 ByteValues[DestByteNo] = V;
1085 return false;
1086}
1087
1088/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1089/// If so, insert the new bswap intrinsic and return it.
1090Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1091 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1092 if (!ITy || ITy->getBitWidth() % 16 ||
1093 // ByteMask only allows up to 32-byte values.
1094 ITy->getBitWidth() > 32*8)
1095 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1096
1097 /// ByteValues - For each byte of the result, we keep track of which value
1098 /// defines each byte.
1099 SmallVector<Value*, 8> ByteValues;
1100 ByteValues.resize(ITy->getBitWidth()/8);
1101
1102 // Try to find all the pieces corresponding to the bswap.
1103 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1104 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1105 return 0;
1106
1107 // Check to see if all of the bytes come from the same value.
1108 Value *V = ByteValues[0];
1109 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1110
1111 // Check to make sure that all of the bytes come from the same value.
1112 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1113 if (ByteValues[i] != V)
1114 return 0;
1115 const Type *Tys[] = { ITy };
1116 Module *M = I.getParent()->getParent()->getParent();
1117 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1118 return CallInst::Create(F, V);
1119}
1120
1121/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1122/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1123/// we can simplify this expression to "cond ? C : D or B".
1124static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1125 Value *C, Value *D) {
1126 // If A is not a select of -1/0, this cannot match.
1127 Value *Cond = 0;
Chris Lattner9b6a1782010-02-09 01:12:41 +00001128 if (!match(A, m_SExt(m_Value(Cond))) ||
Duncan Sands9dff9be2010-02-15 16:12:20 +00001129 !Cond->getType()->isIntegerTy(1))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001130 return 0;
1131
1132 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001133 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001134 return SelectInst::Create(Cond, C, B);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001135 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001136 return SelectInst::Create(Cond, C, B);
1137
Chris Lattner0a8191e2010-01-05 07:50:36 +00001138 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001139 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
Chris Lattner64ffd112010-02-05 19:53:02 +00001140 return SelectInst::Create(Cond, C, D);
Chris Lattnerf4c8d3c2010-02-09 01:14:06 +00001141 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001142 return SelectInst::Create(Cond, C, D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001143 return 0;
1144}
1145
Chris Lattner067459c2010-03-05 08:46:26 +00001146/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1147Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001148 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1149
1150 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1151 if (PredicatesFoldable(LHSCC, RHSCC)) {
1152 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1153 LHS->getOperand(1) == RHS->getOperand(0))
1154 LHS->swapOperands();
1155 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1156 LHS->getOperand(1) == RHS->getOperand(1)) {
1157 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1158 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1159 bool isSigned = LHS->isSigned() || RHS->isSigned();
Chris Lattner067459c2010-03-05 08:46:26 +00001160 return getICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001161 }
1162 }
1163
1164 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1165 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1166 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1167 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1168 if (LHSCst == 0 || RHSCst == 0) return 0;
1169
Owen Anderson8f306a72010-08-02 09:32:13 +00001170 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1171 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1172 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1173 Value *NewOr = Builder->CreateOr(Val, Val2);
1174 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1175 }
1176
1177 // (icmp eq (A & C1), 0) | (icmp eq (A & C2), 0) -->
1178 // (icmp ne (A & (C1|C2)), (C1|C2)) where C1 and C2 are non-zero POT
1179 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
1180 Value *Op1 = 0, *Op2 = 0;
1181 ConstantInt *CI1 = 0, *CI2 = 0;
1182 if (match(LHS->getOperand(0), m_And(m_Value(Op1), m_ConstantInt(CI1))) &&
1183 match(RHS->getOperand(0), m_And(m_Value(Op2), m_ConstantInt(CI2)))) {
1184 if (Op1 == Op2 && !CI1->isZero() && !CI2->isZero() &&
1185 CI1->getValue().isPowerOf2() && CI2->getValue().isPowerOf2()) {
1186 Constant *ConstOr = ConstantExpr::getOr(CI1, CI2);
1187 Value *NewAnd = Builder->CreateAnd(Op1, ConstOr);
1188 return Builder->CreateICmp(ICmpInst::ICMP_NE, NewAnd, ConstOr);
1189 }
1190 }
1191 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001192 }
1193
1194 // From here on, we only handle:
1195 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1196 if (Val != Val2) return 0;
1197
1198 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1199 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1200 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1201 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1202 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1203 return 0;
1204
1205 // We can't fold (ugt x, C) | (sgt x, C2).
1206 if (!PredicatesFoldable(LHSCC, RHSCC))
1207 return 0;
1208
1209 // Ensure that the larger constant is on the RHS.
1210 bool ShouldSwap;
1211 if (CmpInst::isSigned(LHSCC) ||
1212 (ICmpInst::isEquality(LHSCC) &&
1213 CmpInst::isSigned(RHSCC)))
1214 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1215 else
1216 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1217
1218 if (ShouldSwap) {
1219 std::swap(LHS, RHS);
1220 std::swap(LHSCst, RHSCst);
1221 std::swap(LHSCC, RHSCC);
1222 }
1223
Dan Gohman4a618822010-02-10 16:03:48 +00001224 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001225 // comparing a value against two constants and or'ing the result
1226 // together. Because of the above check, we know that we only have
1227 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1228 // icmp folding check above), that the two constants are not
1229 // equal.
1230 assert(LHSCst != RHSCst && "Compares not folded above?");
1231
1232 switch (LHSCC) {
1233 default: llvm_unreachable("Unknown integer condition code!");
1234 case ICmpInst::ICMP_EQ:
1235 switch (RHSCC) {
1236 default: llvm_unreachable("Unknown integer condition code!");
1237 case ICmpInst::ICMP_EQ:
1238 if (LHSCst == SubOne(RHSCst)) {
1239 // (X == 13 | X == 14) -> X-13 <u 2
1240 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1241 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1242 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Chris Lattner067459c2010-03-05 08:46:26 +00001243 return Builder->CreateICmpULT(Add, AddCST);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001244 }
1245 break; // (X == 13 | X == 15) -> no change
1246 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1247 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1248 break;
1249 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1250 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1251 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001252 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001253 }
1254 break;
1255 case ICmpInst::ICMP_NE:
1256 switch (RHSCC) {
1257 default: llvm_unreachable("Unknown integer condition code!");
1258 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1259 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1260 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001261 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001262 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1263 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1264 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001265 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001266 }
1267 break;
1268 case ICmpInst::ICMP_ULT:
1269 switch (RHSCC) {
1270 default: llvm_unreachable("Unknown integer condition code!");
1271 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1272 break;
1273 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1274 // If RHSCst is [us]MAXINT, it is always false. Not handling
1275 // this can cause overflow.
1276 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001277 return LHS;
1278 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001279 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1280 break;
1281 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1282 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001283 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001284 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1285 break;
1286 }
1287 break;
1288 case ICmpInst::ICMP_SLT:
1289 switch (RHSCC) {
1290 default: llvm_unreachable("Unknown integer condition code!");
1291 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1292 break;
1293 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1294 // If RHSCst is [us]MAXINT, it is always false. Not handling
1295 // this can cause overflow.
1296 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001297 return LHS;
1298 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001299 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1300 break;
1301 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1302 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001303 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001304 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1305 break;
1306 }
1307 break;
1308 case ICmpInst::ICMP_UGT:
1309 switch (RHSCC) {
1310 default: llvm_unreachable("Unknown integer condition code!");
1311 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1312 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001313 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001314 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1315 break;
1316 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1317 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001318 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001319 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1320 break;
1321 }
1322 break;
1323 case ICmpInst::ICMP_SGT:
1324 switch (RHSCC) {
1325 default: llvm_unreachable("Unknown integer condition code!");
1326 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1327 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001328 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001329 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1330 break;
1331 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1332 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner067459c2010-03-05 08:46:26 +00001333 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001334 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1335 break;
1336 }
1337 break;
1338 }
1339 return 0;
1340}
1341
Chris Lattner067459c2010-03-05 08:46:26 +00001342/// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1343/// instcombine, this returns a Value which should already be inserted into the
1344/// function.
1345Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001346 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1347 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1348 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1349 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1350 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1351 // If either of the constants are nans, then the whole thing returns
1352 // true.
1353 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner067459c2010-03-05 08:46:26 +00001354 return ConstantInt::getTrue(LHS->getContext());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001355
1356 // Otherwise, no need to compare the two constants, compare the
1357 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001358 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001359 }
1360
1361 // Handle vector zeros. This occurs because the canonical form of
1362 // "fcmp uno x,x" is "fcmp uno x, 0".
1363 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1364 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001365 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001366
1367 return 0;
1368 }
1369
1370 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1371 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1372 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1373
1374 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1375 // Swap RHS operands to match LHS.
1376 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1377 std::swap(Op1LHS, Op1RHS);
1378 }
1379 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1380 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1381 if (Op0CC == Op1CC)
Chris Lattner067459c2010-03-05 08:46:26 +00001382 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001383 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner067459c2010-03-05 08:46:26 +00001384 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001385 if (Op0CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001386 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001387 if (Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner067459c2010-03-05 08:46:26 +00001388 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001389 bool Op0Ordered;
1390 bool Op1Ordered;
1391 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1392 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1393 if (Op0Ordered == Op1Ordered) {
1394 // If both are ordered or unordered, return a new fcmp with
1395 // or'ed predicates.
Chris Lattner067459c2010-03-05 08:46:26 +00001396 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001397 }
1398 }
1399 return 0;
1400}
1401
1402/// FoldOrWithConstants - This helper function folds:
1403///
1404/// ((A | B) & C1) | (B & C2)
1405///
1406/// into:
1407///
1408/// (A & C1) | B
1409///
1410/// when the XOR of the two constants is "all ones" (-1).
1411Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1412 Value *A, Value *B, Value *C) {
1413 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1414 if (!CI1) return 0;
1415
1416 Value *V1 = 0;
1417 ConstantInt *CI2 = 0;
1418 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1419
1420 APInt Xor = CI1->getValue() ^ CI2->getValue();
1421 if (!Xor.isAllOnesValue()) return 0;
1422
1423 if (V1 == A || V1 == B) {
1424 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1425 return BinaryOperator::CreateOr(NewOp, V1);
1426 }
1427
1428 return 0;
1429}
1430
1431Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1432 bool Changed = SimplifyCommutative(I);
1433 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1434
1435 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1436 return ReplaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001437
Chris Lattner0a8191e2010-01-05 07:50:36 +00001438 // See if we can simplify any instructions used by the instruction whose sole
1439 // purpose is to compute bits we don't care about.
1440 if (SimplifyDemandedInstructionBits(I))
1441 return &I;
1442
1443 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1444 ConstantInt *C1 = 0; Value *X = 0;
1445 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Bill Wendlingaf13d822010-03-03 00:35:56 +00001446 // iff (C1 & C2) == 0.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001447 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Bill Wendlingaf13d822010-03-03 00:35:56 +00001448 (RHS->getValue() & C1->getValue()) != 0 &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001449 Op0->hasOneUse()) {
1450 Value *Or = Builder->CreateOr(X, RHS);
1451 Or->takeName(Op0);
1452 return BinaryOperator::CreateAnd(Or,
1453 ConstantInt::get(I.getContext(),
1454 RHS->getValue() | C1->getValue()));
1455 }
1456
1457 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1458 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1459 Op0->hasOneUse()) {
1460 Value *Or = Builder->CreateOr(X, RHS);
1461 Or->takeName(Op0);
1462 return BinaryOperator::CreateXor(Or,
1463 ConstantInt::get(I.getContext(),
1464 C1->getValue() & ~RHS->getValue()));
1465 }
1466
1467 // Try to fold constant and into select arguments.
1468 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1469 if (Instruction *R = FoldOpIntoSelect(I, SI))
1470 return R;
Bill Wendlingaf13d822010-03-03 00:35:56 +00001471
Chris Lattner0a8191e2010-01-05 07:50:36 +00001472 if (isa<PHINode>(Op0))
1473 if (Instruction *NV = FoldOpIntoPhi(I))
1474 return NV;
1475 }
1476
1477 Value *A = 0, *B = 0;
1478 ConstantInt *C1 = 0, *C2 = 0;
1479
1480 // (A | B) | C and A | (B | C) -> bswap if possible.
1481 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1482 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1483 match(Op1, m_Or(m_Value(), m_Value())) ||
1484 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1485 match(Op1, m_Shift(m_Value(), m_Value())))) {
1486 if (Instruction *BSwap = MatchBSwap(I))
1487 return BSwap;
1488 }
1489
1490 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1491 if (Op0->hasOneUse() &&
1492 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1493 MaskedValueIsZero(Op1, C1->getValue())) {
1494 Value *NOr = Builder->CreateOr(A, Op1);
1495 NOr->takeName(Op0);
1496 return BinaryOperator::CreateXor(NOr, C1);
1497 }
1498
1499 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1500 if (Op1->hasOneUse() &&
1501 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1502 MaskedValueIsZero(Op0, C1->getValue())) {
1503 Value *NOr = Builder->CreateOr(A, Op0);
1504 NOr->takeName(Op0);
1505 return BinaryOperator::CreateXor(NOr, C1);
1506 }
1507
1508 // (A & C)|(B & D)
1509 Value *C = 0, *D = 0;
1510 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1511 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1512 Value *V1 = 0, *V2 = 0, *V3 = 0;
1513 C1 = dyn_cast<ConstantInt>(C);
1514 C2 = dyn_cast<ConstantInt>(D);
1515 if (C1 && C2) { // (A & C1)|(B & C2)
1516 // If we have: ((V + N) & C1) | (V & C2)
1517 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1518 // replace with V+N.
1519 if (C1->getValue() == ~C2->getValue()) {
1520 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1521 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1522 // Add commutes, try both ways.
1523 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1524 return ReplaceInstUsesWith(I, A);
1525 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1526 return ReplaceInstUsesWith(I, A);
1527 }
1528 // Or commutes, try both ways.
1529 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1530 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1531 // Add commutes, try both ways.
1532 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1533 return ReplaceInstUsesWith(I, B);
1534 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1535 return ReplaceInstUsesWith(I, B);
1536 }
1537 }
1538
Chris Lattner0a8191e2010-01-05 07:50:36 +00001539 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00001540 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1541 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001542 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1543 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1544 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1545 return BinaryOperator::CreateAnd(A,
1546 ConstantInt::get(A->getContext(),
1547 C1->getValue()|C2->getValue()));
1548 // Or commutes, try both ways.
1549 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1550 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1551 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1552 return BinaryOperator::CreateAnd(B,
1553 ConstantInt::get(B->getContext(),
1554 C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00001555
1556 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1557 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1558 ConstantInt *C3 = 0, *C4 = 0;
1559 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1560 (C3->getValue() & ~C1->getValue()) == 0 &&
1561 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1562 (C4->getValue() & ~C2->getValue()) == 0) {
1563 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1564 return BinaryOperator::CreateAnd(V2,
1565 ConstantInt::get(B->getContext(),
1566 C1->getValue()|C2->getValue()));
1567 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001568 }
1569 }
1570
1571 // Check to see if we have any common things being and'ed. If so, find the
1572 // terms for V1 & (V2|V3).
1573 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1574 V1 = 0;
1575 if (A == B) // (A & C)|(A & D) == A & (C|D)
1576 V1 = A, V2 = C, V3 = D;
1577 else if (A == D) // (A & C)|(B & A) == A & (B|C)
1578 V1 = A, V2 = B, V3 = C;
1579 else if (C == B) // (A & C)|(C & D) == C & (A|D)
1580 V1 = C, V2 = A, V3 = D;
1581 else if (C == D) // (A & C)|(B & C) == C & (A|B)
1582 V1 = C, V2 = A, V3 = B;
1583
1584 if (V1) {
1585 Value *Or = Builder->CreateOr(V2, V3, "tmp");
1586 return BinaryOperator::CreateAnd(V1, Or);
1587 }
1588 }
1589
Chris Lattner8e2c4712010-02-02 02:43:51 +00001590 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1591 // Don't do this for vector select idioms, the code generator doesn't handle
1592 // them well yet.
Duncan Sands19d0b472010-02-16 11:11:14 +00001593 if (!I.getType()->isVectorTy()) {
Chris Lattner8e2c4712010-02-02 02:43:51 +00001594 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1595 return Match;
1596 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1597 return Match;
1598 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1599 return Match;
1600 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1601 return Match;
1602 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001603
1604 // ((A&~B)|(~A&B)) -> A^B
1605 if ((match(C, m_Not(m_Specific(D))) &&
1606 match(B, m_Not(m_Specific(A)))))
1607 return BinaryOperator::CreateXor(A, D);
1608 // ((~B&A)|(~A&B)) -> A^B
1609 if ((match(A, m_Not(m_Specific(D))) &&
1610 match(B, m_Not(m_Specific(C)))))
1611 return BinaryOperator::CreateXor(C, D);
1612 // ((A&~B)|(B&~A)) -> A^B
1613 if ((match(C, m_Not(m_Specific(B))) &&
1614 match(D, m_Not(m_Specific(A)))))
1615 return BinaryOperator::CreateXor(A, B);
1616 // ((~B&A)|(B&~A)) -> A^B
1617 if ((match(A, m_Not(m_Specific(B))) &&
1618 match(D, m_Not(m_Specific(C)))))
1619 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00001620
1621 // ((A|B)&1)|(B&-2) -> (A&1) | B
1622 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1623 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1624 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1625 if (Ret) return Ret;
1626 }
1627 // (B&-2)|((A|B)&1) -> (A&1) | B
1628 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1629 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1630 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1631 if (Ret) return Ret;
1632 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001633 }
1634
1635 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1636 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1637 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1638 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1639 SI0->getOperand(1) == SI1->getOperand(1) &&
1640 (SI0->hasOneUse() || SI1->hasOneUse())) {
1641 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1642 SI0->getName());
1643 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1644 SI1->getOperand(1));
1645 }
1646 }
1647
Chris Lattner0a8191e2010-01-05 07:50:36 +00001648 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1649 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1650 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1651 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1652 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1653 I.getName()+".demorgan");
1654 return BinaryOperator::CreateNot(And);
1655 }
1656
1657 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1658 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner067459c2010-03-05 08:46:26 +00001659 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1660 return ReplaceInstUsesWith(I, Res);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001661
Chris Lattner4e8137d2010-02-11 06:26:33 +00001662 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1663 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1664 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001665 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1666 return ReplaceInstUsesWith(I, Res);
Chris Lattner4e8137d2010-02-11 06:26:33 +00001667
Chris Lattner0a8191e2010-01-05 07:50:36 +00001668 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1669 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1670 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1671 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Chris Lattner4e8137d2010-02-11 06:26:33 +00001672 const Type *SrcTy = Op0C->getOperand(0)->getType();
1673 if (SrcTy == Op1C->getOperand(0)->getType() &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001674 SrcTy->isIntOrIntVectorTy()) {
Chris Lattner4e8137d2010-02-11 06:26:33 +00001675 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1676
1677 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001678 // Only do this if the casts both really cause code to be
1679 // generated.
Chris Lattner4e8137d2010-02-11 06:26:33 +00001680 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1681 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1682 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001683 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1684 }
Chris Lattner4e8137d2010-02-11 06:26:33 +00001685
1686 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1687 // cast is otherwise not optimizable. This happens for vector sexts.
1688 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1689 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001690 if (Value *Res = FoldOrOfICmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001691 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner4e8137d2010-02-11 06:26:33 +00001692
1693 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1694 // cast is otherwise not optimizable. This happens for vector sexts.
1695 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1696 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
Chris Lattner067459c2010-03-05 08:46:26 +00001697 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Chris Lattner4e8137d2010-02-11 06:26:33 +00001698 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
Chris Lattner0a8191e2010-01-05 07:50:36 +00001699 }
1700 }
1701 }
1702
Chris Lattner0a8191e2010-01-05 07:50:36 +00001703 return Changed ? &I : 0;
1704}
1705
1706Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1707 bool Changed = SimplifyCommutative(I);
1708 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1709
1710 if (isa<UndefValue>(Op1)) {
1711 if (isa<UndefValue>(Op0))
1712 // Handle undef ^ undef -> 0 special case. This is a common
1713 // idiom (misuse).
1714 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1715 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1716 }
1717
1718 // xor X, X = 0
1719 if (Op0 == Op1)
1720 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1721
1722 // See if we can simplify any instructions used by the instruction whose sole
1723 // purpose is to compute bits we don't care about.
1724 if (SimplifyDemandedInstructionBits(I))
1725 return &I;
Duncan Sands19d0b472010-02-16 11:11:14 +00001726 if (I.getType()->isVectorTy())
Chris Lattner0a8191e2010-01-05 07:50:36 +00001727 if (isa<ConstantAggregateZero>(Op1))
1728 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
1729
1730 // Is this a ~ operation?
1731 if (Value *NotOp = dyn_castNotVal(&I)) {
1732 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1733 if (Op0I->getOpcode() == Instruction::And ||
1734 Op0I->getOpcode() == Instruction::Or) {
1735 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1736 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1737 if (dyn_castNotVal(Op0I->getOperand(1)))
1738 Op0I->swapOperands();
1739 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1740 Value *NotY =
1741 Builder->CreateNot(Op0I->getOperand(1),
1742 Op0I->getOperand(1)->getName()+".not");
1743 if (Op0I->getOpcode() == Instruction::And)
1744 return BinaryOperator::CreateOr(Op0NotVal, NotY);
1745 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1746 }
1747
1748 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1749 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1750 if (isFreeToInvert(Op0I->getOperand(0)) &&
1751 isFreeToInvert(Op0I->getOperand(1))) {
1752 Value *NotX =
1753 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1754 Value *NotY =
1755 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1756 if (Op0I->getOpcode() == Instruction::And)
1757 return BinaryOperator::CreateOr(NotX, NotY);
1758 return BinaryOperator::CreateAnd(NotX, NotY);
1759 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00001760
1761 } else if (Op0I->getOpcode() == Instruction::AShr) {
1762 // ~(~X >>s Y) --> (X >>s Y)
1763 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
1764 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001765 }
1766 }
1767 }
1768
1769
1770 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Dan Gohman0a8175d2010-04-09 14:53:59 +00001771 if (RHS->isOne() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00001772 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00001773 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
1774 return CmpInst::Create(CI->getOpcode(),
1775 CI->getInversePredicate(),
1776 CI->getOperand(0), CI->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001777
1778 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
1779 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1780 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
1781 if (CI->hasOneUse() && Op0C->hasOneUse()) {
1782 Instruction::CastOps Opcode = Op0C->getOpcode();
1783 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
1784 (RHS == ConstantExpr::getCast(Opcode,
1785 ConstantInt::getTrue(I.getContext()),
1786 Op0C->getDestTy()))) {
1787 CI->setPredicate(CI->getInversePredicate());
1788 return CastInst::Create(Opcode, CI, Op0C->getType());
1789 }
1790 }
1791 }
1792 }
1793
1794 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1795 // ~(c-X) == X-c-1 == X+(-c-1)
1796 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1797 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1798 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1799 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1800 ConstantInt::get(I.getType(), 1));
1801 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
1802 }
1803
1804 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1805 if (Op0I->getOpcode() == Instruction::Add) {
1806 // ~(X-c) --> (-c-1)-X
1807 if (RHS->isAllOnesValue()) {
1808 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1809 return BinaryOperator::CreateSub(
1810 ConstantExpr::getSub(NegOp0CI,
1811 ConstantInt::get(I.getType(), 1)),
1812 Op0I->getOperand(0));
1813 } else if (RHS->getValue().isSignBit()) {
1814 // (X + C) ^ signbit -> (X + C + signbit)
1815 Constant *C = ConstantInt::get(I.getContext(),
1816 RHS->getValue() + Op0CI->getValue());
1817 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
1818
1819 }
1820 } else if (Op0I->getOpcode() == Instruction::Or) {
1821 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
1822 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
1823 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
1824 // Anything in both C1 and C2 is known to be zero, remove it from
1825 // NewRHS.
1826 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
1827 NewRHS = ConstantExpr::getAnd(NewRHS,
1828 ConstantExpr::getNot(CommonBits));
1829 Worklist.Add(Op0I);
1830 I.setOperand(0, Op0I->getOperand(0));
1831 I.setOperand(1, NewRHS);
1832 return &I;
1833 }
1834 }
1835 }
1836 }
1837
1838 // Try to fold constant and into select arguments.
1839 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1840 if (Instruction *R = FoldOpIntoSelect(I, SI))
1841 return R;
1842 if (isa<PHINode>(Op0))
1843 if (Instruction *NV = FoldOpIntoPhi(I))
1844 return NV;
1845 }
1846
1847 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1848 if (X == Op1)
1849 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1850
1851 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1852 if (X == Op0)
1853 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1854
1855
1856 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
1857 if (Op1I) {
1858 Value *A, *B;
1859 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
1860 if (A == Op0) { // B^(B|A) == (A|B)^B
1861 Op1I->swapOperands();
1862 I.swapOperands();
1863 std::swap(Op0, Op1);
1864 } else if (B == Op0) { // B^(A|B) == (A|B)^B
1865 I.swapOperands(); // Simplified below.
1866 std::swap(Op0, Op1);
1867 }
1868 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
1869 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
1870 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
1871 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
1872 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
1873 Op1I->hasOneUse()){
1874 if (A == Op0) { // A^(A&B) -> A^(B&A)
1875 Op1I->swapOperands();
1876 std::swap(A, B);
1877 }
1878 if (B == Op0) { // A^(B&A) -> (B&A)^A
1879 I.swapOperands(); // Simplified below.
1880 std::swap(Op0, Op1);
1881 }
1882 }
1883 }
1884
1885 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
1886 if (Op0I) {
1887 Value *A, *B;
1888 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1889 Op0I->hasOneUse()) {
1890 if (A == Op1) // (B|A)^B == (A|B)^B
1891 std::swap(A, B);
1892 if (B == Op1) // (A|B)^B == A & ~B
1893 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
1894 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
1895 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
1896 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
1897 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
1898 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1899 Op0I->hasOneUse()){
1900 if (A == Op1) // (A&B)^A -> (B&A)^A
1901 std::swap(A, B);
1902 if (B == Op1 && // (B&A)^A == ~B & A
1903 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
1904 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
1905 }
1906 }
1907 }
1908
1909 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
1910 if (Op0I && Op1I && Op0I->isShift() &&
1911 Op0I->getOpcode() == Op1I->getOpcode() &&
1912 Op0I->getOperand(1) == Op1I->getOperand(1) &&
1913 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
1914 Value *NewOp =
1915 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
1916 Op0I->getName());
1917 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
1918 Op1I->getOperand(1));
1919 }
1920
1921 if (Op0I && Op1I) {
1922 Value *A, *B, *C, *D;
1923 // (A & B)^(A | B) -> A ^ B
1924 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1925 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
1926 if ((A == C && B == D) || (A == D && B == C))
1927 return BinaryOperator::CreateXor(A, B);
1928 }
1929 // (A | B)^(A & B) -> A ^ B
1930 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1931 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1932 if ((A == C && B == D) || (A == D && B == C))
1933 return BinaryOperator::CreateXor(A, B);
1934 }
1935
1936 // (A & B)^(C & D)
1937 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
1938 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1939 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1940 // (X & Y)^(X & Y) -> (Y^Z) & X
1941 Value *X = 0, *Y = 0, *Z = 0;
1942 if (A == C)
1943 X = A, Y = B, Z = D;
1944 else if (A == D)
1945 X = A, Y = B, Z = C;
1946 else if (B == C)
1947 X = B, Y = A, Z = D;
1948 else if (B == D)
1949 X = B, Y = A, Z = C;
1950
1951 if (X) {
1952 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
1953 return BinaryOperator::CreateAnd(NewOp, X);
1954 }
1955 }
1956 }
1957
1958 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
1959 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1960 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1961 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
1962 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1963 LHS->getOperand(1) == RHS->getOperand(0))
1964 LHS->swapOperands();
1965 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1966 LHS->getOperand(1) == RHS->getOperand(1)) {
1967 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1968 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
1969 bool isSigned = LHS->isSigned() || RHS->isSigned();
Chris Lattner067459c2010-03-05 08:46:26 +00001970 return ReplaceInstUsesWith(I,
1971 getICmpValue(isSigned, Code, Op0, Op1, Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001972 }
1973 }
1974
1975 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
1976 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1977 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1978 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
1979 const Type *SrcTy = Op0C->getOperand(0)->getType();
Duncan Sands9dff9be2010-02-15 16:12:20 +00001980 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001981 // Only do this if the casts both really cause code to be generated.
Chris Lattner4e8137d2010-02-11 06:26:33 +00001982 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
1983 I.getType()) &&
1984 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
1985 I.getType())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001986 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
1987 Op1C->getOperand(0), I.getName());
1988 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1989 }
1990 }
1991 }
1992
1993 return Changed ? &I : 0;
1994}