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 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/ConstantRange.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/PatternMatch.h"
20 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
22 using namespace PatternMatch;
24 /// isFreeToInvert - Return true if the specified value is free to invert (apply
25 /// ~ to). This happens in cases where the ~ can be eliminated.
26 static inline bool isFreeToInvert(Value *V) {
28 if (BinaryOperator::isNot(V))
31 // Constants can be considered to be not'ed values.
32 if (isa<ConstantInt>(V))
35 // Compares can be inverted if they have a single use.
36 if (CmpInst *CI = dyn_cast<CmpInst>(V))
37 return CI->hasOneUse();
42 static inline Value *dyn_castNotVal(Value *V) {
43 // If this is not(not(x)) don't return that this is a not: we want the two
44 // not's to be folded first.
45 if (BinaryOperator::isNot(V)) {
46 Value *Operand = BinaryOperator::getNotArgument(V);
47 if (!isFreeToInvert(Operand))
51 // Constants can be considered to be not'ed values...
52 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
53 return ConstantInt::get(C->getType(), ~C->getValue());
57 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
58 /// predicate into a three bit mask. It also returns whether it is an ordered
59 /// predicate by reference.
60 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
63 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
64 case FCmpInst::FCMP_UNO: return 0; // 000
65 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
66 case FCmpInst::FCMP_UGT: return 1; // 001
67 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
68 case FCmpInst::FCMP_UEQ: return 2; // 010
69 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
70 case FCmpInst::FCMP_UGE: return 3; // 011
71 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
72 case FCmpInst::FCMP_ULT: return 4; // 100
73 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
74 case FCmpInst::FCMP_UNE: return 5; // 101
75 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
76 case FCmpInst::FCMP_ULE: return 6; // 110
79 // Not expecting FCMP_FALSE and FCMP_TRUE;
80 llvm_unreachable("Unexpected FCmp predicate!");
84 /// getNewICmpValue - This is the complement of getICmpCode, which turns an
85 /// opcode and two operands into either a constant true or false, or a brand
86 /// new ICmp instruction. The sign is passed in to determine which kind
87 /// of predicate to use in the new icmp instruction.
88 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
89 InstCombiner::BuilderTy *Builder) {
90 ICmpInst::Predicate NewPred;
91 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
93 return Builder->CreateICmp(NewPred, LHS, RHS);
96 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
97 /// opcode and two operands into either a FCmp instruction. isordered is passed
98 /// in to determine which kind of predicate to use in the new fcmp instruction.
99 static Value *getFCmpValue(bool isordered, unsigned code,
100 Value *LHS, Value *RHS,
101 InstCombiner::BuilderTy *Builder) {
102 CmpInst::Predicate Pred;
104 default: llvm_unreachable("Illegal FCmp code!");
105 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
106 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
107 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
108 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
109 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
110 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
111 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
113 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
114 Pred = FCmpInst::FCMP_ORD; break;
116 return Builder->CreateFCmp(Pred, LHS, RHS);
119 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
120 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
121 // guaranteed to be a binary operator.
122 Instruction *InstCombiner::OptAndOp(Instruction *Op,
125 BinaryOperator &TheAnd) {
126 Value *X = Op->getOperand(0);
127 Constant *Together = 0;
129 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
131 switch (Op->getOpcode()) {
132 case Instruction::Xor:
133 if (Op->hasOneUse()) {
134 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
135 Value *And = Builder->CreateAnd(X, AndRHS);
137 return BinaryOperator::CreateXor(And, Together);
140 case Instruction::Or:
141 if (Op->hasOneUse()){
142 if (Together != OpRHS) {
143 // (X | C1) & C2 --> (X | (C1&C2)) & C2
144 Value *Or = Builder->CreateOr(X, Together);
146 return BinaryOperator::CreateAnd(Or, AndRHS);
149 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
150 if (TogetherCI && !TogetherCI->isZero()){
151 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
152 // NOTE: This reduces the number of bits set in the & mask, which
153 // can expose opportunities for store narrowing.
154 Together = ConstantExpr::getXor(AndRHS, Together);
155 Value *And = Builder->CreateAnd(X, Together);
157 return BinaryOperator::CreateOr(And, OpRHS);
162 case Instruction::Add:
163 if (Op->hasOneUse()) {
164 // Adding a one to a single bit bit-field should be turned into an XOR
165 // of the bit. First thing to check is to see if this AND is with a
166 // single bit constant.
167 const APInt &AndRHSV = AndRHS->getValue();
169 // If there is only one bit set.
170 if (AndRHSV.isPowerOf2()) {
171 // Ok, at this point, we know that we are masking the result of the
172 // ADD down to exactly one bit. If the constant we are adding has
173 // no bits set below this bit, then we can eliminate the ADD.
174 const APInt& AddRHS = OpRHS->getValue();
176 // Check to see if any bits below the one bit set in AndRHSV are set.
177 if ((AddRHS & (AndRHSV-1)) == 0) {
178 // If not, the only thing that can effect the output of the AND is
179 // the bit specified by AndRHSV. If that bit is set, the effect of
180 // the XOR is to toggle the bit. If it is clear, then the ADD has
182 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
183 TheAnd.setOperand(0, X);
186 // Pull the XOR out of the AND.
187 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
188 NewAnd->takeName(Op);
189 return BinaryOperator::CreateXor(NewAnd, AndRHS);
196 case Instruction::Shl: {
197 // We know that the AND will not produce any of the bits shifted in, so if
198 // the anded constant includes them, clear them now!
200 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
201 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
202 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
203 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
205 if (CI->getValue() == ShlMask)
206 // Masking out bits that the shift already masks.
207 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
209 if (CI != AndRHS) { // Reducing bits set in and.
210 TheAnd.setOperand(1, CI);
215 case Instruction::LShr: {
216 // We know that the AND will not produce any of the bits shifted in, so if
217 // the anded constant includes them, clear them now! This only applies to
218 // unsigned shifts, because a signed shr may bring in set bits!
220 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
221 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
222 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
223 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
225 if (CI->getValue() == ShrMask)
226 // Masking out bits that the shift already masks.
227 return ReplaceInstUsesWith(TheAnd, Op);
230 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
235 case Instruction::AShr:
237 // See if this is shifting in some sign extension, then masking it out
239 if (Op->hasOneUse()) {
240 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
241 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
242 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
243 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
244 if (C == AndRHS) { // Masking out bits shifted in.
245 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
246 // Make the argument unsigned.
247 Value *ShVal = Op->getOperand(0);
248 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
249 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
257 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
258 /// (V < Lo || V >= Hi). In practice, we emit the more efficient
259 /// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
260 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
261 /// insert new instructions.
262 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
263 bool isSigned, bool Inside) {
264 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
265 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
266 "Lo is not <= Hi in range emission code!");
269 if (Lo == Hi) // Trivially false.
270 return Builder->getFalse();
272 // V >= Min && V < Hi --> V < Hi
273 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
274 ICmpInst::Predicate pred = (isSigned ?
275 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
276 return Builder->CreateICmp(pred, V, Hi);
279 // Emit V-Lo <u Hi-Lo
280 Constant *NegLo = ConstantExpr::getNeg(Lo);
281 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
282 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
283 return Builder->CreateICmpULT(Add, UpperBound);
286 if (Lo == Hi) // Trivially true.
287 return Builder->getTrue();
289 // V < Min || V >= Hi -> V > Hi-1
290 Hi = SubOne(cast<ConstantInt>(Hi));
291 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
292 ICmpInst::Predicate pred = (isSigned ?
293 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
294 return Builder->CreateICmp(pred, V, Hi);
297 // Emit V-Lo >u Hi-1-Lo
298 // Note that Hi has already had one subtracted from it, above.
299 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
300 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
301 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
302 return Builder->CreateICmpUGT(Add, LowerBound);
305 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
306 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
307 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
308 // not, since all 1s are not contiguous.
309 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
310 const APInt& V = Val->getValue();
311 uint32_t BitWidth = Val->getType()->getBitWidth();
312 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
314 // look for the first zero bit after the run of ones
315 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
316 // look for the first non-zero bit
317 ME = V.getActiveBits();
321 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
322 /// where isSub determines whether the operator is a sub. If we can fold one of
323 /// the following xforms:
325 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
326 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
327 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
329 /// return (A +/- B).
331 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
332 ConstantInt *Mask, bool isSub,
334 Instruction *LHSI = dyn_cast<Instruction>(LHS);
335 if (!LHSI || LHSI->getNumOperands() != 2 ||
336 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
338 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
340 switch (LHSI->getOpcode()) {
342 case Instruction::And:
343 if (ConstantExpr::getAnd(N, Mask) == Mask) {
344 // If the AndRHS is a power of two minus one (0+1+), this is simple.
345 if ((Mask->getValue().countLeadingZeros() +
346 Mask->getValue().countPopulation()) ==
347 Mask->getValue().getBitWidth())
350 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
351 // part, we don't need any explicit masks to take them out of A. If that
352 // is all N is, ignore it.
353 uint32_t MB = 0, ME = 0;
354 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
355 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
356 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
357 if (MaskedValueIsZero(RHS, Mask))
362 case Instruction::Or:
363 case Instruction::Xor:
364 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
365 if ((Mask->getValue().countLeadingZeros() +
366 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
367 && ConstantExpr::getAnd(N, Mask)->isNullValue())
373 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
374 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
377 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
378 /// One of A and B is considered the mask, the other the value. This is
379 /// described as the "AMask" or "BMask" part of the enum. If the enum
380 /// contains only "Mask", then both A and B can be considered masks.
381 /// If A is the mask, then it was proven, that (A & C) == C. This
382 /// is trivial if C == A, or C == 0. If both A and C are constants, this
383 /// proof is also easy.
384 /// For the following explanations we assume that A is the mask.
385 /// The part "AllOnes" declares, that the comparison is true only
386 /// if (A & B) == A, or all bits of A are set in B.
387 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
388 /// The part "AllZeroes" declares, that the comparison is true only
389 /// if (A & B) == 0, or all bits of A are cleared in B.
390 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
391 /// The part "Mixed" declares, that (A & B) == C and C might or might not
392 /// contain any number of one bits and zero bits.
393 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
394 /// The Part "Not" means, that in above descriptions "==" should be replaced
396 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
397 /// If the mask A contains a single bit, then the following is equivalent:
398 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
399 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
400 enum MaskedICmpType {
401 FoldMskICmp_AMask_AllOnes = 1,
402 FoldMskICmp_AMask_NotAllOnes = 2,
403 FoldMskICmp_BMask_AllOnes = 4,
404 FoldMskICmp_BMask_NotAllOnes = 8,
405 FoldMskICmp_Mask_AllZeroes = 16,
406 FoldMskICmp_Mask_NotAllZeroes = 32,
407 FoldMskICmp_AMask_Mixed = 64,
408 FoldMskICmp_AMask_NotMixed = 128,
409 FoldMskICmp_BMask_Mixed = 256,
410 FoldMskICmp_BMask_NotMixed = 512
413 /// return the set of pattern classes (from MaskedICmpType)
414 /// that (icmp SCC (A & B), C) satisfies
415 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
416 ICmpInst::Predicate SCC)
418 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
419 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
420 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
421 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
422 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
423 ACst->getValue().isPowerOf2());
424 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
425 BCst->getValue().isPowerOf2());
427 if (CCst != 0 && CCst->isZero()) {
428 // if C is zero, then both A and B qualify as mask
429 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
430 FoldMskICmp_Mask_AllZeroes |
431 FoldMskICmp_AMask_Mixed |
432 FoldMskICmp_BMask_Mixed)
433 : (FoldMskICmp_Mask_NotAllZeroes |
434 FoldMskICmp_Mask_NotAllZeroes |
435 FoldMskICmp_AMask_NotMixed |
436 FoldMskICmp_BMask_NotMixed));
438 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
439 FoldMskICmp_AMask_NotMixed)
440 : (FoldMskICmp_AMask_AllOnes |
441 FoldMskICmp_AMask_Mixed));
443 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
444 FoldMskICmp_BMask_NotMixed)
445 : (FoldMskICmp_BMask_AllOnes |
446 FoldMskICmp_BMask_Mixed));
450 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
451 FoldMskICmp_AMask_Mixed)
452 : (FoldMskICmp_AMask_NotAllOnes |
453 FoldMskICmp_AMask_NotMixed));
455 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
456 FoldMskICmp_AMask_NotMixed)
457 : (FoldMskICmp_Mask_AllZeroes |
458 FoldMskICmp_AMask_Mixed));
459 } else if (ACst != 0 && CCst != 0 &&
460 ConstantExpr::getAnd(ACst, CCst) == CCst) {
461 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
462 : FoldMskICmp_AMask_NotMixed);
465 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
466 FoldMskICmp_BMask_Mixed)
467 : (FoldMskICmp_BMask_NotAllOnes |
468 FoldMskICmp_BMask_NotMixed));
470 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
471 FoldMskICmp_BMask_NotMixed)
472 : (FoldMskICmp_Mask_AllZeroes |
473 FoldMskICmp_BMask_Mixed));
474 } else if (BCst != 0 && CCst != 0 &&
475 ConstantExpr::getAnd(BCst, CCst) == CCst) {
476 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
477 : FoldMskICmp_BMask_NotMixed);
482 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
483 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
484 /// is adjacent to the corresponding normal flag (recording ==), this just
485 /// involves swapping those bits over.
486 static unsigned conjugateICmpMask(unsigned Mask) {
488 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
489 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
490 FoldMskICmp_BMask_Mixed))
494 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
495 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
496 FoldMskICmp_BMask_NotMixed))
502 /// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
503 /// if possible. The returned predicate is either == or !=. Returns false if
504 /// decomposition fails.
505 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
506 Value *&X, Value *&Y, Value *&Z) {
507 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
511 switch (I->getPredicate()) {
514 case ICmpInst::ICMP_SLT:
515 // X < 0 is equivalent to (X & SignBit) != 0.
518 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
519 Pred = ICmpInst::ICMP_NE;
521 case ICmpInst::ICMP_SGT:
522 // X > -1 is equivalent to (X & SignBit) == 0.
523 if (!C->isAllOnesValue())
525 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
526 Pred = ICmpInst::ICMP_EQ;
528 case ICmpInst::ICMP_ULT:
529 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
530 if (!C->getValue().isPowerOf2())
532 Y = ConstantInt::get(I->getContext(), -C->getValue());
533 Pred = ICmpInst::ICMP_EQ;
535 case ICmpInst::ICMP_UGT:
536 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
537 if (!(C->getValue() + 1).isPowerOf2())
539 Y = ConstantInt::get(I->getContext(), ~C->getValue());
540 Pred = ICmpInst::ICMP_NE;
544 X = I->getOperand(0);
545 Z = ConstantInt::getNullValue(C->getType());
549 /// foldLogOpOfMaskedICmpsHelper:
550 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
551 /// return the set of pattern classes (from MaskedICmpType)
552 /// that both LHS and RHS satisfy
553 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
554 Value*& B, Value*& C,
555 Value*& D, Value*& E,
556 ICmpInst *LHS, ICmpInst *RHS,
557 ICmpInst::Predicate &LHSCC,
558 ICmpInst::Predicate &RHSCC) {
559 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
560 // vectors are not (yet?) supported
561 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
563 // Here comes the tricky part:
564 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
565 // and L11 & L12 == L21 & L22. The same goes for RHS.
566 // Now we must find those components L** and R**, that are equal, so
567 // that we can extract the parameters A, B, C, D, and E for the canonical
569 Value *L1 = LHS->getOperand(0);
570 Value *L2 = LHS->getOperand(1);
571 Value *L11,*L12,*L21,*L22;
572 // Check whether the icmp can be decomposed into a bit test.
573 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
576 // Look for ANDs in the LHS icmp.
577 if (!L1->getType()->isIntegerTy()) {
578 // You can icmp pointers, for example. They really aren't masks.
580 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
581 // Any icmp can be viewed as being trivially masked; if it allows us to
582 // remove one, it's worth it.
584 L12 = Constant::getAllOnesValue(L1->getType());
587 if (!L2->getType()->isIntegerTy()) {
588 // You can icmp pointers, for example. They really aren't masks.
590 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
592 L22 = Constant::getAllOnesValue(L2->getType());
596 // Bail if LHS was a icmp that can't be decomposed into an equality.
597 if (!ICmpInst::isEquality(LHSCC))
600 Value *R1 = RHS->getOperand(0);
601 Value *R2 = RHS->getOperand(1);
604 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
605 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
607 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
612 E = R2; R1 = 0; ok = true;
613 } else if (R1->getType()->isIntegerTy()) {
614 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
615 // As before, model no mask as a trivial mask if it'll let us do an
618 R12 = Constant::getAllOnesValue(R1->getType());
621 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
622 A = R11; D = R12; E = R2; ok = true;
623 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
624 A = R12; D = R11; E = R2; ok = true;
628 // Bail if RHS was a icmp that can't be decomposed into an equality.
629 if (!ICmpInst::isEquality(RHSCC))
632 // Look for ANDs in on the right side of the RHS icmp.
633 if (!ok && R2->getType()->isIntegerTy()) {
634 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
636 R12 = Constant::getAllOnesValue(R2->getType());
639 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
640 A = R11; D = R12; E = R1; ok = true;
641 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
642 A = R12; D = R11; E = R1; ok = true;
652 } else if (L12 == A) {
654 } else if (L21 == A) {
656 } else if (L22 == A) {
660 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
661 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
662 return left_type & right_type;
664 /// foldLogOpOfMaskedICmps:
665 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
666 /// into a single (icmp(A & X) ==/!= Y)
667 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
668 llvm::InstCombiner::BuilderTy* Builder) {
669 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
670 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
671 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
673 if (mask == 0) return 0;
674 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
675 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
677 // In full generality:
678 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
679 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
681 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
682 // equivalent to (icmp (A & X) !Op Y).
684 // Therefore, we can pretend for the rest of this function that we're dealing
685 // with the conjunction, provided we flip the sense of any comparisons (both
686 // input and output).
688 // In most cases we're going to produce an EQ for the "&&" case.
689 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
691 // Convert the masking analysis into its equivalent with negated
693 mask = conjugateICmpMask(mask);
696 if (mask & FoldMskICmp_Mask_AllZeroes) {
697 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
698 // -> (icmp eq (A & (B|D)), 0)
699 Value* newOr = Builder->CreateOr(B, D);
700 Value* newAnd = Builder->CreateAnd(A, newOr);
701 // we can't use C as zero, because we might actually handle
702 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
703 // with B and D, having a single bit set
704 Value* zero = Constant::getNullValue(A->getType());
705 return Builder->CreateICmp(NEWCC, newAnd, zero);
707 if (mask & FoldMskICmp_BMask_AllOnes) {
708 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
709 // -> (icmp eq (A & (B|D)), (B|D))
710 Value* newOr = Builder->CreateOr(B, D);
711 Value* newAnd = Builder->CreateAnd(A, newOr);
712 return Builder->CreateICmp(NEWCC, newAnd, newOr);
714 if (mask & FoldMskICmp_AMask_AllOnes) {
715 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
716 // -> (icmp eq (A & (B&D)), A)
717 Value* newAnd1 = Builder->CreateAnd(B, D);
718 Value* newAnd = Builder->CreateAnd(A, newAnd1);
719 return Builder->CreateICmp(NEWCC, newAnd, A);
722 // Remaining cases assume at least that B and D are constant, and depend on
723 // their actual values. This isn't strictly, necessary, just a "handle the
724 // easy cases for now" decision.
725 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
726 if (BCst == 0) return 0;
727 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
728 if (DCst == 0) return 0;
730 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
731 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
732 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
733 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
734 // Only valid if one of the masks is a superset of the other (check "B&D" is
735 // the same as either B or D).
736 APInt NewMask = BCst->getValue() & DCst->getValue();
738 if (NewMask == BCst->getValue())
740 else if (NewMask == DCst->getValue())
743 if (mask & FoldMskICmp_AMask_NotAllOnes) {
744 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
745 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
746 // Only valid if one of the masks is a superset of the other (check "B|D" is
747 // the same as either B or D).
748 APInt NewMask = BCst->getValue() | DCst->getValue();
750 if (NewMask == BCst->getValue())
752 else if (NewMask == DCst->getValue())
755 if (mask & FoldMskICmp_BMask_Mixed) {
756 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
757 // We already know that B & C == C && D & E == E.
758 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
759 // C and E, which are shared by both the mask B and the mask D, don't
760 // contradict, then we can transform to
761 // -> (icmp eq (A & (B|D)), (C|E))
762 // Currently, we only handle the case of B, C, D, and E being constant.
763 // we can't simply use C and E, because we might actually handle
764 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
765 // with B and D, having a single bit set
766 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
767 if (CCst == 0) return 0;
769 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
770 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
771 if (ECst == 0) return 0;
773 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
774 ConstantInt* MCst = dyn_cast<ConstantInt>(
775 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
776 ConstantExpr::getXor(CCst, ECst)) );
777 // if there is a conflict we should actually return a false for the
781 Value *newOr1 = Builder->CreateOr(B, D);
782 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
783 Value *newAnd = Builder->CreateAnd(A, newOr1);
784 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
789 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
790 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
791 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
793 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
794 if (PredicatesFoldable(LHSCC, RHSCC)) {
795 if (LHS->getOperand(0) == RHS->getOperand(1) &&
796 LHS->getOperand(1) == RHS->getOperand(0))
798 if (LHS->getOperand(0) == RHS->getOperand(0) &&
799 LHS->getOperand(1) == RHS->getOperand(1)) {
800 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
801 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
802 bool isSigned = LHS->isSigned() || RHS->isSigned();
803 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
807 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
808 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
811 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
812 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
813 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
814 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
815 if (LHSCst == 0 || RHSCst == 0) return 0;
817 if (LHSCst == RHSCst && LHSCC == RHSCC) {
818 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
819 // where C is a power of 2
820 if (LHSCC == ICmpInst::ICMP_ULT &&
821 LHSCst->getValue().isPowerOf2()) {
822 Value *NewOr = Builder->CreateOr(Val, Val2);
823 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
826 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
827 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
828 Value *NewOr = Builder->CreateOr(Val, Val2);
829 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
833 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
834 // where CMAX is the all ones value for the truncated type,
835 // iff the lower bits of C2 and CA are zero.
836 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
837 LHS->hasOneUse() && RHS->hasOneUse()) {
839 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
841 // (trunc x) == C1 & (and x, CA) == C2
842 // (and x, CA) == C2 & (trunc x) == C1
843 if (match(Val2, m_Trunc(m_Value(V))) &&
844 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
847 } else if (match(Val, m_Trunc(m_Value(V))) &&
848 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
853 if (SmallCst && BigCst) {
854 unsigned BigBitSize = BigCst->getType()->getBitWidth();
855 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
857 // Check that the low bits are zero.
858 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
859 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
860 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
861 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
862 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
863 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
868 // From here on, we only handle:
869 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
870 if (Val != Val2) return 0;
872 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
873 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
874 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
875 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
876 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
879 // Make a constant range that's the intersection of the two icmp ranges.
880 // If the intersection is empty, we know that the result is false.
881 ConstantRange LHSRange =
882 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
883 ConstantRange RHSRange =
884 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
886 if (LHSRange.intersectWith(RHSRange).isEmptySet())
887 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
889 // We can't fold (ugt x, C) & (sgt x, C2).
890 if (!PredicatesFoldable(LHSCC, RHSCC))
893 // Ensure that the larger constant is on the RHS.
895 if (CmpInst::isSigned(LHSCC) ||
896 (ICmpInst::isEquality(LHSCC) &&
897 CmpInst::isSigned(RHSCC)))
898 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
900 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
904 std::swap(LHSCst, RHSCst);
905 std::swap(LHSCC, RHSCC);
908 // At this point, we know we have two icmp instructions
909 // comparing a value against two constants and and'ing the result
910 // together. Because of the above check, we know that we only have
911 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
912 // (from the icmp folding check above), that the two constants
913 // are not equal and that the larger constant is on the RHS
914 assert(LHSCst != RHSCst && "Compares not folded above?");
917 default: llvm_unreachable("Unknown integer condition code!");
918 case ICmpInst::ICMP_EQ:
920 default: llvm_unreachable("Unknown integer condition code!");
921 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
922 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
923 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
926 case ICmpInst::ICMP_NE:
928 default: llvm_unreachable("Unknown integer condition code!");
929 case ICmpInst::ICMP_ULT:
930 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
931 return Builder->CreateICmpULT(Val, LHSCst);
932 break; // (X != 13 & X u< 15) -> no change
933 case ICmpInst::ICMP_SLT:
934 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
935 return Builder->CreateICmpSLT(Val, LHSCst);
936 break; // (X != 13 & X s< 15) -> no change
937 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
938 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
939 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
941 case ICmpInst::ICMP_NE:
942 // Special case to get the ordering right when the values wrap around
944 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
945 std::swap(LHSCst, RHSCst);
946 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
947 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
948 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
949 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
950 Val->getName()+".cmp");
952 break; // (X != 13 & X != 15) -> no change
955 case ICmpInst::ICMP_ULT:
957 default: llvm_unreachable("Unknown integer condition code!");
958 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
959 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
960 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
961 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
963 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
964 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
966 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
970 case ICmpInst::ICMP_SLT:
972 default: llvm_unreachable("Unknown integer condition code!");
973 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
975 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
976 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
978 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
982 case ICmpInst::ICMP_UGT:
984 default: llvm_unreachable("Unknown integer condition code!");
985 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
986 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
988 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
990 case ICmpInst::ICMP_NE:
991 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
992 return Builder->CreateICmp(LHSCC, Val, RHSCst);
993 break; // (X u> 13 & X != 15) -> no change
994 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
995 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
996 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1000 case ICmpInst::ICMP_SGT:
1002 default: llvm_unreachable("Unknown integer condition code!");
1003 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1004 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1006 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1008 case ICmpInst::ICMP_NE:
1009 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1010 return Builder->CreateICmp(LHSCC, Val, RHSCst);
1011 break; // (X s> 13 & X != 15) -> no change
1012 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
1013 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1014 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1023 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1024 /// instcombine, this returns a Value which should already be inserted into the
1026 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1027 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1028 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1029 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1032 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1033 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1034 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1035 // If either of the constants are nans, then the whole thing returns
1037 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1038 return Builder->getFalse();
1039 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1042 // Handle vector zeros. This occurs because the canonical form of
1043 // "fcmp ord x,x" is "fcmp ord x, 0".
1044 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1045 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1046 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1050 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1051 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1052 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1055 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1056 // Swap RHS operands to match LHS.
1057 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1058 std::swap(Op1LHS, Op1RHS);
1061 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1062 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1064 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1065 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1066 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1067 if (Op0CC == FCmpInst::FCMP_TRUE)
1069 if (Op1CC == FCmpInst::FCMP_TRUE)
1074 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1075 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1076 // uno && ord -> false
1077 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1078 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1080 std::swap(LHS, RHS);
1081 std::swap(Op0Pred, Op1Pred);
1082 std::swap(Op0Ordered, Op1Ordered);
1085 // uno && ueq -> uno && (uno || eq) -> uno
1086 // ord && olt -> ord && (ord && lt) -> olt
1087 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1089 if (Op0Ordered && (Op0Ordered == Op1Ordered))
1092 // uno && oeq -> uno && (ord && eq) -> false
1094 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1095 // ord && ueq -> ord && (uno || eq) -> oeq
1096 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1104 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1105 bool Changed = SimplifyAssociativeOrCommutative(I);
1106 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1108 if (Value *V = SimplifyAndInst(Op0, Op1, DL))
1109 return ReplaceInstUsesWith(I, V);
1111 // (A|B)&(A|C) -> A|(B&C) etc
1112 if (Value *V = SimplifyUsingDistributiveLaws(I))
1113 return ReplaceInstUsesWith(I, V);
1115 // See if we can simplify any instructions used by the instruction whose sole
1116 // purpose is to compute bits we don't care about.
1117 if (SimplifyDemandedInstructionBits(I))
1120 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1121 const APInt &AndRHSMask = AndRHS->getValue();
1123 // Optimize a variety of ((val OP C1) & C2) combinations...
1124 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1125 Value *Op0LHS = Op0I->getOperand(0);
1126 Value *Op0RHS = Op0I->getOperand(1);
1127 switch (Op0I->getOpcode()) {
1129 case Instruction::Xor:
1130 case Instruction::Or: {
1131 // If the mask is only needed on one incoming arm, push it up.
1132 if (!Op0I->hasOneUse()) break;
1134 APInt NotAndRHS(~AndRHSMask);
1135 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1136 // Not masking anything out for the LHS, move to RHS.
1137 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1138 Op0RHS->getName()+".masked");
1139 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1141 if (!isa<Constant>(Op0RHS) &&
1142 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1143 // Not masking anything out for the RHS, move to LHS.
1144 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1145 Op0LHS->getName()+".masked");
1146 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1151 case Instruction::Add:
1152 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1153 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1154 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1155 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1156 return BinaryOperator::CreateAnd(V, AndRHS);
1157 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1158 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1161 case Instruction::Sub:
1162 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1163 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1164 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1165 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1166 return BinaryOperator::CreateAnd(V, AndRHS);
1168 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1169 // has 1's for all bits that the subtraction with A might affect.
1170 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1171 uint32_t BitWidth = AndRHSMask.getBitWidth();
1172 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1173 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1175 if (MaskedValueIsZero(Op0LHS, Mask)) {
1176 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1177 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1182 case Instruction::Shl:
1183 case Instruction::LShr:
1184 // (1 << x) & 1 --> zext(x == 0)
1185 // (1 >> x) & 1 --> zext(x == 0)
1186 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1188 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1189 return new ZExtInst(NewICmp, I.getType());
1194 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1195 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1199 // If this is an integer truncation, and if the source is an 'and' with
1200 // immediate, transform it. This frequently occurs for bitfield accesses.
1202 Value *X = 0; ConstantInt *YC = 0;
1203 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1204 // Change: and (trunc (and X, YC) to T), C2
1205 // into : and (trunc X to T), trunc(YC) & C2
1206 // This will fold the two constants together, which may allow
1207 // other simplifications.
1208 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1209 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1210 C3 = ConstantExpr::getAnd(C3, AndRHS);
1211 return BinaryOperator::CreateAnd(NewCast, C3);
1215 // Try to fold constant and into select arguments.
1216 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1217 if (Instruction *R = FoldOpIntoSelect(I, SI))
1219 if (isa<PHINode>(Op0))
1220 if (Instruction *NV = FoldOpIntoPhi(I))
1225 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1226 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1227 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1228 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1229 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1230 I.getName()+".demorgan");
1231 return BinaryOperator::CreateNot(Or);
1235 Value *A = 0, *B = 0, *C = 0, *D = 0;
1236 // (A|B) & ~(A&B) -> A^B
1237 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1238 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1239 ((A == C && B == D) || (A == D && B == C)))
1240 return BinaryOperator::CreateXor(A, B);
1242 // ~(A&B) & (A|B) -> A^B
1243 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1244 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1245 ((A == C && B == D) || (A == D && B == C)))
1246 return BinaryOperator::CreateXor(A, B);
1248 // A&(A^B) => A & ~B
1250 Value *tmpOp0 = Op0;
1251 Value *tmpOp1 = Op1;
1252 if (Op0->hasOneUse() &&
1253 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1254 if (A == Op1 || B == Op1 ) {
1261 if (tmpOp1->hasOneUse() &&
1262 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1266 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1267 // A is originally -1 (or a vector of -1 and undefs), then we enter
1268 // an endless loop. By checking that A is non-constant we ensure that
1269 // we will never get to the loop.
1270 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1271 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1275 // (A&((~A)|B)) -> A&B
1276 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1277 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1278 return BinaryOperator::CreateAnd(A, Op1);
1279 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1280 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1281 return BinaryOperator::CreateAnd(A, Op0);
1284 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1285 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1286 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1287 return ReplaceInstUsesWith(I, Res);
1289 // If and'ing two fcmp, try combine them into one.
1290 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1291 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1292 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1293 return ReplaceInstUsesWith(I, Res);
1296 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1297 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1298 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1299 Type *SrcTy = Op0C->getOperand(0)->getType();
1300 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1301 SrcTy == Op1C->getOperand(0)->getType() &&
1302 SrcTy->isIntOrIntVectorTy()) {
1303 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1305 // Only do this if the casts both really cause code to be generated.
1306 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1307 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1308 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1309 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1312 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1313 // cast is otherwise not optimizable. This happens for vector sexts.
1314 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1315 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1316 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1317 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1319 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1320 // cast is otherwise not optimizable. This happens for vector sexts.
1321 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1322 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1323 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1324 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1328 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1329 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1330 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1331 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1332 SI0->getOperand(1) == SI1->getOperand(1) &&
1333 (SI0->hasOneUse() || SI1->hasOneUse())) {
1335 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1337 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1338 SI1->getOperand(1));
1344 bool OpsSwapped = false;
1345 // Canonicalize SExt or Not to the LHS
1346 if (match(Op1, m_SExt(m_Value())) ||
1347 match(Op1, m_Not(m_Value()))) {
1348 std::swap(Op0, Op1);
1352 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1353 if (match(Op0, m_SExt(m_Value(X))) &&
1354 X->getType()->getScalarType()->isIntegerTy(1)) {
1355 Value *Zero = Constant::getNullValue(Op1->getType());
1356 return SelectInst::Create(X, Op1, Zero);
1359 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1360 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1361 X->getType()->getScalarType()->isIntegerTy(1)) {
1362 Value *Zero = Constant::getNullValue(Op0->getType());
1363 return SelectInst::Create(X, Zero, Op1);
1367 std::swap(Op0, Op1);
1370 return Changed ? &I : 0;
1373 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1374 /// capable of providing pieces of a bswap. The subexpression provides pieces
1375 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1376 /// the expression came from the corresponding "byte swapped" byte in some other
1377 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1378 /// we know that the expression deposits the low byte of %X into the high byte
1379 /// of the bswap result and that all other bytes are zero. This expression is
1380 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1383 /// This function returns true if the match was unsuccessful and false if so.
1384 /// On entry to the function the "OverallLeftShift" is a signed integer value
1385 /// indicating the number of bytes that the subexpression is later shifted. For
1386 /// example, if the expression is later right shifted by 16 bits, the
1387 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1388 /// byte of ByteValues is actually being set.
1390 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1391 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1392 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1393 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1394 /// always in the local (OverallLeftShift) coordinate space.
1396 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1397 SmallVectorImpl<Value *> &ByteValues) {
1398 if (Instruction *I = dyn_cast<Instruction>(V)) {
1399 // If this is an or instruction, it may be an inner node of the bswap.
1400 if (I->getOpcode() == Instruction::Or) {
1401 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1403 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1407 // If this is a logical shift by a constant multiple of 8, recurse with
1408 // OverallLeftShift and ByteMask adjusted.
1409 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1411 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1412 // Ensure the shift amount is defined and of a byte value.
1413 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1416 unsigned ByteShift = ShAmt >> 3;
1417 if (I->getOpcode() == Instruction::Shl) {
1418 // X << 2 -> collect(X, +2)
1419 OverallLeftShift += ByteShift;
1420 ByteMask >>= ByteShift;
1422 // X >>u 2 -> collect(X, -2)
1423 OverallLeftShift -= ByteShift;
1424 ByteMask <<= ByteShift;
1425 ByteMask &= (~0U >> (32-ByteValues.size()));
1428 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1429 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1431 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1435 // If this is a logical 'and' with a mask that clears bytes, clear the
1436 // corresponding bytes in ByteMask.
1437 if (I->getOpcode() == Instruction::And &&
1438 isa<ConstantInt>(I->getOperand(1))) {
1439 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1440 unsigned NumBytes = ByteValues.size();
1441 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1442 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1444 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1445 // If this byte is masked out by a later operation, we don't care what
1447 if ((ByteMask & (1 << i)) == 0)
1450 // If the AndMask is all zeros for this byte, clear the bit.
1451 APInt MaskB = AndMask & Byte;
1453 ByteMask &= ~(1U << i);
1457 // If the AndMask is not all ones for this byte, it's not a bytezap.
1461 // Otherwise, this byte is kept.
1464 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1469 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1470 // the input value to the bswap. Some observations: 1) if more than one byte
1471 // is demanded from this input, then it could not be successfully assembled
1472 // into a byteswap. At least one of the two bytes would not be aligned with
1473 // their ultimate destination.
1474 if (!isPowerOf2_32(ByteMask)) return true;
1475 unsigned InputByteNo = countTrailingZeros(ByteMask);
1477 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1478 // is demanded, it needs to go into byte 0 of the result. This means that the
1479 // byte needs to be shifted until it lands in the right byte bucket. The
1480 // shift amount depends on the position: if the byte is coming from the high
1481 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1482 // low part, it must be shifted left.
1483 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1484 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1487 // If the destination byte value is already defined, the values are or'd
1488 // together, which isn't a bswap (unless it's an or of the same bits).
1489 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1491 ByteValues[DestByteNo] = V;
1495 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1496 /// If so, insert the new bswap intrinsic and return it.
1497 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1498 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1499 if (!ITy || ITy->getBitWidth() % 16 ||
1500 // ByteMask only allows up to 32-byte values.
1501 ITy->getBitWidth() > 32*8)
1502 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1504 /// ByteValues - For each byte of the result, we keep track of which value
1505 /// defines each byte.
1506 SmallVector<Value*, 8> ByteValues;
1507 ByteValues.resize(ITy->getBitWidth()/8);
1509 // Try to find all the pieces corresponding to the bswap.
1510 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1511 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1514 // Check to see if all of the bytes come from the same value.
1515 Value *V = ByteValues[0];
1516 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1518 // Check to make sure that all of the bytes come from the same value.
1519 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1520 if (ByteValues[i] != V)
1522 Module *M = I.getParent()->getParent()->getParent();
1523 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1524 return CallInst::Create(F, V);
1527 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1528 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1529 /// we can simplify this expression to "cond ? C : D or B".
1530 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1531 Value *C, Value *D) {
1532 // If A is not a select of -1/0, this cannot match.
1534 if (!match(A, m_SExt(m_Value(Cond))) ||
1535 !Cond->getType()->isIntegerTy(1))
1538 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1539 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1540 return SelectInst::Create(Cond, C, B);
1541 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1542 return SelectInst::Create(Cond, C, B);
1544 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1545 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1546 return SelectInst::Create(Cond, C, D);
1547 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1548 return SelectInst::Create(Cond, C, D);
1552 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1553 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1554 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1556 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1557 // if K1 and K2 are a one-bit mask.
1558 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1559 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1561 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1562 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1564 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1565 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1566 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1567 LAnd->getOpcode() == Instruction::And &&
1568 RAnd->getOpcode() == Instruction::And) {
1572 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1573 isKnownToBeAPowerOfTwo(LAnd->getOperand(1)) &&
1574 isKnownToBeAPowerOfTwo(RAnd->getOperand(1))) {
1575 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1576 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1577 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1578 isKnownToBeAPowerOfTwo(LAnd->getOperand(0)) &&
1579 isKnownToBeAPowerOfTwo(RAnd->getOperand(0))) {
1580 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1581 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1585 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1589 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1590 if (PredicatesFoldable(LHSCC, RHSCC)) {
1591 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1592 LHS->getOperand(1) == RHS->getOperand(0))
1593 LHS->swapOperands();
1594 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1595 LHS->getOperand(1) == RHS->getOperand(1)) {
1596 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1597 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1598 bool isSigned = LHS->isSigned() || RHS->isSigned();
1599 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1603 // handle (roughly):
1604 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1605 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1608 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1609 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1610 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1611 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1612 Value *A = 0, *B = 0;
1613 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1615 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1617 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1618 A = RHS->getOperand(1);
1620 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1621 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1622 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1624 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1626 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1627 A = LHS->getOperand(1);
1630 return Builder->CreateICmp(
1632 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1635 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1636 if (LHSCst == 0 || RHSCst == 0) return 0;
1638 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1639 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1640 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1641 Value *NewOr = Builder->CreateOr(Val, Val2);
1642 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1646 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1647 // iff C2 + CA == C1.
1648 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1649 ConstantInt *AddCst;
1650 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1651 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1652 return Builder->CreateICmpULE(Val, LHSCst);
1655 // From here on, we only handle:
1656 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1657 if (Val != Val2) return 0;
1659 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1660 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1661 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1662 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1663 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1666 // We can't fold (ugt x, C) | (sgt x, C2).
1667 if (!PredicatesFoldable(LHSCC, RHSCC))
1670 // Ensure that the larger constant is on the RHS.
1672 if (CmpInst::isSigned(LHSCC) ||
1673 (ICmpInst::isEquality(LHSCC) &&
1674 CmpInst::isSigned(RHSCC)))
1675 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1677 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1680 std::swap(LHS, RHS);
1681 std::swap(LHSCst, RHSCst);
1682 std::swap(LHSCC, RHSCC);
1685 // At this point, we know we have two icmp instructions
1686 // comparing a value against two constants and or'ing the result
1687 // together. Because of the above check, we know that we only have
1688 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1689 // icmp folding check above), that the two constants are not
1691 assert(LHSCst != RHSCst && "Compares not folded above?");
1694 default: llvm_unreachable("Unknown integer condition code!");
1695 case ICmpInst::ICMP_EQ:
1697 default: llvm_unreachable("Unknown integer condition code!");
1698 case ICmpInst::ICMP_EQ:
1699 if (LHS->getOperand(0) == RHS->getOperand(0)) {
1700 // if LHSCst and RHSCst differ only by one bit:
1701 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1702 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1704 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1705 if (Xor.isPowerOf2()) {
1706 Value *NegCst = Builder->getInt(~Xor);
1707 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1708 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1712 if (LHSCst == SubOne(RHSCst)) {
1713 // (X == 13 | X == 14) -> X-13 <u 2
1714 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1715 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1716 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1717 return Builder->CreateICmpULT(Add, AddCST);
1720 break; // (X == 13 | X == 15) -> no change
1721 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1722 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1724 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1725 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1726 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1730 case ICmpInst::ICMP_NE:
1732 default: llvm_unreachable("Unknown integer condition code!");
1733 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1734 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1735 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1737 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1738 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1739 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1740 return Builder->getTrue();
1742 case ICmpInst::ICMP_ULT:
1744 default: llvm_unreachable("Unknown integer condition code!");
1745 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1747 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1748 // If RHSCst is [us]MAXINT, it is always false. Not handling
1749 // this can cause overflow.
1750 if (RHSCst->isMaxValue(false))
1752 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1753 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1755 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1756 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1758 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1762 case ICmpInst::ICMP_SLT:
1764 default: llvm_unreachable("Unknown integer condition code!");
1765 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1767 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1768 // If RHSCst is [us]MAXINT, it is always false. Not handling
1769 // this can cause overflow.
1770 if (RHSCst->isMaxValue(true))
1772 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1773 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1775 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1776 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1778 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1782 case ICmpInst::ICMP_UGT:
1784 default: llvm_unreachable("Unknown integer condition code!");
1785 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1786 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1788 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1790 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1791 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1792 return Builder->getTrue();
1793 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1797 case ICmpInst::ICMP_SGT:
1799 default: llvm_unreachable("Unknown integer condition code!");
1800 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1801 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1803 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1805 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1806 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1807 return Builder->getTrue();
1808 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1816 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1817 /// instcombine, this returns a Value which should already be inserted into the
1819 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1820 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1821 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1822 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1823 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1824 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1825 // If either of the constants are nans, then the whole thing returns
1827 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1828 return Builder->getTrue();
1830 // Otherwise, no need to compare the two constants, compare the
1832 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1835 // Handle vector zeros. This occurs because the canonical form of
1836 // "fcmp uno x,x" is "fcmp uno x, 0".
1837 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1838 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1839 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1844 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1845 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1846 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1848 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1849 // Swap RHS operands to match LHS.
1850 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1851 std::swap(Op1LHS, Op1RHS);
1853 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1854 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1856 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1857 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1858 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1859 if (Op0CC == FCmpInst::FCMP_FALSE)
1861 if (Op1CC == FCmpInst::FCMP_FALSE)
1865 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1866 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1867 if (Op0Ordered == Op1Ordered) {
1868 // If both are ordered or unordered, return a new fcmp with
1869 // or'ed predicates.
1870 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1876 /// FoldOrWithConstants - This helper function folds:
1878 /// ((A | B) & C1) | (B & C2)
1884 /// when the XOR of the two constants is "all ones" (-1).
1885 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1886 Value *A, Value *B, Value *C) {
1887 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1891 ConstantInt *CI2 = 0;
1892 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1894 APInt Xor = CI1->getValue() ^ CI2->getValue();
1895 if (!Xor.isAllOnesValue()) return 0;
1897 if (V1 == A || V1 == B) {
1898 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1899 return BinaryOperator::CreateOr(NewOp, V1);
1905 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1906 bool Changed = SimplifyAssociativeOrCommutative(I);
1907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1909 if (Value *V = SimplifyOrInst(Op0, Op1, DL))
1910 return ReplaceInstUsesWith(I, V);
1912 // (A&B)|(A&C) -> A&(B|C) etc
1913 if (Value *V = SimplifyUsingDistributiveLaws(I))
1914 return ReplaceInstUsesWith(I, V);
1916 // See if we can simplify any instructions used by the instruction whose sole
1917 // purpose is to compute bits we don't care about.
1918 if (SimplifyDemandedInstructionBits(I))
1921 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1922 ConstantInt *C1 = 0; Value *X = 0;
1923 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1924 // iff (C1 & C2) == 0.
1925 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1926 (RHS->getValue() & C1->getValue()) != 0 &&
1928 Value *Or = Builder->CreateOr(X, RHS);
1930 return BinaryOperator::CreateAnd(Or,
1931 Builder->getInt(RHS->getValue() | C1->getValue()));
1934 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1935 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1937 Value *Or = Builder->CreateOr(X, RHS);
1939 return BinaryOperator::CreateXor(Or,
1940 Builder->getInt(C1->getValue() & ~RHS->getValue()));
1943 // Try to fold constant and into select arguments.
1944 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1945 if (Instruction *R = FoldOpIntoSelect(I, SI))
1948 if (isa<PHINode>(Op0))
1949 if (Instruction *NV = FoldOpIntoPhi(I))
1953 Value *A = 0, *B = 0;
1954 ConstantInt *C1 = 0, *C2 = 0;
1956 // (A | B) | C and A | (B | C) -> bswap if possible.
1957 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1958 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1959 match(Op1, m_Or(m_Value(), m_Value())) ||
1960 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1961 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1962 if (Instruction *BSwap = MatchBSwap(I))
1966 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1967 if (Op0->hasOneUse() &&
1968 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1969 MaskedValueIsZero(Op1, C1->getValue())) {
1970 Value *NOr = Builder->CreateOr(A, Op1);
1972 return BinaryOperator::CreateXor(NOr, C1);
1975 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1976 if (Op1->hasOneUse() &&
1977 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1978 MaskedValueIsZero(Op0, C1->getValue())) {
1979 Value *NOr = Builder->CreateOr(A, Op0);
1981 return BinaryOperator::CreateXor(NOr, C1);
1985 Value *C = 0, *D = 0;
1986 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1987 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1988 Value *V1 = 0, *V2 = 0;
1989 C1 = dyn_cast<ConstantInt>(C);
1990 C2 = dyn_cast<ConstantInt>(D);
1991 if (C1 && C2) { // (A & C1)|(B & C2)
1992 // If we have: ((V + N) & C1) | (V & C2)
1993 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1994 // replace with V+N.
1995 if (C1->getValue() == ~C2->getValue()) {
1996 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1997 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1998 // Add commutes, try both ways.
1999 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
2000 return ReplaceInstUsesWith(I, A);
2001 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
2002 return ReplaceInstUsesWith(I, A);
2004 // Or commutes, try both ways.
2005 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
2006 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2007 // Add commutes, try both ways.
2008 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
2009 return ReplaceInstUsesWith(I, B);
2010 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
2011 return ReplaceInstUsesWith(I, B);
2015 if ((C1->getValue() & C2->getValue()) == 0) {
2016 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2017 // iff (C1&C2) == 0 and (N&~C1) == 0
2018 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2019 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2020 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2021 return BinaryOperator::CreateAnd(A,
2022 Builder->getInt(C1->getValue()|C2->getValue()));
2023 // Or commutes, try both ways.
2024 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2025 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2026 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2027 return BinaryOperator::CreateAnd(B,
2028 Builder->getInt(C1->getValue()|C2->getValue()));
2030 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2031 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2032 ConstantInt *C3 = 0, *C4 = 0;
2033 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2034 (C3->getValue() & ~C1->getValue()) == 0 &&
2035 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2036 (C4->getValue() & ~C2->getValue()) == 0) {
2037 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2038 return BinaryOperator::CreateAnd(V2,
2039 Builder->getInt(C1->getValue()|C2->getValue()));
2044 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2045 // Don't do this for vector select idioms, the code generator doesn't handle
2047 if (!I.getType()->isVectorTy()) {
2048 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2050 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2052 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2054 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2058 // ((A&~B)|(~A&B)) -> A^B
2059 if ((match(C, m_Not(m_Specific(D))) &&
2060 match(B, m_Not(m_Specific(A)))))
2061 return BinaryOperator::CreateXor(A, D);
2062 // ((~B&A)|(~A&B)) -> A^B
2063 if ((match(A, m_Not(m_Specific(D))) &&
2064 match(B, m_Not(m_Specific(C)))))
2065 return BinaryOperator::CreateXor(C, D);
2066 // ((A&~B)|(B&~A)) -> A^B
2067 if ((match(C, m_Not(m_Specific(B))) &&
2068 match(D, m_Not(m_Specific(A)))))
2069 return BinaryOperator::CreateXor(A, B);
2070 // ((~B&A)|(B&~A)) -> A^B
2071 if ((match(A, m_Not(m_Specific(B))) &&
2072 match(D, m_Not(m_Specific(C)))))
2073 return BinaryOperator::CreateXor(C, B);
2075 // ((A|B)&1)|(B&-2) -> (A&1) | B
2076 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2077 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2078 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2079 if (Ret) return Ret;
2081 // (B&-2)|((A|B)&1) -> (A&1) | B
2082 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2083 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2084 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2085 if (Ret) return Ret;
2089 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
2090 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2091 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2092 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
2093 SI0->getOperand(1) == SI1->getOperand(1) &&
2094 (SI0->hasOneUse() || SI1->hasOneUse())) {
2095 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2097 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
2098 SI1->getOperand(1));
2102 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2103 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2104 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2105 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2106 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2107 I.getName()+".demorgan");
2108 return BinaryOperator::CreateNot(And);
2111 // Canonicalize xor to the RHS.
2112 bool SwappedForXor = false;
2113 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2114 std::swap(Op0, Op1);
2115 SwappedForXor = true;
2118 // A | ( A ^ B) -> A | B
2119 // A | (~A ^ B) -> A | ~B
2120 // (A & B) | (A ^ B)
2121 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2122 if (Op0 == A || Op0 == B)
2123 return BinaryOperator::CreateOr(A, B);
2125 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2126 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2127 return BinaryOperator::CreateOr(A, B);
2129 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2130 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2131 return BinaryOperator::CreateOr(Not, Op0);
2133 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2134 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2135 return BinaryOperator::CreateOr(Not, Op0);
2139 // A | ~(A | B) -> A | ~B
2140 // A | ~(A ^ B) -> A | ~B
2141 if (match(Op1, m_Not(m_Value(A))))
2142 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2143 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2144 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2145 B->getOpcode() == Instruction::Xor)) {
2146 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2148 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2149 return BinaryOperator::CreateOr(Not, Op0);
2153 std::swap(Op0, Op1);
2155 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2156 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2157 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2158 return ReplaceInstUsesWith(I, Res);
2160 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2161 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2162 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2163 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2164 return ReplaceInstUsesWith(I, Res);
2166 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2167 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2168 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2169 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2170 Type *SrcTy = Op0C->getOperand(0)->getType();
2171 if (SrcTy == Op1C->getOperand(0)->getType() &&
2172 SrcTy->isIntOrIntVectorTy()) {
2173 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
2175 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2176 // Only do this if the casts both really cause code to be
2178 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2179 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2180 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2181 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2184 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2185 // cast is otherwise not optimizable. This happens for vector sexts.
2186 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2187 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2188 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2189 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2191 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2192 // cast is otherwise not optimizable. This happens for vector sexts.
2193 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2194 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2195 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2196 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2201 // or(sext(A), B) -> A ? -1 : B where A is an i1
2202 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2203 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2204 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2205 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2206 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2208 // Note: If we've gotten to the point of visiting the outer OR, then the
2209 // inner one couldn't be simplified. If it was a constant, then it won't
2210 // be simplified by a later pass either, so we try swapping the inner/outer
2211 // ORs in the hopes that we'll be able to simplify it this way.
2212 // (X|C) | V --> (X|V) | C
2213 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2214 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2215 Value *Inner = Builder->CreateOr(A, Op1);
2216 Inner->takeName(Op0);
2217 return BinaryOperator::CreateOr(Inner, C1);
2220 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2221 // Since this OR statement hasn't been optimized further yet, we hope
2222 // that this transformation will allow the new ORs to be optimized.
2224 Value *X = 0, *Y = 0;
2225 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2226 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2227 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2228 Value *orTrue = Builder->CreateOr(A, C);
2229 Value *orFalse = Builder->CreateOr(B, D);
2230 return SelectInst::Create(X, orTrue, orFalse);
2234 return Changed ? &I : 0;
2237 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2238 bool Changed = SimplifyAssociativeOrCommutative(I);
2239 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2241 if (Value *V = SimplifyXorInst(Op0, Op1, DL))
2242 return ReplaceInstUsesWith(I, V);
2244 // (A&B)^(A&C) -> A&(B^C) etc
2245 if (Value *V = SimplifyUsingDistributiveLaws(I))
2246 return ReplaceInstUsesWith(I, V);
2248 // See if we can simplify any instructions used by the instruction whose sole
2249 // purpose is to compute bits we don't care about.
2250 if (SimplifyDemandedInstructionBits(I))
2253 // Is this a ~ operation?
2254 if (Value *NotOp = dyn_castNotVal(&I)) {
2255 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2256 if (Op0I->getOpcode() == Instruction::And ||
2257 Op0I->getOpcode() == Instruction::Or) {
2258 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2259 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2260 if (dyn_castNotVal(Op0I->getOperand(1)))
2261 Op0I->swapOperands();
2262 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2264 Builder->CreateNot(Op0I->getOperand(1),
2265 Op0I->getOperand(1)->getName()+".not");
2266 if (Op0I->getOpcode() == Instruction::And)
2267 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2268 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2271 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2272 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2273 if (isFreeToInvert(Op0I->getOperand(0)) &&
2274 isFreeToInvert(Op0I->getOperand(1))) {
2276 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2278 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2279 if (Op0I->getOpcode() == Instruction::And)
2280 return BinaryOperator::CreateOr(NotX, NotY);
2281 return BinaryOperator::CreateAnd(NotX, NotY);
2284 } else if (Op0I->getOpcode() == Instruction::AShr) {
2285 // ~(~X >>s Y) --> (X >>s Y)
2286 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2287 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2293 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2294 if (RHS->isOne() && Op0->hasOneUse())
2295 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2296 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2297 return CmpInst::Create(CI->getOpcode(),
2298 CI->getInversePredicate(),
2299 CI->getOperand(0), CI->getOperand(1));
2301 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2302 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2303 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2304 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2305 Instruction::CastOps Opcode = Op0C->getOpcode();
2306 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2307 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2308 Op0C->getDestTy()))) {
2309 CI->setPredicate(CI->getInversePredicate());
2310 return CastInst::Create(Opcode, CI, Op0C->getType());
2316 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2317 // ~(c-X) == X-c-1 == X+(-c-1)
2318 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2319 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2320 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2321 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2322 ConstantInt::get(I.getType(), 1));
2323 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2326 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2327 if (Op0I->getOpcode() == Instruction::Add) {
2328 // ~(X-c) --> (-c-1)-X
2329 if (RHS->isAllOnesValue()) {
2330 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2331 return BinaryOperator::CreateSub(
2332 ConstantExpr::getSub(NegOp0CI,
2333 ConstantInt::get(I.getType(), 1)),
2334 Op0I->getOperand(0));
2335 } else if (RHS->getValue().isSignBit()) {
2336 // (X + C) ^ signbit -> (X + C + signbit)
2337 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2338 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2341 } else if (Op0I->getOpcode() == Instruction::Or) {
2342 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2343 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2344 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2345 // Anything in both C1 and C2 is known to be zero, remove it from
2347 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2348 NewRHS = ConstantExpr::getAnd(NewRHS,
2349 ConstantExpr::getNot(CommonBits));
2351 I.setOperand(0, Op0I->getOperand(0));
2352 I.setOperand(1, NewRHS);
2355 } else if (Op0I->getOpcode() == Instruction::LShr) {
2356 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2360 if (Op0I->hasOneUse() &&
2361 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2362 E1->getOpcode() == Instruction::Xor &&
2363 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2364 // fold (C1 >> C2) ^ C3
2365 ConstantInt *C2 = Op0CI, *C3 = RHS;
2366 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2367 FoldConst ^= C3->getValue();
2368 // Prepare the two operands.
2369 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2370 Opnd0->takeName(Op0I);
2371 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2372 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2374 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2380 // Try to fold constant and into select arguments.
2381 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2382 if (Instruction *R = FoldOpIntoSelect(I, SI))
2384 if (isa<PHINode>(Op0))
2385 if (Instruction *NV = FoldOpIntoPhi(I))
2389 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2392 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2393 if (A == Op0) { // B^(B|A) == (A|B)^B
2394 Op1I->swapOperands();
2396 std::swap(Op0, Op1);
2397 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2398 I.swapOperands(); // Simplified below.
2399 std::swap(Op0, Op1);
2401 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2403 if (A == Op0) { // A^(A&B) -> A^(B&A)
2404 Op1I->swapOperands();
2407 if (B == Op0) { // A^(B&A) -> (B&A)^A
2408 I.swapOperands(); // Simplified below.
2409 std::swap(Op0, Op1);
2414 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2417 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2418 Op0I->hasOneUse()) {
2419 if (A == Op1) // (B|A)^B == (A|B)^B
2421 if (B == Op1) // (A|B)^B == A & ~B
2422 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2423 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2425 if (A == Op1) // (A&B)^A -> (B&A)^A
2427 if (B == Op1 && // (B&A)^A == ~B & A
2428 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2429 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2434 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2435 if (Op0I && Op1I && Op0I->isShift() &&
2436 Op0I->getOpcode() == Op1I->getOpcode() &&
2437 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2438 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
2440 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2442 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2443 Op1I->getOperand(1));
2447 Value *A, *B, *C, *D;
2448 // (A & B)^(A | B) -> A ^ B
2449 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2450 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2451 if ((A == C && B == D) || (A == D && B == C))
2452 return BinaryOperator::CreateXor(A, B);
2454 // (A | B)^(A & B) -> A ^ B
2455 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2456 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2457 if ((A == C && B == D) || (A == D && B == C))
2458 return BinaryOperator::CreateXor(A, B);
2462 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2463 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2464 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2465 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2466 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2467 LHS->getOperand(1) == RHS->getOperand(0))
2468 LHS->swapOperands();
2469 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2470 LHS->getOperand(1) == RHS->getOperand(1)) {
2471 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2472 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2473 bool isSigned = LHS->isSigned() || RHS->isSigned();
2474 return ReplaceInstUsesWith(I,
2475 getNewICmpValue(isSigned, Code, Op0, Op1,
2480 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2481 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2482 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2483 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2484 Type *SrcTy = Op0C->getOperand(0)->getType();
2485 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2486 // Only do this if the casts both really cause code to be generated.
2487 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2489 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2491 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2492 Op1C->getOperand(0), I.getName());
2493 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2498 return Changed ? &I : 0;