1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitAnd, visitOr, and visitXor functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Support/PatternMatch.h"
19 using namespace PatternMatch;
22 /// AddOne - Add one to a ConstantInt.
23 static Constant *AddOne(Constant *C) {
24 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
26 /// SubOne - Subtract one from a ConstantInt.
27 static Constant *SubOne(ConstantInt *C) {
28 return ConstantInt::get(C->getContext(), C->getValue()-1);
31 /// isFreeToInvert - Return true if the specified value is free to invert (apply
32 /// ~ to). This happens in cases where the ~ can be eliminated.
33 static inline bool isFreeToInvert(Value *V) {
35 if (BinaryOperator::isNot(V))
38 // Constants can be considered to be not'ed values.
39 if (isa<ConstantInt>(V))
42 // Compares can be inverted if they have a single use.
43 if (CmpInst *CI = dyn_cast<CmpInst>(V))
44 return CI->hasOneUse();
49 static 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))
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());
65 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
66 /// are carefully arranged to allow folding of expressions such as:
68 /// (A < B) | (A > B) --> (A != B)
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)
73 /// Three bits are used to represent the condition, as follows:
78 /// <=> Value Definition
79 /// 000 0 Always false
88 static unsigned getICmpCode(const ICmpInst *ICI) {
89 switch (ICI->getPredicate()) {
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
103 llvm_unreachable("Invalid ICmp predicate!");
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.
111 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
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
130 // Not expecting FCMP_FALSE and FCMP_TRUE;
131 llvm_unreachable("Unexpected FCmp predicate!");
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.
140 static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
141 CmpInst::Predicate Pred;
143 default: assert(0 && "Illegal ICmp code!");
145 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
146 case 1: Pred = Sign ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
147 case 2: Pred = ICmpInst::ICMP_EQ; break;
148 case 3: Pred = Sign ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
149 case 4: Pred = Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
150 case 5: Pred = ICmpInst::ICMP_NE; break;
151 case 6: Pred = Sign ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
153 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
155 return new ICmpInst(Pred, LHS, RHS);
158 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
159 /// opcode and two operands into either a FCmp instruction. isordered is passed
160 /// in to determine which kind of predicate to use in the new fcmp instruction.
161 static Value *getFCmpValue(bool isordered, unsigned code,
162 Value *LHS, Value *RHS) {
163 CmpInst::Predicate Pred;
165 default: assert(0 && "Illegal FCmp code!");
166 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
167 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
168 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
169 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
170 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
171 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
172 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
173 case 7: return ConstantInt::getTrue(LHS->getContext());
175 return new FCmpInst(Pred, LHS, RHS);
178 /// PredicatesFoldable - Return true if both predicates match sign or if at
179 /// least one of them is an equality comparison (which is signless).
180 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
181 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
182 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
183 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
186 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
187 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
188 // guaranteed to be a binary operator.
189 Instruction *InstCombiner::OptAndOp(Instruction *Op,
192 BinaryOperator &TheAnd) {
193 Value *X = Op->getOperand(0);
194 Constant *Together = 0;
196 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
198 switch (Op->getOpcode()) {
199 case Instruction::Xor:
200 if (Op->hasOneUse()) {
201 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
202 Value *And = Builder->CreateAnd(X, AndRHS);
204 return BinaryOperator::CreateXor(And, Together);
207 case Instruction::Or:
208 if (Together == AndRHS) // (X | C) & C --> C
209 return ReplaceInstUsesWith(TheAnd, AndRHS);
211 if (Op->hasOneUse() && Together != OpRHS) {
212 // (X | C1) & C2 --> (X | (C1&C2)) & C2
213 Value *Or = Builder->CreateOr(X, Together);
215 return BinaryOperator::CreateAnd(Or, AndRHS);
218 case Instruction::Add:
219 if (Op->hasOneUse()) {
220 // Adding a one to a single bit bit-field should be turned into an XOR
221 // of the bit. First thing to check is to see if this AND is with a
222 // single bit constant.
223 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
225 // If there is only one bit set.
226 if (AndRHSV.isPowerOf2()) {
227 // Ok, at this point, we know that we are masking the result of the
228 // ADD down to exactly one bit. If the constant we are adding has
229 // no bits set below this bit, then we can eliminate the ADD.
230 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
232 // Check to see if any bits below the one bit set in AndRHSV are set.
233 if ((AddRHS & (AndRHSV-1)) == 0) {
234 // If not, the only thing that can effect the output of the AND is
235 // the bit specified by AndRHSV. If that bit is set, the effect of
236 // the XOR is to toggle the bit. If it is clear, then the ADD has
238 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
239 TheAnd.setOperand(0, X);
242 // Pull the XOR out of the AND.
243 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
244 NewAnd->takeName(Op);
245 return BinaryOperator::CreateXor(NewAnd, AndRHS);
252 case Instruction::Shl: {
253 // We know that the AND will not produce any of the bits shifted in, so if
254 // the anded constant includes them, clear them now!
256 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
257 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
258 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
259 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
260 AndRHS->getValue() & ShlMask);
262 if (CI->getValue() == ShlMask) {
263 // Masking out bits that the shift already masks
264 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
265 } else if (CI != AndRHS) { // Reducing bits set in and.
266 TheAnd.setOperand(1, CI);
271 case Instruction::LShr: {
272 // We know that the AND will not produce any of the bits shifted in, so if
273 // the anded constant includes them, clear them now! This only applies to
274 // unsigned shifts, because a signed shr may bring in set bits!
276 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
277 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
278 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
279 ConstantInt *CI = ConstantInt::get(Op->getContext(),
280 AndRHS->getValue() & ShrMask);
282 if (CI->getValue() == ShrMask) {
283 // Masking out bits that the shift already masks.
284 return ReplaceInstUsesWith(TheAnd, Op);
285 } else if (CI != AndRHS) {
286 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
291 case Instruction::AShr:
293 // See if this is shifting in some sign extension, then masking it out
295 if (Op->hasOneUse()) {
296 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
297 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
298 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
299 Constant *C = ConstantInt::get(Op->getContext(),
300 AndRHS->getValue() & ShrMask);
301 if (C == AndRHS) { // Masking out bits shifted in.
302 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
303 // Make the argument unsigned.
304 Value *ShVal = Op->getOperand(0);
305 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
306 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
315 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
316 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
317 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
318 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
319 /// insert new instructions.
320 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
321 bool isSigned, bool Inside,
323 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
324 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
325 "Lo is not <= Hi in range emission code!");
328 if (Lo == Hi) // Trivially false.
329 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
331 // V >= Min && V < Hi --> V < Hi
332 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
333 ICmpInst::Predicate pred = (isSigned ?
334 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
335 return new ICmpInst(pred, V, Hi);
338 // Emit V-Lo <u Hi-Lo
339 Constant *NegLo = ConstantExpr::getNeg(Lo);
340 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
341 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
342 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
345 if (Lo == Hi) // Trivially true.
346 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
348 // V < Min || V >= Hi -> V > Hi-1
349 Hi = SubOne(cast<ConstantInt>(Hi));
350 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
351 ICmpInst::Predicate pred = (isSigned ?
352 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
353 return new ICmpInst(pred, V, Hi);
356 // Emit V-Lo >u Hi-1-Lo
357 // Note that Hi has already had one subtracted from it, above.
358 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
359 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
360 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
361 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
364 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
365 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
366 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
367 // not, since all 1s are not contiguous.
368 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
369 const APInt& V = Val->getValue();
370 uint32_t BitWidth = Val->getType()->getBitWidth();
371 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
373 // look for the first zero bit after the run of ones
374 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
375 // look for the first non-zero bit
376 ME = V.getActiveBits();
380 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
381 /// where isSub determines whether the operator is a sub. If we can fold one of
382 /// the following xforms:
384 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
385 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
386 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
388 /// return (A +/- B).
390 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
391 ConstantInt *Mask, bool isSub,
393 Instruction *LHSI = dyn_cast<Instruction>(LHS);
394 if (!LHSI || LHSI->getNumOperands() != 2 ||
395 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
397 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
399 switch (LHSI->getOpcode()) {
401 case Instruction::And:
402 if (ConstantExpr::getAnd(N, Mask) == Mask) {
403 // If the AndRHS is a power of two minus one (0+1+), this is simple.
404 if ((Mask->getValue().countLeadingZeros() +
405 Mask->getValue().countPopulation()) ==
406 Mask->getValue().getBitWidth())
409 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
410 // part, we don't need any explicit masks to take them out of A. If that
411 // is all N is, ignore it.
412 uint32_t MB = 0, ME = 0;
413 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
414 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
415 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
416 if (MaskedValueIsZero(RHS, Mask))
421 case Instruction::Or:
422 case Instruction::Xor:
423 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
424 if ((Mask->getValue().countLeadingZeros() +
425 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
426 && ConstantExpr::getAnd(N, Mask)->isNullValue())
432 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
433 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
436 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
437 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
438 ICmpInst *LHS, ICmpInst *RHS) {
439 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
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))
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();
451 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
452 if (Instruction *I = dyn_cast<Instruction>(RV))
454 // Otherwise, it's a constant boolean value.
455 return ReplaceInstUsesWith(I, RV);
459 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
460 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
461 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
462 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
463 if (LHSCst == 0 || RHSCst == 0) return 0;
465 if (LHSCst == RHSCst && LHSCC == RHSCC) {
466 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
467 // where C is a power of 2
468 if (LHSCC == ICmpInst::ICMP_ULT &&
469 LHSCst->getValue().isPowerOf2()) {
470 Value *NewOr = Builder->CreateOr(Val, Val2);
471 return new ICmpInst(LHSCC, NewOr, LHSCst);
474 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
475 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
476 Value *NewOr = Builder->CreateOr(Val, Val2);
477 return new ICmpInst(LHSCC, NewOr, LHSCst);
481 // From here on, we only handle:
482 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
483 if (Val != Val2) return 0;
485 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
486 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
487 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
488 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
489 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
492 // We can't fold (ugt x, C) & (sgt x, C2).
493 if (!PredicatesFoldable(LHSCC, RHSCC))
496 // Ensure that the larger constant is on the RHS.
498 if (CmpInst::isSigned(LHSCC) ||
499 (ICmpInst::isEquality(LHSCC) &&
500 CmpInst::isSigned(RHSCC)))
501 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
503 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
507 std::swap(LHSCst, RHSCst);
508 std::swap(LHSCC, RHSCC);
511 // At this point, we know we have two icmp instructions
512 // comparing a value against two constants and and'ing the result
513 // together. Because of the above check, we know that we only have
514 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
515 // (from the icmp folding check above), that the two constants
516 // are not equal and that the larger constant is on the RHS
517 assert(LHSCst != RHSCst && "Compares not folded above?");
520 default: llvm_unreachable("Unknown integer condition code!");
521 case ICmpInst::ICMP_EQ:
523 default: llvm_unreachable("Unknown integer condition code!");
524 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
525 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
526 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
527 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
528 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
529 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
530 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
531 return ReplaceInstUsesWith(I, LHS);
533 case ICmpInst::ICMP_NE:
535 default: llvm_unreachable("Unknown integer condition code!");
536 case ICmpInst::ICMP_ULT:
537 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
538 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
539 break; // (X != 13 & X u< 15) -> no change
540 case ICmpInst::ICMP_SLT:
541 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
542 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
543 break; // (X != 13 & X s< 15) -> no change
544 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
545 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
546 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
547 return ReplaceInstUsesWith(I, RHS);
548 case ICmpInst::ICMP_NE:
549 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
550 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
551 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
552 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
553 ConstantInt::get(Add->getType(), 1));
555 break; // (X != 13 & X != 15) -> no change
558 case ICmpInst::ICMP_ULT:
560 default: llvm_unreachable("Unknown integer condition code!");
561 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
562 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
563 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
564 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
566 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
567 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
568 return ReplaceInstUsesWith(I, LHS);
569 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
573 case ICmpInst::ICMP_SLT:
575 default: llvm_unreachable("Unknown integer condition code!");
576 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
577 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
578 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
579 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
581 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
582 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
583 return ReplaceInstUsesWith(I, LHS);
584 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
588 case ICmpInst::ICMP_UGT:
590 default: llvm_unreachable("Unknown integer condition code!");
591 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
592 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
593 return ReplaceInstUsesWith(I, RHS);
594 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
596 case ICmpInst::ICMP_NE:
597 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
598 return new ICmpInst(LHSCC, Val, RHSCst);
599 break; // (X u> 13 & X != 15) -> no change
600 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
601 return InsertRangeTest(Val, AddOne(LHSCst),
602 RHSCst, false, true, I);
603 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
607 case ICmpInst::ICMP_SGT:
609 default: llvm_unreachable("Unknown integer condition code!");
610 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
611 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
612 return ReplaceInstUsesWith(I, RHS);
613 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
615 case ICmpInst::ICMP_NE:
616 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
617 return new ICmpInst(LHSCC, Val, RHSCst);
618 break; // (X s> 13 & X != 15) -> no change
619 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
620 return InsertRangeTest(Val, AddOne(LHSCst),
621 RHSCst, true, true, I);
622 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
631 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
634 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
635 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
636 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
637 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
638 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
639 // If either of the constants are nans, then the whole thing returns
641 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
642 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
643 return new FCmpInst(FCmpInst::FCMP_ORD,
644 LHS->getOperand(0), RHS->getOperand(0));
647 // Handle vector zeros. This occurs because the canonical form of
648 // "fcmp ord x,x" is "fcmp ord x, 0".
649 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
650 isa<ConstantAggregateZero>(RHS->getOperand(1)))
651 return new FCmpInst(FCmpInst::FCMP_ORD,
652 LHS->getOperand(0), RHS->getOperand(0));
656 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
657 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
658 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
661 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
662 // Swap RHS operands to match LHS.
663 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
664 std::swap(Op1LHS, Op1RHS);
667 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
668 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
670 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
672 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
673 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
674 if (Op0CC == FCmpInst::FCMP_TRUE)
675 return ReplaceInstUsesWith(I, RHS);
676 if (Op1CC == FCmpInst::FCMP_TRUE)
677 return ReplaceInstUsesWith(I, LHS);
681 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
682 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
685 std::swap(Op0Pred, Op1Pred);
686 std::swap(Op0Ordered, Op1Ordered);
689 // uno && ueq -> uno && (uno || eq) -> ueq
690 // ord && olt -> ord && (ord && lt) -> olt
691 if (Op0Ordered == Op1Ordered)
692 return ReplaceInstUsesWith(I, RHS);
694 // uno && oeq -> uno && (ord && eq) -> false
695 // uno && ord -> false
697 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
698 // ord && ueq -> ord && (uno || eq) -> oeq
699 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
707 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
708 bool Changed = SimplifyCommutative(I);
709 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
711 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
712 return ReplaceInstUsesWith(I, V);
714 // See if we can simplify any instructions used by the instruction whose sole
715 // purpose is to compute bits we don't care about.
716 if (SimplifyDemandedInstructionBits(I))
719 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
720 const APInt &AndRHSMask = AndRHS->getValue();
721 APInt NotAndRHS(~AndRHSMask);
723 // Optimize a variety of ((val OP C1) & C2) combinations...
724 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
725 Value *Op0LHS = Op0I->getOperand(0);
726 Value *Op0RHS = Op0I->getOperand(1);
727 switch (Op0I->getOpcode()) {
729 case Instruction::Xor:
730 case Instruction::Or:
731 // If the mask is only needed on one incoming arm, push it up.
732 if (!Op0I->hasOneUse()) break;
734 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
735 // Not masking anything out for the LHS, move to RHS.
736 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
737 Op0RHS->getName()+".masked");
738 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
740 if (!isa<Constant>(Op0RHS) &&
741 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
742 // Not masking anything out for the RHS, move to LHS.
743 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
744 Op0LHS->getName()+".masked");
745 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
749 case Instruction::Add:
750 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
751 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
752 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
753 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
754 return BinaryOperator::CreateAnd(V, AndRHS);
755 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
756 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
759 case Instruction::Sub:
760 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
761 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
762 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
763 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
764 return BinaryOperator::CreateAnd(V, AndRHS);
766 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
767 // has 1's for all bits that the subtraction with A might affect.
768 if (Op0I->hasOneUse()) {
769 uint32_t BitWidth = AndRHSMask.getBitWidth();
770 uint32_t Zeros = AndRHSMask.countLeadingZeros();
771 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
773 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
774 if (!(A && A->isZero()) && // avoid infinite recursion.
775 MaskedValueIsZero(Op0LHS, Mask)) {
776 Value *NewNeg = Builder->CreateNeg(Op0RHS);
777 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
782 case Instruction::Shl:
783 case Instruction::LShr:
784 // (1 << x) & 1 --> zext(x == 0)
785 // (1 >> x) & 1 --> zext(x == 0)
786 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
788 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
789 return new ZExtInst(NewICmp, I.getType());
794 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
795 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
797 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
798 // If this is an integer truncation or change from signed-to-unsigned, and
799 // if the source is an and/or with immediate, transform it. This
800 // frequently occurs for bitfield accesses.
801 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
802 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
803 CastOp->getNumOperands() == 2)
804 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
805 if (CastOp->getOpcode() == Instruction::And) {
806 // Change: and (cast (and X, C1) to T), C2
807 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
808 // This will fold the two constants together, which may allow
809 // other simplifications.
810 Value *NewCast = Builder->CreateTruncOrBitCast(
811 CastOp->getOperand(0), I.getType(),
812 CastOp->getName()+".shrunk");
813 // trunc_or_bitcast(C1)&C2
814 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
815 C3 = ConstantExpr::getAnd(C3, AndRHS);
816 return BinaryOperator::CreateAnd(NewCast, C3);
817 } else if (CastOp->getOpcode() == Instruction::Or) {
818 // Change: and (cast (or X, C1) to T), C2
819 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
820 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
821 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
823 return ReplaceInstUsesWith(I, AndRHS);
829 // Try to fold constant and into select arguments.
830 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
831 if (Instruction *R = FoldOpIntoSelect(I, SI))
833 if (isa<PHINode>(Op0))
834 if (Instruction *NV = FoldOpIntoPhi(I))
839 // (~A & ~B) == (~(A | B)) - De Morgan's Law
840 if (Value *Op0NotVal = dyn_castNotVal(Op0))
841 if (Value *Op1NotVal = dyn_castNotVal(Op1))
842 if (Op0->hasOneUse() && Op1->hasOneUse()) {
843 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
844 I.getName()+".demorgan");
845 return BinaryOperator::CreateNot(Or);
849 Value *A = 0, *B = 0, *C = 0, *D = 0;
850 // (A|B) & ~(A&B) -> A^B
851 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
852 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
853 ((A == C && B == D) || (A == D && B == C)))
854 return BinaryOperator::CreateXor(A, B);
856 // ~(A&B) & (A|B) -> A^B
857 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
858 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
859 ((A == C && B == D) || (A == D && B == C)))
860 return BinaryOperator::CreateXor(A, B);
862 if (Op0->hasOneUse() &&
863 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
864 if (A == Op1) { // (A^B)&A -> A&(A^B)
865 I.swapOperands(); // Simplify below
867 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
868 cast<BinaryOperator>(Op0)->swapOperands();
869 I.swapOperands(); // Simplify below
874 if (Op1->hasOneUse() &&
875 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
876 if (B == Op0) { // B&(A^B) -> B&(B^A)
877 cast<BinaryOperator>(Op1)->swapOperands();
880 if (A == Op0) // A&(A^B) -> A & ~B
881 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
884 // (A&((~A)|B)) -> A&B
885 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
886 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
887 return BinaryOperator::CreateAnd(A, Op1);
888 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
889 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
890 return BinaryOperator::CreateAnd(A, Op0);
893 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
894 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
895 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
898 // If and'ing two fcmp, try combine them into one.
899 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
900 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
901 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
905 // fold (and (cast A), (cast B)) -> (cast (and A, B))
906 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
907 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
908 const Type *SrcTy = Op0C->getOperand(0)->getType();
909 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
910 SrcTy == Op1C->getOperand(0)->getType() &&
911 SrcTy->isIntOrIntVectorTy()) {
912 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
914 // Only do this if the casts both really cause code to be generated.
915 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
916 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
917 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
918 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
921 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
922 // cast is otherwise not optimizable. This happens for vector sexts.
923 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
924 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
925 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS)) {
926 InsertNewInstBefore(Res, I);
927 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
930 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
931 // cast is otherwise not optimizable. This happens for vector sexts.
932 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
933 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
934 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS)) {
935 InsertNewInstBefore(Res, I);
936 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
941 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
942 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
943 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
944 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
945 SI0->getOperand(1) == SI1->getOperand(1) &&
946 (SI0->hasOneUse() || SI1->hasOneUse())) {
948 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
950 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
955 return Changed ? &I : 0;
958 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
959 /// capable of providing pieces of a bswap. The subexpression provides pieces
960 /// of a bswap if it is proven that each of the non-zero bytes in the output of
961 /// the expression came from the corresponding "byte swapped" byte in some other
962 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
963 /// we know that the expression deposits the low byte of %X into the high byte
964 /// of the bswap result and that all other bytes are zero. This expression is
965 /// accepted, the high byte of ByteValues is set to X to indicate a correct
968 /// This function returns true if the match was unsuccessful and false if so.
969 /// On entry to the function the "OverallLeftShift" is a signed integer value
970 /// indicating the number of bytes that the subexpression is later shifted. For
971 /// example, if the expression is later right shifted by 16 bits, the
972 /// OverallLeftShift value would be -2 on entry. This is used to specify which
973 /// byte of ByteValues is actually being set.
975 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
976 /// byte is masked to zero by a user. For example, in (X & 255), X will be
977 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
978 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
979 /// always in the local (OverallLeftShift) coordinate space.
981 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
982 SmallVector<Value*, 8> &ByteValues) {
983 if (Instruction *I = dyn_cast<Instruction>(V)) {
984 // If this is an or instruction, it may be an inner node of the bswap.
985 if (I->getOpcode() == Instruction::Or) {
986 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
988 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
992 // If this is a logical shift by a constant multiple of 8, recurse with
993 // OverallLeftShift and ByteMask adjusted.
994 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
996 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
997 // Ensure the shift amount is defined and of a byte value.
998 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1001 unsigned ByteShift = ShAmt >> 3;
1002 if (I->getOpcode() == Instruction::Shl) {
1003 // X << 2 -> collect(X, +2)
1004 OverallLeftShift += ByteShift;
1005 ByteMask >>= ByteShift;
1007 // X >>u 2 -> collect(X, -2)
1008 OverallLeftShift -= ByteShift;
1009 ByteMask <<= ByteShift;
1010 ByteMask &= (~0U >> (32-ByteValues.size()));
1013 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1014 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1016 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1020 // If this is a logical 'and' with a mask that clears bytes, clear the
1021 // corresponding bytes in ByteMask.
1022 if (I->getOpcode() == Instruction::And &&
1023 isa<ConstantInt>(I->getOperand(1))) {
1024 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1025 unsigned NumBytes = ByteValues.size();
1026 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1027 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1029 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1030 // If this byte is masked out by a later operation, we don't care what
1032 if ((ByteMask & (1 << i)) == 0)
1035 // If the AndMask is all zeros for this byte, clear the bit.
1036 APInt MaskB = AndMask & Byte;
1038 ByteMask &= ~(1U << i);
1042 // If the AndMask is not all ones for this byte, it's not a bytezap.
1046 // Otherwise, this byte is kept.
1049 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1054 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1055 // the input value to the bswap. Some observations: 1) if more than one byte
1056 // is demanded from this input, then it could not be successfully assembled
1057 // into a byteswap. At least one of the two bytes would not be aligned with
1058 // their ultimate destination.
1059 if (!isPowerOf2_32(ByteMask)) return true;
1060 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1062 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1063 // is demanded, it needs to go into byte 0 of the result. This means that the
1064 // byte needs to be shifted until it lands in the right byte bucket. The
1065 // shift amount depends on the position: if the byte is coming from the high
1066 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1067 // low part, it must be shifted left.
1068 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1069 if (InputByteNo < ByteValues.size()/2) {
1070 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1073 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1077 // If the destination byte value is already defined, the values are or'd
1078 // together, which isn't a bswap (unless it's an or of the same bits).
1079 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1081 ByteValues[DestByteNo] = V;
1085 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1086 /// If so, insert the new bswap intrinsic and return it.
1087 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1088 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1089 if (!ITy || ITy->getBitWidth() % 16 ||
1090 // ByteMask only allows up to 32-byte values.
1091 ITy->getBitWidth() > 32*8)
1092 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1094 /// ByteValues - For each byte of the result, we keep track of which value
1095 /// defines each byte.
1096 SmallVector<Value*, 8> ByteValues;
1097 ByteValues.resize(ITy->getBitWidth()/8);
1099 // Try to find all the pieces corresponding to the bswap.
1100 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1101 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1104 // Check to see if all of the bytes come from the same value.
1105 Value *V = ByteValues[0];
1106 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1108 // Check to make sure that all of the bytes come from the same value.
1109 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1110 if (ByteValues[i] != V)
1112 const Type *Tys[] = { ITy };
1113 Module *M = I.getParent()->getParent()->getParent();
1114 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1115 return CallInst::Create(F, V);
1118 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1119 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1120 /// we can simplify this expression to "cond ? C : D or B".
1121 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1122 Value *C, Value *D) {
1123 // If A is not a select of -1/0, this cannot match.
1125 if (!match(A, m_SExt(m_Value(Cond))) ||
1126 !Cond->getType()->isIntegerTy(1))
1129 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1130 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1131 return SelectInst::Create(Cond, C, B);
1132 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1133 return SelectInst::Create(Cond, C, B);
1135 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1136 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1137 return SelectInst::Create(Cond, C, D);
1138 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1139 return SelectInst::Create(Cond, C, D);
1143 /// FoldOrOfICmps - Fold (icmp)|(icmp) and (cast (icmp))|(cast (icmp)) if
1145 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1146 ICmpInst *LHS, ICmpInst *RHS) {
1147 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1149 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1150 if (PredicatesFoldable(LHSCC, RHSCC)) {
1151 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1152 LHS->getOperand(1) == RHS->getOperand(0))
1153 LHS->swapOperands();
1154 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1155 LHS->getOperand(1) == RHS->getOperand(1)) {
1156 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1157 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1158 bool isSigned = LHS->isSigned() || RHS->isSigned();
1159 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1160 if (Instruction *I = dyn_cast<Instruction>(RV))
1162 // Otherwise, it's a constant boolean value.
1163 return ReplaceInstUsesWith(I, RV);
1167 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1168 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1169 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1170 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1171 if (LHSCst == 0 || RHSCst == 0) return 0;
1173 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1174 if (LHSCst == RHSCst && LHSCC == RHSCC &&
1175 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1176 Value *NewOr = Builder->CreateOr(Val, Val2);
1177 return new ICmpInst(LHSCC, NewOr, LHSCst);
1180 // From here on, we only handle:
1181 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1182 if (Val != Val2) return 0;
1184 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1185 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1186 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1187 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1188 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1191 // We can't fold (ugt x, C) | (sgt x, C2).
1192 if (!PredicatesFoldable(LHSCC, RHSCC))
1195 // Ensure that the larger constant is on the RHS.
1197 if (CmpInst::isSigned(LHSCC) ||
1198 (ICmpInst::isEquality(LHSCC) &&
1199 CmpInst::isSigned(RHSCC)))
1200 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1202 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1205 std::swap(LHS, RHS);
1206 std::swap(LHSCst, RHSCst);
1207 std::swap(LHSCC, RHSCC);
1210 // At this point, we know we have two icmp instructions
1211 // comparing a value against two constants and or'ing the result
1212 // together. Because of the above check, we know that we only have
1213 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1214 // icmp folding check above), that the two constants are not
1216 assert(LHSCst != RHSCst && "Compares not folded above?");
1219 default: llvm_unreachable("Unknown integer condition code!");
1220 case ICmpInst::ICMP_EQ:
1222 default: llvm_unreachable("Unknown integer condition code!");
1223 case ICmpInst::ICMP_EQ:
1224 if (LHSCst == SubOne(RHSCst)) {
1225 // (X == 13 | X == 14) -> X-13 <u 2
1226 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1227 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1228 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1229 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
1231 break; // (X == 13 | X == 15) -> no change
1232 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1233 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1235 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1236 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1237 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1238 return ReplaceInstUsesWith(I, RHS);
1241 case ICmpInst::ICMP_NE:
1243 default: llvm_unreachable("Unknown integer condition code!");
1244 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1245 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1246 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1247 return ReplaceInstUsesWith(I, LHS);
1248 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1249 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1250 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1251 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1254 case ICmpInst::ICMP_ULT:
1256 default: llvm_unreachable("Unknown integer condition code!");
1257 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1259 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1260 // If RHSCst is [us]MAXINT, it is always false. Not handling
1261 // this can cause overflow.
1262 if (RHSCst->isMaxValue(false))
1263 return ReplaceInstUsesWith(I, LHS);
1264 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1266 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1268 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1269 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1270 return ReplaceInstUsesWith(I, RHS);
1271 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1275 case ICmpInst::ICMP_SLT:
1277 default: llvm_unreachable("Unknown integer condition code!");
1278 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1280 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1281 // If RHSCst is [us]MAXINT, it is always false. Not handling
1282 // this can cause overflow.
1283 if (RHSCst->isMaxValue(true))
1284 return ReplaceInstUsesWith(I, LHS);
1285 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1287 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1289 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1290 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1291 return ReplaceInstUsesWith(I, RHS);
1292 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1296 case ICmpInst::ICMP_UGT:
1298 default: llvm_unreachable("Unknown integer condition code!");
1299 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1300 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1301 return ReplaceInstUsesWith(I, LHS);
1302 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1304 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1305 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1306 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1307 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1311 case ICmpInst::ICMP_SGT:
1313 default: llvm_unreachable("Unknown integer condition code!");
1314 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1315 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1316 return ReplaceInstUsesWith(I, LHS);
1317 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1319 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1320 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1321 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1322 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1330 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
1332 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1333 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1334 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1335 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1336 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1337 // If either of the constants are nans, then the whole thing returns
1339 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1340 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1342 // Otherwise, no need to compare the two constants, compare the
1344 return new FCmpInst(FCmpInst::FCMP_UNO,
1345 LHS->getOperand(0), RHS->getOperand(0));
1348 // Handle vector zeros. This occurs because the canonical form of
1349 // "fcmp uno x,x" is "fcmp uno x, 0".
1350 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1351 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1352 return new FCmpInst(FCmpInst::FCMP_UNO,
1353 LHS->getOperand(0), RHS->getOperand(0));
1358 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1359 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1360 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1362 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1363 // Swap RHS operands to match LHS.
1364 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1365 std::swap(Op1LHS, Op1RHS);
1367 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1368 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1370 return new FCmpInst((FCmpInst::Predicate)Op0CC,
1372 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1373 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1374 if (Op0CC == FCmpInst::FCMP_FALSE)
1375 return ReplaceInstUsesWith(I, RHS);
1376 if (Op1CC == FCmpInst::FCMP_FALSE)
1377 return ReplaceInstUsesWith(I, LHS);
1380 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1381 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1382 if (Op0Ordered == Op1Ordered) {
1383 // If both are ordered or unordered, return a new fcmp with
1384 // or'ed predicates.
1385 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
1386 if (Instruction *I = dyn_cast<Instruction>(RV))
1388 // Otherwise, it's a constant boolean value...
1389 return ReplaceInstUsesWith(I, RV);
1395 /// FoldOrWithConstants - This helper function folds:
1397 /// ((A | B) & C1) | (B & C2)
1403 /// when the XOR of the two constants is "all ones" (-1).
1404 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1405 Value *A, Value *B, Value *C) {
1406 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1410 ConstantInt *CI2 = 0;
1411 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1413 APInt Xor = CI1->getValue() ^ CI2->getValue();
1414 if (!Xor.isAllOnesValue()) return 0;
1416 if (V1 == A || V1 == B) {
1417 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1418 return BinaryOperator::CreateOr(NewOp, V1);
1424 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1425 bool Changed = SimplifyCommutative(I);
1426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1428 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1429 return ReplaceInstUsesWith(I, V);
1431 // See if we can simplify any instructions used by the instruction whose sole
1432 // purpose is to compute bits we don't care about.
1433 if (SimplifyDemandedInstructionBits(I))
1436 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1437 ConstantInt *C1 = 0; Value *X = 0;
1438 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1439 // iff (C1 & C2) == 0.
1440 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1441 (RHS->getValue() & C1->getValue()) != 0 &&
1443 Value *Or = Builder->CreateOr(X, RHS);
1445 return BinaryOperator::CreateAnd(Or,
1446 ConstantInt::get(I.getContext(),
1447 RHS->getValue() | C1->getValue()));
1450 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1451 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1453 Value *Or = Builder->CreateOr(X, RHS);
1455 return BinaryOperator::CreateXor(Or,
1456 ConstantInt::get(I.getContext(),
1457 C1->getValue() & ~RHS->getValue()));
1460 // Try to fold constant and into select arguments.
1461 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1462 if (Instruction *R = FoldOpIntoSelect(I, SI))
1465 if (isa<PHINode>(Op0))
1466 if (Instruction *NV = FoldOpIntoPhi(I))
1470 Value *A = 0, *B = 0;
1471 ConstantInt *C1 = 0, *C2 = 0;
1473 // (A | B) | C and A | (B | C) -> bswap if possible.
1474 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1475 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1476 match(Op1, m_Or(m_Value(), m_Value())) ||
1477 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1478 match(Op1, m_Shift(m_Value(), m_Value())))) {
1479 if (Instruction *BSwap = MatchBSwap(I))
1483 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1484 if (Op0->hasOneUse() &&
1485 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1486 MaskedValueIsZero(Op1, C1->getValue())) {
1487 Value *NOr = Builder->CreateOr(A, Op1);
1489 return BinaryOperator::CreateXor(NOr, C1);
1492 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1493 if (Op1->hasOneUse() &&
1494 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1495 MaskedValueIsZero(Op0, C1->getValue())) {
1496 Value *NOr = Builder->CreateOr(A, Op0);
1498 return BinaryOperator::CreateXor(NOr, C1);
1502 Value *C = 0, *D = 0;
1503 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1504 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1505 Value *V1 = 0, *V2 = 0, *V3 = 0;
1506 C1 = dyn_cast<ConstantInt>(C);
1507 C2 = dyn_cast<ConstantInt>(D);
1508 if (C1 && C2) { // (A & C1)|(B & C2)
1509 // If we have: ((V + N) & C1) | (V & C2)
1510 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1511 // replace with V+N.
1512 if (C1->getValue() == ~C2->getValue()) {
1513 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1514 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1515 // Add commutes, try both ways.
1516 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1517 return ReplaceInstUsesWith(I, A);
1518 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1519 return ReplaceInstUsesWith(I, A);
1521 // Or commutes, try both ways.
1522 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1523 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1524 // Add commutes, try both ways.
1525 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1526 return ReplaceInstUsesWith(I, B);
1527 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1528 return ReplaceInstUsesWith(I, B);
1532 if ((C1->getValue() & C2->getValue()) == 0) {
1533 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1534 // iff (C1&C2) == 0 and (N&~C1) == 0
1535 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1536 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1537 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1538 return BinaryOperator::CreateAnd(A,
1539 ConstantInt::get(A->getContext(),
1540 C1->getValue()|C2->getValue()));
1541 // Or commutes, try both ways.
1542 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1543 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1544 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1545 return BinaryOperator::CreateAnd(B,
1546 ConstantInt::get(B->getContext(),
1547 C1->getValue()|C2->getValue()));
1549 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1550 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1551 ConstantInt *C3 = 0, *C4 = 0;
1552 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1553 (C3->getValue() & ~C1->getValue()) == 0 &&
1554 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1555 (C4->getValue() & ~C2->getValue()) == 0) {
1556 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1557 return BinaryOperator::CreateAnd(V2,
1558 ConstantInt::get(B->getContext(),
1559 C1->getValue()|C2->getValue()));
1564 // Check to see if we have any common things being and'ed. If so, find the
1565 // terms for V1 & (V2|V3).
1566 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1568 if (A == B) // (A & C)|(A & D) == A & (C|D)
1569 V1 = A, V2 = C, V3 = D;
1570 else if (A == D) // (A & C)|(B & A) == A & (B|C)
1571 V1 = A, V2 = B, V3 = C;
1572 else if (C == B) // (A & C)|(C & D) == C & (A|D)
1573 V1 = C, V2 = A, V3 = D;
1574 else if (C == D) // (A & C)|(B & C) == C & (A|B)
1575 V1 = C, V2 = A, V3 = B;
1578 Value *Or = Builder->CreateOr(V2, V3, "tmp");
1579 return BinaryOperator::CreateAnd(V1, Or);
1583 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1584 // Don't do this for vector select idioms, the code generator doesn't handle
1586 if (!I.getType()->isVectorTy()) {
1587 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1589 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1591 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1593 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1597 // ((A&~B)|(~A&B)) -> A^B
1598 if ((match(C, m_Not(m_Specific(D))) &&
1599 match(B, m_Not(m_Specific(A)))))
1600 return BinaryOperator::CreateXor(A, D);
1601 // ((~B&A)|(~A&B)) -> A^B
1602 if ((match(A, m_Not(m_Specific(D))) &&
1603 match(B, m_Not(m_Specific(C)))))
1604 return BinaryOperator::CreateXor(C, D);
1605 // ((A&~B)|(B&~A)) -> A^B
1606 if ((match(C, m_Not(m_Specific(B))) &&
1607 match(D, m_Not(m_Specific(A)))))
1608 return BinaryOperator::CreateXor(A, B);
1609 // ((~B&A)|(B&~A)) -> A^B
1610 if ((match(A, m_Not(m_Specific(B))) &&
1611 match(D, m_Not(m_Specific(C)))))
1612 return BinaryOperator::CreateXor(C, B);
1615 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1616 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1617 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1618 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1619 SI0->getOperand(1) == SI1->getOperand(1) &&
1620 (SI0->hasOneUse() || SI1->hasOneUse())) {
1621 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1623 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1624 SI1->getOperand(1));
1628 // ((A|B)&1)|(B&-2) -> (A&1) | B
1629 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1630 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1631 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
1632 if (Ret) return Ret;
1634 // (B&-2)|((A|B)&1) -> (A&1) | B
1635 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1636 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1637 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
1638 if (Ret) return Ret;
1641 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1642 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1643 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1644 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1645 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1646 I.getName()+".demorgan");
1647 return BinaryOperator::CreateNot(And);
1650 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1651 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1652 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
1655 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1656 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1657 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1658 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
1661 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1662 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1663 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1664 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1665 const Type *SrcTy = Op0C->getOperand(0)->getType();
1666 if (SrcTy == Op1C->getOperand(0)->getType() &&
1667 SrcTy->isIntOrIntVectorTy()) {
1668 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1670 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1671 // Only do this if the casts both really cause code to be
1673 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1674 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1675 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1676 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1679 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1680 // cast is otherwise not optimizable. This happens for vector sexts.
1681 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1682 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1683 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS)) {
1684 InsertNewInstBefore(Res, I);
1685 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1688 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1689 // cast is otherwise not optimizable. This happens for vector sexts.
1690 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1691 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1692 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS)) {
1693 InsertNewInstBefore(Res, I);
1694 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1700 return Changed ? &I : 0;
1703 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1704 bool Changed = SimplifyCommutative(I);
1705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1707 if (isa<UndefValue>(Op1)) {
1708 if (isa<UndefValue>(Op0))
1709 // Handle undef ^ undef -> 0 special case. This is a common
1711 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1712 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1717 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1719 // See if we can simplify any instructions used by the instruction whose sole
1720 // purpose is to compute bits we don't care about.
1721 if (SimplifyDemandedInstructionBits(I))
1723 if (I.getType()->isVectorTy())
1724 if (isa<ConstantAggregateZero>(Op1))
1725 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
1727 // Is this a ~ operation?
1728 if (Value *NotOp = dyn_castNotVal(&I)) {
1729 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1730 if (Op0I->getOpcode() == Instruction::And ||
1731 Op0I->getOpcode() == Instruction::Or) {
1732 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1733 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1734 if (dyn_castNotVal(Op0I->getOperand(1)))
1735 Op0I->swapOperands();
1736 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1738 Builder->CreateNot(Op0I->getOperand(1),
1739 Op0I->getOperand(1)->getName()+".not");
1740 if (Op0I->getOpcode() == Instruction::And)
1741 return BinaryOperator::CreateOr(Op0NotVal, NotY);
1742 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1745 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1746 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1747 if (isFreeToInvert(Op0I->getOperand(0)) &&
1748 isFreeToInvert(Op0I->getOperand(1))) {
1750 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1752 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1753 if (Op0I->getOpcode() == Instruction::And)
1754 return BinaryOperator::CreateOr(NotX, NotY);
1755 return BinaryOperator::CreateAnd(NotX, NotY);
1758 } else if (Op0I->getOpcode() == Instruction::AShr) {
1759 // ~(~X >>s Y) --> (X >>s Y)
1760 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
1761 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
1767 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1768 if (RHS->isOne() && Op0->hasOneUse()) {
1769 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
1770 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
1771 return new ICmpInst(ICI->getInversePredicate(),
1772 ICI->getOperand(0), ICI->getOperand(1));
1774 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
1775 return new FCmpInst(FCI->getInversePredicate(),
1776 FCI->getOperand(0), FCI->getOperand(1));
1779 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
1780 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1781 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
1782 if (CI->hasOneUse() && Op0C->hasOneUse()) {
1783 Instruction::CastOps Opcode = Op0C->getOpcode();
1784 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
1785 (RHS == ConstantExpr::getCast(Opcode,
1786 ConstantInt::getTrue(I.getContext()),
1787 Op0C->getDestTy()))) {
1788 CI->setPredicate(CI->getInversePredicate());
1789 return CastInst::Create(Opcode, CI, Op0C->getType());
1795 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1796 // ~(c-X) == X-c-1 == X+(-c-1)
1797 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1798 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1799 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1800 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1801 ConstantInt::get(I.getType(), 1));
1802 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
1805 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1806 if (Op0I->getOpcode() == Instruction::Add) {
1807 // ~(X-c) --> (-c-1)-X
1808 if (RHS->isAllOnesValue()) {
1809 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1810 return BinaryOperator::CreateSub(
1811 ConstantExpr::getSub(NegOp0CI,
1812 ConstantInt::get(I.getType(), 1)),
1813 Op0I->getOperand(0));
1814 } else if (RHS->getValue().isSignBit()) {
1815 // (X + C) ^ signbit -> (X + C + signbit)
1816 Constant *C = ConstantInt::get(I.getContext(),
1817 RHS->getValue() + Op0CI->getValue());
1818 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
1821 } else if (Op0I->getOpcode() == Instruction::Or) {
1822 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
1823 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
1824 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
1825 // Anything in both C1 and C2 is known to be zero, remove it from
1827 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
1828 NewRHS = ConstantExpr::getAnd(NewRHS,
1829 ConstantExpr::getNot(CommonBits));
1831 I.setOperand(0, Op0I->getOperand(0));
1832 I.setOperand(1, NewRHS);
1839 // Try to fold constant and into select arguments.
1840 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1841 if (Instruction *R = FoldOpIntoSelect(I, SI))
1843 if (isa<PHINode>(Op0))
1844 if (Instruction *NV = FoldOpIntoPhi(I))
1848 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1850 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1852 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1854 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1857 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
1860 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
1861 if (A == Op0) { // B^(B|A) == (A|B)^B
1862 Op1I->swapOperands();
1864 std::swap(Op0, Op1);
1865 } else if (B == Op0) { // B^(A|B) == (A|B)^B
1866 I.swapOperands(); // Simplified below.
1867 std::swap(Op0, Op1);
1869 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
1870 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
1871 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
1872 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
1873 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
1875 if (A == Op0) { // A^(A&B) -> A^(B&A)
1876 Op1I->swapOperands();
1879 if (B == Op0) { // A^(B&A) -> (B&A)^A
1880 I.swapOperands(); // Simplified below.
1881 std::swap(Op0, Op1);
1886 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
1889 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1890 Op0I->hasOneUse()) {
1891 if (A == Op1) // (B|A)^B == (A|B)^B
1893 if (B == Op1) // (A|B)^B == A & ~B
1894 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
1895 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
1896 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
1897 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
1898 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
1899 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1901 if (A == Op1) // (A&B)^A -> (B&A)^A
1903 if (B == Op1 && // (B&A)^A == ~B & A
1904 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
1905 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
1910 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
1911 if (Op0I && Op1I && Op0I->isShift() &&
1912 Op0I->getOpcode() == Op1I->getOpcode() &&
1913 Op0I->getOperand(1) == Op1I->getOperand(1) &&
1914 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
1916 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
1918 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
1919 Op1I->getOperand(1));
1923 Value *A, *B, *C, *D;
1924 // (A & B)^(A | B) -> A ^ B
1925 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1926 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
1927 if ((A == C && B == D) || (A == D && B == C))
1928 return BinaryOperator::CreateXor(A, B);
1930 // (A | B)^(A & B) -> A ^ B
1931 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1932 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1933 if ((A == C && B == D) || (A == D && B == C))
1934 return BinaryOperator::CreateXor(A, B);
1938 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
1939 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1940 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1941 // (X & Y)^(X & Y) -> (Y^Z) & X
1942 Value *X = 0, *Y = 0, *Z = 0;
1944 X = A, Y = B, Z = D;
1946 X = A, Y = B, Z = C;
1948 X = B, Y = A, Z = D;
1950 X = B, Y = A, Z = C;
1953 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
1954 return BinaryOperator::CreateAnd(NewOp, X);
1959 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
1960 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1961 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1962 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
1963 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1964 LHS->getOperand(1) == RHS->getOperand(0))
1965 LHS->swapOperands();
1966 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1967 LHS->getOperand(1) == RHS->getOperand(1)) {
1968 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1969 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
1970 bool isSigned = LHS->isSigned() || RHS->isSigned();
1971 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1972 if (Instruction *I = dyn_cast<Instruction>(RV))
1974 // Otherwise, it's a constant boolean value.
1975 return ReplaceInstUsesWith(I, RV);
1979 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
1980 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1981 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1982 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
1983 const Type *SrcTy = Op0C->getOperand(0)->getType();
1984 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
1985 // Only do this if the casts both really cause code to be generated.
1986 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
1988 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
1990 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
1991 Op1C->getOperand(0), I.getName());
1992 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1997 return Changed ? &I : 0;