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/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/ConstantRange.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
21 using namespace PatternMatch;
23 /// isFreeToInvert - Return true if the specified value is free to invert (apply
24 /// ~ to). This happens in cases where the ~ can be eliminated.
25 static inline bool isFreeToInvert(Value *V) {
27 if (BinaryOperator::isNot(V))
30 // Constants can be considered to be not'ed values.
31 if (isa<ConstantInt>(V))
34 // Compares can be inverted if they have a single use.
35 if (CmpInst *CI = dyn_cast<CmpInst>(V))
36 return CI->hasOneUse();
41 static inline Value *dyn_castNotVal(Value *V) {
42 // If this is not(not(x)) don't return that this is a not: we want the two
43 // not's to be folded first.
44 if (BinaryOperator::isNot(V)) {
45 Value *Operand = BinaryOperator::getNotArgument(V);
46 if (!isFreeToInvert(Operand))
50 // Constants can be considered to be not'ed values...
51 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
52 return ConstantInt::get(C->getType(), ~C->getValue());
56 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
57 /// predicate into a three bit mask. It also returns whether it is an ordered
58 /// predicate by reference.
59 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
62 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
63 case FCmpInst::FCMP_UNO: return 0; // 000
64 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
65 case FCmpInst::FCMP_UGT: return 1; // 001
66 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
67 case FCmpInst::FCMP_UEQ: return 2; // 010
68 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
69 case FCmpInst::FCMP_UGE: return 3; // 011
70 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
71 case FCmpInst::FCMP_ULT: return 4; // 100
72 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
73 case FCmpInst::FCMP_UNE: return 5; // 101
74 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
75 case FCmpInst::FCMP_ULE: return 6; // 110
78 // Not expecting FCMP_FALSE and FCMP_TRUE;
79 llvm_unreachable("Unexpected FCmp predicate!");
83 /// getNewICmpValue - This is the complement of getICmpCode, which turns an
84 /// opcode and two operands into either a constant true or false, or a brand
85 /// new ICmp instruction. The sign is passed in to determine which kind
86 /// of predicate to use in the new icmp instruction.
87 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
88 InstCombiner::BuilderTy *Builder) {
89 ICmpInst::Predicate NewPred;
90 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
92 return Builder->CreateICmp(NewPred, LHS, RHS);
95 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
96 /// opcode and two operands into either a FCmp instruction. isordered is passed
97 /// in to determine which kind of predicate to use in the new fcmp instruction.
98 static Value *getFCmpValue(bool isordered, unsigned code,
99 Value *LHS, Value *RHS,
100 InstCombiner::BuilderTy *Builder) {
101 CmpInst::Predicate Pred;
103 default: llvm_unreachable("Illegal FCmp code!");
104 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
105 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
106 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
107 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
108 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
109 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
110 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
112 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
113 Pred = FCmpInst::FCMP_ORD; break;
115 return Builder->CreateFCmp(Pred, LHS, RHS);
118 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
119 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
120 // guaranteed to be a binary operator.
121 Instruction *InstCombiner::OptAndOp(Instruction *Op,
124 BinaryOperator &TheAnd) {
125 Value *X = Op->getOperand(0);
126 Constant *Together = 0;
128 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
130 switch (Op->getOpcode()) {
131 case Instruction::Xor:
132 if (Op->hasOneUse()) {
133 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
134 Value *And = Builder->CreateAnd(X, AndRHS);
136 return BinaryOperator::CreateXor(And, Together);
139 case Instruction::Or:
140 if (Op->hasOneUse()){
141 if (Together != OpRHS) {
142 // (X | C1) & C2 --> (X | (C1&C2)) & C2
143 Value *Or = Builder->CreateOr(X, Together);
145 return BinaryOperator::CreateAnd(Or, AndRHS);
148 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
149 if (TogetherCI && !TogetherCI->isZero()){
150 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
151 // NOTE: This reduces the number of bits set in the & mask, which
152 // can expose opportunities for store narrowing.
153 Together = ConstantExpr::getXor(AndRHS, Together);
154 Value *And = Builder->CreateAnd(X, Together);
156 return BinaryOperator::CreateOr(And, OpRHS);
161 case Instruction::Add:
162 if (Op->hasOneUse()) {
163 // Adding a one to a single bit bit-field should be turned into an XOR
164 // of the bit. First thing to check is to see if this AND is with a
165 // single bit constant.
166 const APInt &AndRHSV = AndRHS->getValue();
168 // If there is only one bit set.
169 if (AndRHSV.isPowerOf2()) {
170 // Ok, at this point, we know that we are masking the result of the
171 // ADD down to exactly one bit. If the constant we are adding has
172 // no bits set below this bit, then we can eliminate the ADD.
173 const APInt& AddRHS = OpRHS->getValue();
175 // Check to see if any bits below the one bit set in AndRHSV are set.
176 if ((AddRHS & (AndRHSV-1)) == 0) {
177 // If not, the only thing that can effect the output of the AND is
178 // the bit specified by AndRHSV. If that bit is set, the effect of
179 // the XOR is to toggle the bit. If it is clear, then the ADD has
181 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
182 TheAnd.setOperand(0, X);
185 // Pull the XOR out of the AND.
186 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
187 NewAnd->takeName(Op);
188 return BinaryOperator::CreateXor(NewAnd, AndRHS);
195 case Instruction::Shl: {
196 // We know that the AND will not produce any of the bits shifted in, so if
197 // the anded constant includes them, clear them now!
199 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
200 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
201 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
202 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
204 if (CI->getValue() == ShlMask)
205 // Masking out bits that the shift already masks.
206 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
208 if (CI != AndRHS) { // Reducing bits set in and.
209 TheAnd.setOperand(1, CI);
214 case Instruction::LShr: {
215 // We know that the AND will not produce any of the bits shifted in, so if
216 // the anded constant includes them, clear them now! This only applies to
217 // unsigned shifts, because a signed shr may bring in set bits!
219 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
220 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
221 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
222 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
224 if (CI->getValue() == ShrMask)
225 // Masking out bits that the shift already masks.
226 return ReplaceInstUsesWith(TheAnd, Op);
229 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
234 case Instruction::AShr:
236 // See if this is shifting in some sign extension, then masking it out
238 if (Op->hasOneUse()) {
239 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
240 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
241 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
242 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
243 if (C == AndRHS) { // Masking out bits shifted in.
244 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
245 // Make the argument unsigned.
246 Value *ShVal = Op->getOperand(0);
247 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
248 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
256 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
257 /// (V < Lo || V >= Hi). In practice, we emit the more efficient
258 /// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
259 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
260 /// insert new instructions.
261 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
262 bool isSigned, bool Inside) {
263 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
264 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
265 "Lo is not <= Hi in range emission code!");
268 if (Lo == Hi) // Trivially false.
269 return Builder->getFalse();
271 // V >= Min && V < Hi --> V < Hi
272 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
273 ICmpInst::Predicate pred = (isSigned ?
274 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
275 return Builder->CreateICmp(pred, V, Hi);
278 // Emit V-Lo <u Hi-Lo
279 Constant *NegLo = ConstantExpr::getNeg(Lo);
280 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
281 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
282 return Builder->CreateICmpULT(Add, UpperBound);
285 if (Lo == Hi) // Trivially true.
286 return Builder->getTrue();
288 // V < Min || V >= Hi -> V > Hi-1
289 Hi = SubOne(cast<ConstantInt>(Hi));
290 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
291 ICmpInst::Predicate pred = (isSigned ?
292 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
293 return Builder->CreateICmp(pred, V, Hi);
296 // Emit V-Lo >u Hi-1-Lo
297 // Note that Hi has already had one subtracted from it, above.
298 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
299 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
300 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
301 return Builder->CreateICmpUGT(Add, LowerBound);
304 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
305 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
306 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
307 // not, since all 1s are not contiguous.
308 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
309 const APInt& V = Val->getValue();
310 uint32_t BitWidth = Val->getType()->getBitWidth();
311 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
313 // look for the first zero bit after the run of ones
314 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
315 // look for the first non-zero bit
316 ME = V.getActiveBits();
320 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
321 /// where isSub determines whether the operator is a sub. If we can fold one of
322 /// the following xforms:
324 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
325 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
326 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
328 /// return (A +/- B).
330 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
331 ConstantInt *Mask, bool isSub,
333 Instruction *LHSI = dyn_cast<Instruction>(LHS);
334 if (!LHSI || LHSI->getNumOperands() != 2 ||
335 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
337 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
339 switch (LHSI->getOpcode()) {
341 case Instruction::And:
342 if (ConstantExpr::getAnd(N, Mask) == Mask) {
343 // If the AndRHS is a power of two minus one (0+1+), this is simple.
344 if ((Mask->getValue().countLeadingZeros() +
345 Mask->getValue().countPopulation()) ==
346 Mask->getValue().getBitWidth())
349 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
350 // part, we don't need any explicit masks to take them out of A. If that
351 // is all N is, ignore it.
352 uint32_t MB = 0, ME = 0;
353 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
354 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
355 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
356 if (MaskedValueIsZero(RHS, Mask))
361 case Instruction::Or:
362 case Instruction::Xor:
363 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
364 if ((Mask->getValue().countLeadingZeros() +
365 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
366 && ConstantExpr::getAnd(N, Mask)->isNullValue())
372 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
373 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
376 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
377 /// One of A and B is considered the mask, the other the value. This is
378 /// described as the "AMask" or "BMask" part of the enum. If the enum
379 /// contains only "Mask", then both A and B can be considered masks.
380 /// If A is the mask, then it was proven, that (A & C) == C. This
381 /// is trivial if C == A, or C == 0. If both A and C are constants, this
382 /// proof is also easy.
383 /// For the following explanations we assume that A is the mask.
384 /// The part "AllOnes" declares, that the comparison is true only
385 /// if (A & B) == A, or all bits of A are set in B.
386 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
387 /// The part "AllZeroes" declares, that the comparison is true only
388 /// if (A & B) == 0, or all bits of A are cleared in B.
389 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
390 /// The part "Mixed" declares, that (A & B) == C and C might or might not
391 /// contain any number of one bits and zero bits.
392 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
393 /// The Part "Not" means, that in above descriptions "==" should be replaced
395 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
396 /// If the mask A contains a single bit, then the following is equivalent:
397 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
398 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
399 enum MaskedICmpType {
400 FoldMskICmp_AMask_AllOnes = 1,
401 FoldMskICmp_AMask_NotAllOnes = 2,
402 FoldMskICmp_BMask_AllOnes = 4,
403 FoldMskICmp_BMask_NotAllOnes = 8,
404 FoldMskICmp_Mask_AllZeroes = 16,
405 FoldMskICmp_Mask_NotAllZeroes = 32,
406 FoldMskICmp_AMask_Mixed = 64,
407 FoldMskICmp_AMask_NotMixed = 128,
408 FoldMskICmp_BMask_Mixed = 256,
409 FoldMskICmp_BMask_NotMixed = 512
412 /// return the set of pattern classes (from MaskedICmpType)
413 /// that (icmp SCC (A & B), C) satisfies
414 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
415 ICmpInst::Predicate SCC)
417 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
418 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
419 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
420 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
421 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
422 ACst->getValue().isPowerOf2());
423 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
424 BCst->getValue().isPowerOf2());
426 if (CCst != 0 && CCst->isZero()) {
427 // if C is zero, then both A and B qualify as mask
428 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
429 FoldMskICmp_Mask_AllZeroes |
430 FoldMskICmp_AMask_Mixed |
431 FoldMskICmp_BMask_Mixed)
432 : (FoldMskICmp_Mask_NotAllZeroes |
433 FoldMskICmp_Mask_NotAllZeroes |
434 FoldMskICmp_AMask_NotMixed |
435 FoldMskICmp_BMask_NotMixed));
437 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
438 FoldMskICmp_AMask_NotMixed)
439 : (FoldMskICmp_AMask_AllOnes |
440 FoldMskICmp_AMask_Mixed));
442 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
443 FoldMskICmp_BMask_NotMixed)
444 : (FoldMskICmp_BMask_AllOnes |
445 FoldMskICmp_BMask_Mixed));
449 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
450 FoldMskICmp_AMask_Mixed)
451 : (FoldMskICmp_AMask_NotAllOnes |
452 FoldMskICmp_AMask_NotMixed));
454 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
455 FoldMskICmp_AMask_NotMixed)
456 : (FoldMskICmp_Mask_AllZeroes |
457 FoldMskICmp_AMask_Mixed));
458 } else if (ACst != 0 && CCst != 0 &&
459 ConstantExpr::getAnd(ACst, CCst) == CCst) {
460 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
461 : FoldMskICmp_AMask_NotMixed);
464 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
465 FoldMskICmp_BMask_Mixed)
466 : (FoldMskICmp_BMask_NotAllOnes |
467 FoldMskICmp_BMask_NotMixed));
469 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
470 FoldMskICmp_BMask_NotMixed)
471 : (FoldMskICmp_Mask_AllZeroes |
472 FoldMskICmp_BMask_Mixed));
473 } else if (BCst != 0 && CCst != 0 &&
474 ConstantExpr::getAnd(BCst, CCst) == CCst) {
475 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
476 : FoldMskICmp_BMask_NotMixed);
481 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
482 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
483 /// is adjacent to the corresponding normal flag (recording ==), this just
484 /// involves swapping those bits over.
485 static unsigned conjugateICmpMask(unsigned Mask) {
487 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
488 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
489 FoldMskICmp_BMask_Mixed))
493 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
494 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
495 FoldMskICmp_BMask_NotMixed))
501 /// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
502 /// if possible. The returned predicate is either == or !=. Returns false if
503 /// decomposition fails.
504 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
505 Value *&X, Value *&Y, Value *&Z) {
506 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
510 switch (I->getPredicate()) {
513 case ICmpInst::ICMP_SLT:
514 // X < 0 is equivalent to (X & SignBit) != 0.
517 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
518 Pred = ICmpInst::ICMP_NE;
520 case ICmpInst::ICMP_SGT:
521 // X > -1 is equivalent to (X & SignBit) == 0.
522 if (!C->isAllOnesValue())
524 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
525 Pred = ICmpInst::ICMP_EQ;
527 case ICmpInst::ICMP_ULT:
528 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
529 if (!C->getValue().isPowerOf2())
531 Y = ConstantInt::get(I->getContext(), -C->getValue());
532 Pred = ICmpInst::ICMP_EQ;
534 case ICmpInst::ICMP_UGT:
535 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
536 if (!(C->getValue() + 1).isPowerOf2())
538 Y = ConstantInt::get(I->getContext(), ~C->getValue());
539 Pred = ICmpInst::ICMP_NE;
543 X = I->getOperand(0);
544 Z = ConstantInt::getNullValue(C->getType());
548 /// foldLogOpOfMaskedICmpsHelper:
549 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
550 /// return the set of pattern classes (from MaskedICmpType)
551 /// that both LHS and RHS satisfy
552 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
553 Value*& B, Value*& C,
554 Value*& D, Value*& E,
555 ICmpInst *LHS, ICmpInst *RHS,
556 ICmpInst::Predicate &LHSCC,
557 ICmpInst::Predicate &RHSCC) {
558 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
559 // vectors are not (yet?) supported
560 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
562 // Here comes the tricky part:
563 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
564 // and L11 & L12 == L21 & L22. The same goes for RHS.
565 // Now we must find those components L** and R**, that are equal, so
566 // that we can extract the parameters A, B, C, D, and E for the canonical
568 Value *L1 = LHS->getOperand(0);
569 Value *L2 = LHS->getOperand(1);
570 Value *L11,*L12,*L21,*L22;
571 // Check whether the icmp can be decomposed into a bit test.
572 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
575 // Look for ANDs in the LHS icmp.
576 if (!L1->getType()->isIntegerTy()) {
577 // You can icmp pointers, for example. They really aren't masks.
579 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
580 // Any icmp can be viewed as being trivially masked; if it allows us to
581 // remove one, it's worth it.
583 L12 = Constant::getAllOnesValue(L1->getType());
586 if (!L2->getType()->isIntegerTy()) {
587 // You can icmp pointers, for example. They really aren't masks.
589 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
591 L22 = Constant::getAllOnesValue(L2->getType());
595 // Bail if LHS was a icmp that can't be decomposed into an equality.
596 if (!ICmpInst::isEquality(LHSCC))
599 Value *R1 = RHS->getOperand(0);
600 Value *R2 = RHS->getOperand(1);
603 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
604 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
606 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
611 E = R2; R1 = 0; ok = true;
612 } else if (R1->getType()->isIntegerTy()) {
613 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
614 // As before, model no mask as a trivial mask if it'll let us do an
617 R12 = Constant::getAllOnesValue(R1->getType());
620 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
621 A = R11; D = R12; E = R2; ok = true;
622 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
623 A = R12; D = R11; E = R2; ok = true;
627 // Bail if RHS was a icmp that can't be decomposed into an equality.
628 if (!ICmpInst::isEquality(RHSCC))
631 // Look for ANDs in on the right side of the RHS icmp.
632 if (!ok && R2->getType()->isIntegerTy()) {
633 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
635 R12 = Constant::getAllOnesValue(R2->getType());
638 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
639 A = R11; D = R12; E = R1; ok = true;
640 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
641 A = R12; D = R11; E = R1; ok = true;
651 } else if (L12 == A) {
653 } else if (L21 == A) {
655 } else if (L22 == A) {
659 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
660 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
661 return left_type & right_type;
663 /// foldLogOpOfMaskedICmps:
664 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
665 /// into a single (icmp(A & X) ==/!= Y)
666 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
667 llvm::InstCombiner::BuilderTy* Builder) {
668 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
669 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
670 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
672 if (mask == 0) return 0;
673 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
674 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
676 // In full generality:
677 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
678 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
680 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
681 // equivalent to (icmp (A & X) !Op Y).
683 // Therefore, we can pretend for the rest of this function that we're dealing
684 // with the conjunction, provided we flip the sense of any comparisons (both
685 // input and output).
687 // In most cases we're going to produce an EQ for the "&&" case.
688 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
690 // Convert the masking analysis into its equivalent with negated
692 mask = conjugateICmpMask(mask);
695 if (mask & FoldMskICmp_Mask_AllZeroes) {
696 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
697 // -> (icmp eq (A & (B|D)), 0)
698 Value* newOr = Builder->CreateOr(B, D);
699 Value* newAnd = Builder->CreateAnd(A, newOr);
700 // we can't use C as zero, because we might actually handle
701 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
702 // with B and D, having a single bit set
703 Value* zero = Constant::getNullValue(A->getType());
704 return Builder->CreateICmp(NEWCC, newAnd, zero);
706 if (mask & FoldMskICmp_BMask_AllOnes) {
707 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
708 // -> (icmp eq (A & (B|D)), (B|D))
709 Value* newOr = Builder->CreateOr(B, D);
710 Value* newAnd = Builder->CreateAnd(A, newOr);
711 return Builder->CreateICmp(NEWCC, newAnd, newOr);
713 if (mask & FoldMskICmp_AMask_AllOnes) {
714 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
715 // -> (icmp eq (A & (B&D)), A)
716 Value* newAnd1 = Builder->CreateAnd(B, D);
717 Value* newAnd = Builder->CreateAnd(A, newAnd1);
718 return Builder->CreateICmp(NEWCC, newAnd, A);
721 // Remaining cases assume at least that B and D are constant, and depend on
722 // their actual values. This isn't strictly, necessary, just a "handle the
723 // easy cases for now" decision.
724 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
725 if (BCst == 0) return 0;
726 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
727 if (DCst == 0) return 0;
729 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
730 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
731 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
732 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
733 // Only valid if one of the masks is a superset of the other (check "B&D" is
734 // the same as either B or D).
735 APInt NewMask = BCst->getValue() & DCst->getValue();
737 if (NewMask == BCst->getValue())
739 else if (NewMask == DCst->getValue())
742 if (mask & FoldMskICmp_AMask_NotAllOnes) {
743 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
744 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
745 // Only valid if one of the masks is a superset of the other (check "B|D" is
746 // the same as either B or D).
747 APInt NewMask = BCst->getValue() | DCst->getValue();
749 if (NewMask == BCst->getValue())
751 else if (NewMask == DCst->getValue())
754 if (mask & FoldMskICmp_BMask_Mixed) {
755 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
756 // We already know that B & C == C && D & E == E.
757 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
758 // C and E, which are shared by both the mask B and the mask D, don't
759 // contradict, then we can transform to
760 // -> (icmp eq (A & (B|D)), (C|E))
761 // Currently, we only handle the case of B, C, D, and E being constant.
762 // we can't simply use C and E, because we might actually handle
763 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
764 // with B and D, having a single bit set
765 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
766 if (CCst == 0) return 0;
768 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
769 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
770 if (ECst == 0) return 0;
772 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
773 ConstantInt* MCst = dyn_cast<ConstantInt>(
774 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
775 ConstantExpr::getXor(CCst, ECst)) );
776 // if there is a conflict we should actually return a false for the
780 Value *newOr1 = Builder->CreateOr(B, D);
781 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
782 Value *newAnd = Builder->CreateAnd(A, newOr1);
783 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
788 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
789 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
790 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
792 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
793 if (PredicatesFoldable(LHSCC, RHSCC)) {
794 if (LHS->getOperand(0) == RHS->getOperand(1) &&
795 LHS->getOperand(1) == RHS->getOperand(0))
797 if (LHS->getOperand(0) == RHS->getOperand(0) &&
798 LHS->getOperand(1) == RHS->getOperand(1)) {
799 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
800 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
801 bool isSigned = LHS->isSigned() || RHS->isSigned();
802 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
806 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
807 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
810 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
811 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
812 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
813 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
814 if (LHSCst == 0 || RHSCst == 0) return 0;
816 if (LHSCst == RHSCst && LHSCC == RHSCC) {
817 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
818 // where C is a power of 2
819 if (LHSCC == ICmpInst::ICMP_ULT &&
820 LHSCst->getValue().isPowerOf2()) {
821 Value *NewOr = Builder->CreateOr(Val, Val2);
822 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
825 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
826 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
827 Value *NewOr = Builder->CreateOr(Val, Val2);
828 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
832 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
833 // where CMAX is the all ones value for the truncated type,
834 // iff the lower bits of C2 and CA are zero.
835 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
836 LHS->hasOneUse() && RHS->hasOneUse()) {
838 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
840 // (trunc x) == C1 & (and x, CA) == C2
841 // (and x, CA) == C2 & (trunc x) == C1
842 if (match(Val2, m_Trunc(m_Value(V))) &&
843 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
846 } else if (match(Val, m_Trunc(m_Value(V))) &&
847 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
852 if (SmallCst && BigCst) {
853 unsigned BigBitSize = BigCst->getType()->getBitWidth();
854 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
856 // Check that the low bits are zero.
857 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
858 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
859 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
860 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
861 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
862 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
867 // From here on, we only handle:
868 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
869 if (Val != Val2) return 0;
871 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
872 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
873 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
874 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
875 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
878 // Make a constant range that's the intersection of the two icmp ranges.
879 // If the intersection is empty, we know that the result is false.
880 ConstantRange LHSRange =
881 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
882 ConstantRange RHSRange =
883 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
885 if (LHSRange.intersectWith(RHSRange).isEmptySet())
886 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
888 // We can't fold (ugt x, C) & (sgt x, C2).
889 if (!PredicatesFoldable(LHSCC, RHSCC))
892 // Ensure that the larger constant is on the RHS.
894 if (CmpInst::isSigned(LHSCC) ||
895 (ICmpInst::isEquality(LHSCC) &&
896 CmpInst::isSigned(RHSCC)))
897 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
899 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
903 std::swap(LHSCst, RHSCst);
904 std::swap(LHSCC, RHSCC);
907 // At this point, we know we have two icmp instructions
908 // comparing a value against two constants and and'ing the result
909 // together. Because of the above check, we know that we only have
910 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
911 // (from the icmp folding check above), that the two constants
912 // are not equal and that the larger constant is on the RHS
913 assert(LHSCst != RHSCst && "Compares not folded above?");
916 default: llvm_unreachable("Unknown integer condition code!");
917 case ICmpInst::ICMP_EQ:
919 default: llvm_unreachable("Unknown integer condition code!");
920 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
921 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
922 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
925 case ICmpInst::ICMP_NE:
927 default: llvm_unreachable("Unknown integer condition code!");
928 case ICmpInst::ICMP_ULT:
929 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
930 return Builder->CreateICmpULT(Val, LHSCst);
931 break; // (X != 13 & X u< 15) -> no change
932 case ICmpInst::ICMP_SLT:
933 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
934 return Builder->CreateICmpSLT(Val, LHSCst);
935 break; // (X != 13 & X s< 15) -> no change
936 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
937 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
938 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
940 case ICmpInst::ICMP_NE:
941 // Special case to get the ordering right when the values wrap around
943 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
944 std::swap(LHSCst, RHSCst);
945 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
946 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
947 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
948 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
949 Val->getName()+".cmp");
951 break; // (X != 13 & X != 15) -> no change
954 case ICmpInst::ICMP_ULT:
956 default: llvm_unreachable("Unknown integer condition code!");
957 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
958 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
959 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
960 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
962 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
963 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
965 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
969 case ICmpInst::ICMP_SLT:
971 default: llvm_unreachable("Unknown integer condition code!");
972 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
974 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
975 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
977 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
981 case ICmpInst::ICMP_UGT:
983 default: llvm_unreachable("Unknown integer condition code!");
984 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
985 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
987 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
989 case ICmpInst::ICMP_NE:
990 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
991 return Builder->CreateICmp(LHSCC, Val, RHSCst);
992 break; // (X u> 13 & X != 15) -> no change
993 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
994 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
995 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
999 case ICmpInst::ICMP_SGT:
1001 default: llvm_unreachable("Unknown integer condition code!");
1002 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1003 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1005 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1007 case ICmpInst::ICMP_NE:
1008 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1009 return Builder->CreateICmp(LHSCC, Val, RHSCst);
1010 break; // (X s> 13 & X != 15) -> no change
1011 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
1012 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1013 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1022 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1023 /// instcombine, this returns a Value which should already be inserted into the
1025 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1026 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1027 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1028 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1031 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1032 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1033 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1034 // If either of the constants are nans, then the whole thing returns
1036 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1037 return Builder->getFalse();
1038 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1041 // Handle vector zeros. This occurs because the canonical form of
1042 // "fcmp ord x,x" is "fcmp ord x, 0".
1043 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1044 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1045 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1049 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1050 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1051 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1054 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1055 // Swap RHS operands to match LHS.
1056 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1057 std::swap(Op1LHS, Op1RHS);
1060 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1061 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1063 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1064 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1065 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1066 if (Op0CC == FCmpInst::FCMP_TRUE)
1068 if (Op1CC == FCmpInst::FCMP_TRUE)
1073 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1074 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1075 // uno && ord -> false
1076 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1077 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1079 std::swap(LHS, RHS);
1080 std::swap(Op0Pred, Op1Pred);
1081 std::swap(Op0Ordered, Op1Ordered);
1084 // uno && ueq -> uno && (uno || eq) -> uno
1085 // ord && olt -> ord && (ord && lt) -> olt
1086 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1088 if (Op0Ordered && (Op0Ordered == Op1Ordered))
1091 // uno && oeq -> uno && (ord && eq) -> false
1093 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1094 // ord && ueq -> ord && (uno || eq) -> oeq
1095 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1103 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1104 bool Changed = SimplifyAssociativeOrCommutative(I);
1105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1107 if (Value *V = SimplifyAndInst(Op0, Op1, DL))
1108 return ReplaceInstUsesWith(I, V);
1110 // (A|B)&(A|C) -> A|(B&C) etc
1111 if (Value *V = SimplifyUsingDistributiveLaws(I))
1112 return ReplaceInstUsesWith(I, V);
1114 // See if we can simplify any instructions used by the instruction whose sole
1115 // purpose is to compute bits we don't care about.
1116 if (SimplifyDemandedInstructionBits(I))
1119 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1120 const APInt &AndRHSMask = AndRHS->getValue();
1122 // Optimize a variety of ((val OP C1) & C2) combinations...
1123 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1124 Value *Op0LHS = Op0I->getOperand(0);
1125 Value *Op0RHS = Op0I->getOperand(1);
1126 switch (Op0I->getOpcode()) {
1128 case Instruction::Xor:
1129 case Instruction::Or: {
1130 // If the mask is only needed on one incoming arm, push it up.
1131 if (!Op0I->hasOneUse()) break;
1133 APInt NotAndRHS(~AndRHSMask);
1134 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1135 // Not masking anything out for the LHS, move to RHS.
1136 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1137 Op0RHS->getName()+".masked");
1138 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1140 if (!isa<Constant>(Op0RHS) &&
1141 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1142 // Not masking anything out for the RHS, move to LHS.
1143 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1144 Op0LHS->getName()+".masked");
1145 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1150 case Instruction::Add:
1151 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1152 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1153 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1154 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1155 return BinaryOperator::CreateAnd(V, AndRHS);
1156 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1157 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1160 case Instruction::Sub:
1161 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1162 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1163 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1164 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1165 return BinaryOperator::CreateAnd(V, AndRHS);
1167 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1168 // has 1's for all bits that the subtraction with A might affect.
1169 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1170 uint32_t BitWidth = AndRHSMask.getBitWidth();
1171 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1172 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1174 if (MaskedValueIsZero(Op0LHS, Mask)) {
1175 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1176 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1181 case Instruction::Shl:
1182 case Instruction::LShr:
1183 // (1 << x) & 1 --> zext(x == 0)
1184 // (1 >> x) & 1 --> zext(x == 0)
1185 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1187 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1188 return new ZExtInst(NewICmp, I.getType());
1193 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1194 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1198 // If this is an integer truncation, and if the source is an 'and' with
1199 // immediate, transform it. This frequently occurs for bitfield accesses.
1201 Value *X = 0; ConstantInt *YC = 0;
1202 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1203 // Change: and (trunc (and X, YC) to T), C2
1204 // into : and (trunc X to T), trunc(YC) & C2
1205 // This will fold the two constants together, which may allow
1206 // other simplifications.
1207 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1208 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1209 C3 = ConstantExpr::getAnd(C3, AndRHS);
1210 return BinaryOperator::CreateAnd(NewCast, C3);
1214 // Try to fold constant and into select arguments.
1215 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1216 if (Instruction *R = FoldOpIntoSelect(I, SI))
1218 if (isa<PHINode>(Op0))
1219 if (Instruction *NV = FoldOpIntoPhi(I))
1224 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1225 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1226 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1227 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1228 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1229 I.getName()+".demorgan");
1230 return BinaryOperator::CreateNot(Or);
1234 Value *A = 0, *B = 0, *C = 0, *D = 0;
1235 // (A|B) & ~(A&B) -> A^B
1236 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1237 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1238 ((A == C && B == D) || (A == D && B == C)))
1239 return BinaryOperator::CreateXor(A, B);
1241 // ~(A&B) & (A|B) -> A^B
1242 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1243 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1244 ((A == C && B == D) || (A == D && B == C)))
1245 return BinaryOperator::CreateXor(A, B);
1247 // A&(A^B) => A & ~B
1249 Value *tmpOp0 = Op0;
1250 Value *tmpOp1 = Op1;
1251 if (Op0->hasOneUse() &&
1252 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1253 if (A == Op1 || B == Op1 ) {
1260 if (tmpOp1->hasOneUse() &&
1261 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1265 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1266 // A is originally -1 (or a vector of -1 and undefs), then we enter
1267 // an endless loop. By checking that A is non-constant we ensure that
1268 // we will never get to the loop.
1269 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1270 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1274 // (A&((~A)|B)) -> A&B
1275 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1276 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1277 return BinaryOperator::CreateAnd(A, Op1);
1278 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1279 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1280 return BinaryOperator::CreateAnd(A, Op0);
1283 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1284 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1285 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1286 return ReplaceInstUsesWith(I, Res);
1288 // If and'ing two fcmp, try combine them into one.
1289 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1290 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1291 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1292 return ReplaceInstUsesWith(I, Res);
1295 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1296 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1297 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1298 Type *SrcTy = Op0C->getOperand(0)->getType();
1299 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1300 SrcTy == Op1C->getOperand(0)->getType() &&
1301 SrcTy->isIntOrIntVectorTy()) {
1302 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1304 // Only do this if the casts both really cause code to be generated.
1305 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1306 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1307 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1308 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1311 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1312 // cast is otherwise not optimizable. This happens for vector sexts.
1313 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1314 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1315 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1316 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1318 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1319 // cast is otherwise not optimizable. This happens for vector sexts.
1320 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1321 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1322 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1323 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1327 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1328 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1329 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1330 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1331 SI0->getOperand(1) == SI1->getOperand(1) &&
1332 (SI0->hasOneUse() || SI1->hasOneUse())) {
1334 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1336 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1337 SI1->getOperand(1));
1343 bool OpsSwapped = false;
1344 // Canonicalize SExt or Not to the LHS
1345 if (match(Op1, m_SExt(m_Value())) ||
1346 match(Op1, m_Not(m_Value()))) {
1347 std::swap(Op0, Op1);
1351 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1352 if (match(Op0, m_SExt(m_Value(X))) &&
1353 X->getType()->getScalarType()->isIntegerTy(1)) {
1354 Value *Zero = Constant::getNullValue(Op1->getType());
1355 return SelectInst::Create(X, Op1, Zero);
1358 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1359 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1360 X->getType()->getScalarType()->isIntegerTy(1)) {
1361 Value *Zero = Constant::getNullValue(Op0->getType());
1362 return SelectInst::Create(X, Zero, Op1);
1366 std::swap(Op0, Op1);
1369 return Changed ? &I : 0;
1372 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1373 /// capable of providing pieces of a bswap. The subexpression provides pieces
1374 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1375 /// the expression came from the corresponding "byte swapped" byte in some other
1376 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1377 /// we know that the expression deposits the low byte of %X into the high byte
1378 /// of the bswap result and that all other bytes are zero. This expression is
1379 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1382 /// This function returns true if the match was unsuccessful and false if so.
1383 /// On entry to the function the "OverallLeftShift" is a signed integer value
1384 /// indicating the number of bytes that the subexpression is later shifted. For
1385 /// example, if the expression is later right shifted by 16 bits, the
1386 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1387 /// byte of ByteValues is actually being set.
1389 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1390 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1391 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1392 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1393 /// always in the local (OverallLeftShift) coordinate space.
1395 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1396 SmallVectorImpl<Value *> &ByteValues) {
1397 if (Instruction *I = dyn_cast<Instruction>(V)) {
1398 // If this is an or instruction, it may be an inner node of the bswap.
1399 if (I->getOpcode() == Instruction::Or) {
1400 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1402 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1406 // If this is a logical shift by a constant multiple of 8, recurse with
1407 // OverallLeftShift and ByteMask adjusted.
1408 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1410 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1411 // Ensure the shift amount is defined and of a byte value.
1412 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1415 unsigned ByteShift = ShAmt >> 3;
1416 if (I->getOpcode() == Instruction::Shl) {
1417 // X << 2 -> collect(X, +2)
1418 OverallLeftShift += ByteShift;
1419 ByteMask >>= ByteShift;
1421 // X >>u 2 -> collect(X, -2)
1422 OverallLeftShift -= ByteShift;
1423 ByteMask <<= ByteShift;
1424 ByteMask &= (~0U >> (32-ByteValues.size()));
1427 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1428 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1430 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1434 // If this is a logical 'and' with a mask that clears bytes, clear the
1435 // corresponding bytes in ByteMask.
1436 if (I->getOpcode() == Instruction::And &&
1437 isa<ConstantInt>(I->getOperand(1))) {
1438 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1439 unsigned NumBytes = ByteValues.size();
1440 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1441 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1443 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1444 // If this byte is masked out by a later operation, we don't care what
1446 if ((ByteMask & (1 << i)) == 0)
1449 // If the AndMask is all zeros for this byte, clear the bit.
1450 APInt MaskB = AndMask & Byte;
1452 ByteMask &= ~(1U << i);
1456 // If the AndMask is not all ones for this byte, it's not a bytezap.
1460 // Otherwise, this byte is kept.
1463 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1468 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1469 // the input value to the bswap. Some observations: 1) if more than one byte
1470 // is demanded from this input, then it could not be successfully assembled
1471 // into a byteswap. At least one of the two bytes would not be aligned with
1472 // their ultimate destination.
1473 if (!isPowerOf2_32(ByteMask)) return true;
1474 unsigned InputByteNo = countTrailingZeros(ByteMask);
1476 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1477 // is demanded, it needs to go into byte 0 of the result. This means that the
1478 // byte needs to be shifted until it lands in the right byte bucket. The
1479 // shift amount depends on the position: if the byte is coming from the high
1480 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1481 // low part, it must be shifted left.
1482 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1483 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1486 // If the destination byte value is already defined, the values are or'd
1487 // together, which isn't a bswap (unless it's an or of the same bits).
1488 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1490 ByteValues[DestByteNo] = V;
1494 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1495 /// If so, insert the new bswap intrinsic and return it.
1496 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1497 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1498 if (!ITy || ITy->getBitWidth() % 16 ||
1499 // ByteMask only allows up to 32-byte values.
1500 ITy->getBitWidth() > 32*8)
1501 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1503 /// ByteValues - For each byte of the result, we keep track of which value
1504 /// defines each byte.
1505 SmallVector<Value*, 8> ByteValues;
1506 ByteValues.resize(ITy->getBitWidth()/8);
1508 // Try to find all the pieces corresponding to the bswap.
1509 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1510 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1513 // Check to see if all of the bytes come from the same value.
1514 Value *V = ByteValues[0];
1515 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1517 // Check to make sure that all of the bytes come from the same value.
1518 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1519 if (ByteValues[i] != V)
1521 Module *M = I.getParent()->getParent()->getParent();
1522 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1523 return CallInst::Create(F, V);
1526 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1527 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1528 /// we can simplify this expression to "cond ? C : D or B".
1529 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1530 Value *C, Value *D) {
1531 // If A is not a select of -1/0, this cannot match.
1533 if (!match(A, m_SExt(m_Value(Cond))) ||
1534 !Cond->getType()->isIntegerTy(1))
1537 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1538 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1539 return SelectInst::Create(Cond, C, B);
1540 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1541 return SelectInst::Create(Cond, C, B);
1543 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1544 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1545 return SelectInst::Create(Cond, C, D);
1546 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1547 return SelectInst::Create(Cond, C, D);
1551 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1552 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1553 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1555 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1556 // if K1 and K2 are a one-bit mask.
1557 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1558 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1560 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1561 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1563 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1564 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1565 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1566 LAnd->getOpcode() == Instruction::And &&
1567 RAnd->getOpcode() == Instruction::And) {
1571 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1572 isKnownToBeAPowerOfTwo(LAnd->getOperand(1)) &&
1573 isKnownToBeAPowerOfTwo(RAnd->getOperand(1))) {
1574 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1575 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1576 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1577 isKnownToBeAPowerOfTwo(LAnd->getOperand(0)) &&
1578 isKnownToBeAPowerOfTwo(RAnd->getOperand(0))) {
1579 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1580 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1584 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1588 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1589 if (PredicatesFoldable(LHSCC, RHSCC)) {
1590 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1591 LHS->getOperand(1) == RHS->getOperand(0))
1592 LHS->swapOperands();
1593 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1594 LHS->getOperand(1) == RHS->getOperand(1)) {
1595 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1596 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1597 bool isSigned = LHS->isSigned() || RHS->isSigned();
1598 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1602 // handle (roughly):
1603 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1604 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1607 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1608 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1609 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1610 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1611 Value *A = 0, *B = 0;
1612 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1614 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1616 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1617 A = RHS->getOperand(1);
1619 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1620 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1621 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1623 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1625 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1626 A = LHS->getOperand(1);
1629 return Builder->CreateICmp(
1631 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1634 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1635 if (LHSCst == 0 || RHSCst == 0) return 0;
1637 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1638 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1639 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1640 Value *NewOr = Builder->CreateOr(Val, Val2);
1641 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1645 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1646 // iff C2 + CA == C1.
1647 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1648 ConstantInt *AddCst;
1649 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1650 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1651 return Builder->CreateICmpULE(Val, LHSCst);
1654 // From here on, we only handle:
1655 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1656 if (Val != Val2) return 0;
1658 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1659 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1660 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1661 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1662 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1665 // We can't fold (ugt x, C) | (sgt x, C2).
1666 if (!PredicatesFoldable(LHSCC, RHSCC))
1669 // Ensure that the larger constant is on the RHS.
1671 if (CmpInst::isSigned(LHSCC) ||
1672 (ICmpInst::isEquality(LHSCC) &&
1673 CmpInst::isSigned(RHSCC)))
1674 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1676 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1679 std::swap(LHS, RHS);
1680 std::swap(LHSCst, RHSCst);
1681 std::swap(LHSCC, RHSCC);
1684 // At this point, we know we have two icmp instructions
1685 // comparing a value against two constants and or'ing the result
1686 // together. Because of the above check, we know that we only have
1687 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1688 // icmp folding check above), that the two constants are not
1690 assert(LHSCst != RHSCst && "Compares not folded above?");
1693 default: llvm_unreachable("Unknown integer condition code!");
1694 case ICmpInst::ICMP_EQ:
1696 default: llvm_unreachable("Unknown integer condition code!");
1697 case ICmpInst::ICMP_EQ:
1698 if (LHS->getOperand(0) == RHS->getOperand(0)) {
1699 // if LHSCst and RHSCst differ only by one bit:
1700 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1701 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1703 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1704 if (Xor.isPowerOf2()) {
1705 Value *NegCst = Builder->getInt(~Xor);
1706 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1707 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1711 if (LHSCst == SubOne(RHSCst)) {
1712 // (X == 13 | X == 14) -> X-13 <u 2
1713 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1714 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1715 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1716 return Builder->CreateICmpULT(Add, AddCST);
1719 break; // (X == 13 | X == 15) -> no change
1720 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1721 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1723 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1724 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1725 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1729 case ICmpInst::ICMP_NE:
1731 default: llvm_unreachable("Unknown integer condition code!");
1732 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1733 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1734 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1736 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1737 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1738 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1739 return Builder->getTrue();
1741 case ICmpInst::ICMP_ULT:
1743 default: llvm_unreachable("Unknown integer condition code!");
1744 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1746 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1747 // If RHSCst is [us]MAXINT, it is always false. Not handling
1748 // this can cause overflow.
1749 if (RHSCst->isMaxValue(false))
1751 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1752 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1754 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1755 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1757 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1761 case ICmpInst::ICMP_SLT:
1763 default: llvm_unreachable("Unknown integer condition code!");
1764 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1766 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1767 // If RHSCst is [us]MAXINT, it is always false. Not handling
1768 // this can cause overflow.
1769 if (RHSCst->isMaxValue(true))
1771 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1772 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1774 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1775 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1777 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1781 case ICmpInst::ICMP_UGT:
1783 default: llvm_unreachable("Unknown integer condition code!");
1784 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1785 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1787 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1789 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1790 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1791 return Builder->getTrue();
1792 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1796 case ICmpInst::ICMP_SGT:
1798 default: llvm_unreachable("Unknown integer condition code!");
1799 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1800 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1802 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1804 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1805 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1806 return Builder->getTrue();
1807 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1815 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1816 /// instcombine, this returns a Value which should already be inserted into the
1818 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1819 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1820 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1821 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1822 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1823 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1824 // If either of the constants are nans, then the whole thing returns
1826 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1827 return Builder->getTrue();
1829 // Otherwise, no need to compare the two constants, compare the
1831 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1834 // Handle vector zeros. This occurs because the canonical form of
1835 // "fcmp uno x,x" is "fcmp uno x, 0".
1836 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1837 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1838 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1843 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1844 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1845 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1847 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1848 // Swap RHS operands to match LHS.
1849 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1850 std::swap(Op1LHS, Op1RHS);
1852 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1853 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1855 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1856 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1857 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1858 if (Op0CC == FCmpInst::FCMP_FALSE)
1860 if (Op1CC == FCmpInst::FCMP_FALSE)
1864 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1865 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1866 if (Op0Ordered == Op1Ordered) {
1867 // If both are ordered or unordered, return a new fcmp with
1868 // or'ed predicates.
1869 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1875 /// FoldOrWithConstants - This helper function folds:
1877 /// ((A | B) & C1) | (B & C2)
1883 /// when the XOR of the two constants is "all ones" (-1).
1884 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1885 Value *A, Value *B, Value *C) {
1886 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1890 ConstantInt *CI2 = 0;
1891 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1893 APInt Xor = CI1->getValue() ^ CI2->getValue();
1894 if (!Xor.isAllOnesValue()) return 0;
1896 if (V1 == A || V1 == B) {
1897 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1898 return BinaryOperator::CreateOr(NewOp, V1);
1904 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1905 bool Changed = SimplifyAssociativeOrCommutative(I);
1906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1908 if (Value *V = SimplifyOrInst(Op0, Op1, DL))
1909 return ReplaceInstUsesWith(I, V);
1911 // (A&B)|(A&C) -> A&(B|C) etc
1912 if (Value *V = SimplifyUsingDistributiveLaws(I))
1913 return ReplaceInstUsesWith(I, V);
1915 // See if we can simplify any instructions used by the instruction whose sole
1916 // purpose is to compute bits we don't care about.
1917 if (SimplifyDemandedInstructionBits(I))
1920 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1921 ConstantInt *C1 = 0; Value *X = 0;
1922 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1923 // iff (C1 & C2) == 0.
1924 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1925 (RHS->getValue() & C1->getValue()) != 0 &&
1927 Value *Or = Builder->CreateOr(X, RHS);
1929 return BinaryOperator::CreateAnd(Or,
1930 Builder->getInt(RHS->getValue() | C1->getValue()));
1933 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1934 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1936 Value *Or = Builder->CreateOr(X, RHS);
1938 return BinaryOperator::CreateXor(Or,
1939 Builder->getInt(C1->getValue() & ~RHS->getValue()));
1942 // Try to fold constant and into select arguments.
1943 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1944 if (Instruction *R = FoldOpIntoSelect(I, SI))
1947 if (isa<PHINode>(Op0))
1948 if (Instruction *NV = FoldOpIntoPhi(I))
1952 Value *A = 0, *B = 0;
1953 ConstantInt *C1 = 0, *C2 = 0;
1955 // (A | B) | C and A | (B | C) -> bswap if possible.
1956 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1957 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1958 match(Op1, m_Or(m_Value(), m_Value())) ||
1959 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1960 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1961 if (Instruction *BSwap = MatchBSwap(I))
1965 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1966 if (Op0->hasOneUse() &&
1967 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1968 MaskedValueIsZero(Op1, C1->getValue())) {
1969 Value *NOr = Builder->CreateOr(A, Op1);
1971 return BinaryOperator::CreateXor(NOr, C1);
1974 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1975 if (Op1->hasOneUse() &&
1976 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1977 MaskedValueIsZero(Op0, C1->getValue())) {
1978 Value *NOr = Builder->CreateOr(A, Op0);
1980 return BinaryOperator::CreateXor(NOr, C1);
1984 Value *C = 0, *D = 0;
1985 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1986 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1987 Value *V1 = 0, *V2 = 0;
1988 C1 = dyn_cast<ConstantInt>(C);
1989 C2 = dyn_cast<ConstantInt>(D);
1990 if (C1 && C2) { // (A & C1)|(B & C2)
1991 // If we have: ((V + N) & C1) | (V & C2)
1992 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1993 // replace with V+N.
1994 if (C1->getValue() == ~C2->getValue()) {
1995 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1996 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1997 // Add commutes, try both ways.
1998 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1999 return ReplaceInstUsesWith(I, A);
2000 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2001 return ReplaceInstUsesWith(I, A);
2003 // Or commutes, try both ways.
2004 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
2005 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2006 // Add commutes, try both ways.
2007 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2008 return ReplaceInstUsesWith(I, B);
2009 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2010 return ReplaceInstUsesWith(I, B);
2014 if ((C1->getValue() & C2->getValue()) == 0) {
2015 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2016 // iff (C1&C2) == 0 and (N&~C1) == 0
2017 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2018 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2019 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2020 return BinaryOperator::CreateAnd(A,
2021 Builder->getInt(C1->getValue()|C2->getValue()));
2022 // Or commutes, try both ways.
2023 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2024 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2025 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2026 return BinaryOperator::CreateAnd(B,
2027 Builder->getInt(C1->getValue()|C2->getValue()));
2029 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2030 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2031 ConstantInt *C3 = 0, *C4 = 0;
2032 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2033 (C3->getValue() & ~C1->getValue()) == 0 &&
2034 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2035 (C4->getValue() & ~C2->getValue()) == 0) {
2036 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2037 return BinaryOperator::CreateAnd(V2,
2038 Builder->getInt(C1->getValue()|C2->getValue()));
2043 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2044 // Don't do this for vector select idioms, the code generator doesn't handle
2046 if (!I.getType()->isVectorTy()) {
2047 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2049 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2051 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2053 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2057 // ((A&~B)|(~A&B)) -> A^B
2058 if ((match(C, m_Not(m_Specific(D))) &&
2059 match(B, m_Not(m_Specific(A)))))
2060 return BinaryOperator::CreateXor(A, D);
2061 // ((~B&A)|(~A&B)) -> A^B
2062 if ((match(A, m_Not(m_Specific(D))) &&
2063 match(B, m_Not(m_Specific(C)))))
2064 return BinaryOperator::CreateXor(C, D);
2065 // ((A&~B)|(B&~A)) -> A^B
2066 if ((match(C, m_Not(m_Specific(B))) &&
2067 match(D, m_Not(m_Specific(A)))))
2068 return BinaryOperator::CreateXor(A, B);
2069 // ((~B&A)|(B&~A)) -> A^B
2070 if ((match(A, m_Not(m_Specific(B))) &&
2071 match(D, m_Not(m_Specific(C)))))
2072 return BinaryOperator::CreateXor(C, B);
2074 // ((A|B)&1)|(B&-2) -> (A&1) | B
2075 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2076 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2077 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2078 if (Ret) return Ret;
2080 // (B&-2)|((A|B)&1) -> (A&1) | B
2081 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2082 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2083 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2084 if (Ret) return Ret;
2088 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
2089 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2090 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2091 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
2092 SI0->getOperand(1) == SI1->getOperand(1) &&
2093 (SI0->hasOneUse() || SI1->hasOneUse())) {
2094 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2096 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
2097 SI1->getOperand(1));
2101 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2102 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2103 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2104 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2105 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2106 I.getName()+".demorgan");
2107 return BinaryOperator::CreateNot(And);
2110 // Canonicalize xor to the RHS.
2111 bool SwappedForXor = false;
2112 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2113 std::swap(Op0, Op1);
2114 SwappedForXor = true;
2117 // A | ( A ^ B) -> A | B
2118 // A | (~A ^ B) -> A | ~B
2119 // (A & B) | (A ^ B)
2120 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2121 if (Op0 == A || Op0 == B)
2122 return BinaryOperator::CreateOr(A, B);
2124 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2125 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2126 return BinaryOperator::CreateOr(A, B);
2128 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2129 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2130 return BinaryOperator::CreateOr(Not, Op0);
2132 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2133 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2134 return BinaryOperator::CreateOr(Not, Op0);
2138 // A | ~(A | B) -> A | ~B
2139 // A | ~(A ^ B) -> A | ~B
2140 if (match(Op1, m_Not(m_Value(A))))
2141 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2142 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2143 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2144 B->getOpcode() == Instruction::Xor)) {
2145 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2147 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2148 return BinaryOperator::CreateOr(Not, Op0);
2152 std::swap(Op0, Op1);
2154 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2155 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2156 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2157 return ReplaceInstUsesWith(I, Res);
2159 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2160 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2161 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2162 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2163 return ReplaceInstUsesWith(I, Res);
2165 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2166 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2167 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2168 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2169 Type *SrcTy = Op0C->getOperand(0)->getType();
2170 if (SrcTy == Op1C->getOperand(0)->getType() &&
2171 SrcTy->isIntOrIntVectorTy()) {
2172 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
2174 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2175 // Only do this if the casts both really cause code to be
2177 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2178 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2179 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2180 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2183 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2184 // cast is otherwise not optimizable. This happens for vector sexts.
2185 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2186 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2187 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2188 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2190 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2191 // cast is otherwise not optimizable. This happens for vector sexts.
2192 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2193 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2194 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2195 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2200 // or(sext(A), B) -> A ? -1 : B where A is an i1
2201 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2202 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2203 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2204 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2205 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2207 // Note: If we've gotten to the point of visiting the outer OR, then the
2208 // inner one couldn't be simplified. If it was a constant, then it won't
2209 // be simplified by a later pass either, so we try swapping the inner/outer
2210 // ORs in the hopes that we'll be able to simplify it this way.
2211 // (X|C) | V --> (X|V) | C
2212 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2213 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2214 Value *Inner = Builder->CreateOr(A, Op1);
2215 Inner->takeName(Op0);
2216 return BinaryOperator::CreateOr(Inner, C1);
2219 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2220 // Since this OR statement hasn't been optimized further yet, we hope
2221 // that this transformation will allow the new ORs to be optimized.
2223 Value *X = 0, *Y = 0;
2224 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2225 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2226 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2227 Value *orTrue = Builder->CreateOr(A, C);
2228 Value *orFalse = Builder->CreateOr(B, D);
2229 return SelectInst::Create(X, orTrue, orFalse);
2233 return Changed ? &I : 0;
2236 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2237 bool Changed = SimplifyAssociativeOrCommutative(I);
2238 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2240 if (Value *V = SimplifyXorInst(Op0, Op1, DL))
2241 return ReplaceInstUsesWith(I, V);
2243 // (A&B)^(A&C) -> A&(B^C) etc
2244 if (Value *V = SimplifyUsingDistributiveLaws(I))
2245 return ReplaceInstUsesWith(I, V);
2247 // See if we can simplify any instructions used by the instruction whose sole
2248 // purpose is to compute bits we don't care about.
2249 if (SimplifyDemandedInstructionBits(I))
2252 // Is this a ~ operation?
2253 if (Value *NotOp = dyn_castNotVal(&I)) {
2254 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2255 if (Op0I->getOpcode() == Instruction::And ||
2256 Op0I->getOpcode() == Instruction::Or) {
2257 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2258 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2259 if (dyn_castNotVal(Op0I->getOperand(1)))
2260 Op0I->swapOperands();
2261 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2263 Builder->CreateNot(Op0I->getOperand(1),
2264 Op0I->getOperand(1)->getName()+".not");
2265 if (Op0I->getOpcode() == Instruction::And)
2266 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2267 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2270 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2271 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2272 if (isFreeToInvert(Op0I->getOperand(0)) &&
2273 isFreeToInvert(Op0I->getOperand(1))) {
2275 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2277 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2278 if (Op0I->getOpcode() == Instruction::And)
2279 return BinaryOperator::CreateOr(NotX, NotY);
2280 return BinaryOperator::CreateAnd(NotX, NotY);
2283 } else if (Op0I->getOpcode() == Instruction::AShr) {
2284 // ~(~X >>s Y) --> (X >>s Y)
2285 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2286 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2292 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2293 if (RHS->isOne() && Op0->hasOneUse())
2294 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2295 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2296 return CmpInst::Create(CI->getOpcode(),
2297 CI->getInversePredicate(),
2298 CI->getOperand(0), CI->getOperand(1));
2300 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2301 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2302 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2303 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2304 Instruction::CastOps Opcode = Op0C->getOpcode();
2305 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2306 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2307 Op0C->getDestTy()))) {
2308 CI->setPredicate(CI->getInversePredicate());
2309 return CastInst::Create(Opcode, CI, Op0C->getType());
2315 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2316 // ~(c-X) == X-c-1 == X+(-c-1)
2317 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2318 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2319 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2320 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2321 ConstantInt::get(I.getType(), 1));
2322 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2325 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2326 if (Op0I->getOpcode() == Instruction::Add) {
2327 // ~(X-c) --> (-c-1)-X
2328 if (RHS->isAllOnesValue()) {
2329 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2330 return BinaryOperator::CreateSub(
2331 ConstantExpr::getSub(NegOp0CI,
2332 ConstantInt::get(I.getType(), 1)),
2333 Op0I->getOperand(0));
2334 } else if (RHS->getValue().isSignBit()) {
2335 // (X + C) ^ signbit -> (X + C + signbit)
2336 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2337 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2340 } else if (Op0I->getOpcode() == Instruction::Or) {
2341 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2342 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2343 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2344 // Anything in both C1 and C2 is known to be zero, remove it from
2346 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2347 NewRHS = ConstantExpr::getAnd(NewRHS,
2348 ConstantExpr::getNot(CommonBits));
2350 I.setOperand(0, Op0I->getOperand(0));
2351 I.setOperand(1, NewRHS);
2354 } else if (Op0I->getOpcode() == Instruction::LShr) {
2355 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2359 if (Op0I->hasOneUse() &&
2360 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2361 E1->getOpcode() == Instruction::Xor &&
2362 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2363 // fold (C1 >> C2) ^ C3
2364 ConstantInt *C2 = Op0CI, *C3 = RHS;
2365 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2366 FoldConst ^= C3->getValue();
2367 // Prepare the two operands.
2368 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2369 Opnd0->takeName(Op0I);
2370 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2371 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2373 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2379 // Try to fold constant and into select arguments.
2380 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2381 if (Instruction *R = FoldOpIntoSelect(I, SI))
2383 if (isa<PHINode>(Op0))
2384 if (Instruction *NV = FoldOpIntoPhi(I))
2388 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2391 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2392 if (A == Op0) { // B^(B|A) == (A|B)^B
2393 Op1I->swapOperands();
2395 std::swap(Op0, Op1);
2396 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2397 I.swapOperands(); // Simplified below.
2398 std::swap(Op0, Op1);
2400 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2402 if (A == Op0) { // A^(A&B) -> A^(B&A)
2403 Op1I->swapOperands();
2406 if (B == Op0) { // A^(B&A) -> (B&A)^A
2407 I.swapOperands(); // Simplified below.
2408 std::swap(Op0, Op1);
2413 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2416 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2417 Op0I->hasOneUse()) {
2418 if (A == Op1) // (B|A)^B == (A|B)^B
2420 if (B == Op1) // (A|B)^B == A & ~B
2421 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2422 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2424 if (A == Op1) // (A&B)^A -> (B&A)^A
2426 if (B == Op1 && // (B&A)^A == ~B & A
2427 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2428 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2433 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2434 if (Op0I && Op1I && Op0I->isShift() &&
2435 Op0I->getOpcode() == Op1I->getOpcode() &&
2436 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2437 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
2439 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2441 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2442 Op1I->getOperand(1));
2446 Value *A, *B, *C, *D;
2447 // (A & B)^(A | B) -> A ^ B
2448 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2449 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2450 if ((A == C && B == D) || (A == D && B == C))
2451 return BinaryOperator::CreateXor(A, B);
2453 // (A | B)^(A & B) -> A ^ B
2454 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2455 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2456 if ((A == C && B == D) || (A == D && B == C))
2457 return BinaryOperator::CreateXor(A, B);
2461 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2462 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2463 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2464 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2465 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2466 LHS->getOperand(1) == RHS->getOperand(0))
2467 LHS->swapOperands();
2468 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2469 LHS->getOperand(1) == RHS->getOperand(1)) {
2470 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2471 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2472 bool isSigned = LHS->isSigned() || RHS->isSigned();
2473 return ReplaceInstUsesWith(I,
2474 getNewICmpValue(isSigned, Code, Op0, Op1,
2479 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2480 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2481 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2482 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2483 Type *SrcTy = Op0C->getOperand(0)->getType();
2484 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2485 // Only do this if the casts both really cause code to be generated.
2486 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2488 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2490 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2491 Op1C->getOperand(0), I.getName());
2492 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2497 return Changed ? &I : 0;